Programs & Examples On #Gherkin

Gherkin is the language used to write specifications for Cucumber, Specflow and similar BDD frameworks. It is a business-readable, domain-specific language that lets you describe your software’s behaviour without detailing how that behaviour is implemented.

incompatible character encodings: ASCII-8BIT and UTF-8

I encountered the error while migrating an app from Ruby 1.8.7 to 1.9.3 and it only occured in production. It turned out that I had some leftovers in my Memcache store. The now encoding sensitive Ruby 1.9.3 version of my app tried to mix old ASCII-8BIT values with new UTF-8.

It was as simple as flushing the cache to fix it for me.

Subtracting Dates in Oracle - Number or Interval Datatype?

Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.

When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.

An example of a DATE subtraction resulting in a positive integer difference:

select date '2009-08-07' - date '2008-08-08' from dual;

Results in:

DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
                              364

select dump(date '2009-08-07' - date '2008-08-08') from dual;

DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0

Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.

An example of a DATE subtraction resulting in a negative integer difference:

select date '1000-08-07' - date '2008-08-08' from dual;

Results in:

DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
                          -368160

select dump(date '1000-08-07' - date '2008-08-08') from dual;

DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0

Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.

An example of a DATE subtraction resulting in a decimal difference:

select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;

TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
                                                                             .25

The difference between those 2 dates is 0.25 days or 6 hours.

select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;

DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0

Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.

Hope this helps anyone who was wondering how a DATE subtraction is actually stored.


You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:

SQL> SELECT DUMP(SYSDATE - start_date) from test;

DUMP(SYSDATE-START_DATE)
-------------------------------------- 
Typ=14 Len=8: 188,10,0,0,223,65,1,0

You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function

For example:

SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;

(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000

SQL> SELECT (SYSDATE - start_date) from test;

(SYSDATE-START_DATE)
--------------------
           2748.9515

SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;

NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000

SQL>

Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

UPDATE: I've gotten a few upvotes on this lately, so I figured I'd let people know the advice I give below isn't the best. Since I originally started mucking about with doing Entity Framework on old keyless databases, I've come to realize that the best thing you can do BY FAR is do it by reverse code-first. There are a few good articles out there on how to do this. Just follow them, and then when you want to add a key to it, use data annotations to "fake" the key.

For instance, let's say I know my table Orders, while it doesn't have a primary key, is assured to only ever have one order number per customer. Since those are the first two columns on the table, I'd set up the code first classes to look like this:

    [Key, Column(Order = 0)]
    public Int32? OrderNumber { get; set; }

    [Key, Column(Order = 1)]
    public String Customer { get; set; }

By doing this, you're basically faked EF into believing that there's a clustered key composed of OrderNumber and Customer. This will allow you to do inserts, updates, etc on your keyless table.

If you're not too familiar with doing reverse Code First, go and find a good tutorial on Entity Framework Code First. Then go find one on Reverse Code First (which is doing Code First with an existing database). Then just come back here and look at my key advice again. :)

Original Answer:

First: as others have said, the best option is to add a primary key to the table. Full stop. If you can do this, read no further.

But if you can't, or just hate yourself, there's a way to do it without the primary key.

In my case, I was working with a legacy system (originally flat files on a AS400 ported to Access and then ported to T-SQL). So I had to find a way. This is my solution. The following worked for me using Entity Framework 6.0 (the latest on NuGet as of this writing).

  1. Right-click on your .edmx file in the Solution Explorer. Choose "Open With..." and then select "XML (Text) Editor". We're going to be hand-editing the auto-generated code here.

  2. Look for a line like this:
    <EntitySet Name="table_name" EntityType="MyModel.Store.table_name" store:Type="Tables" store:Schema="dbo" store:Name="table_nane">

  3. Remove store:Name="table_name" from the end.

  4. Change store:Schema="whatever" to Schema="whatever"

  5. Look below that line and find the <DefiningQuery> tag. It will have a big ol' select statement in it. Remove the tag and it's contents.

  6. Now your line should look something like this:
    <EntitySet Name="table_name" EntityType="MyModel.Store.table_name" store:Type="Tables" Schema="dbo" />

  7. We have something else to change. Go through your file and find this:
    <EntityType Name="table_name">

  8. Nearby you'll probably see some commented text warning you that it didn't have a primary key identified, so the key has been inferred and the definition is a read-only table/view. You can leave it or delete it. I deleted it.

  9. Below is the <Key> tag. This is what Entity Framework is going to use to do insert/update/deletes. SO MAKE SURE YOU DO THIS RIGHT. The property (or properties) in that tag need to indicate a uniquely identifiable row. For instance, let's say I know my table orders, while it doesn't have a primary key, is assured to only ever have one order number per customer.

So mine looks like:

<EntityType Name="table_name">
              <Key>
                <PropertyRef Name="order_numbers" />
                <PropertyRef Name="customer_name" />
              </Key>

Seriously, don't do this wrong. Let's say that even though there should never be duplicates, somehow two rows get into my system with the same order number and customer name. Whooops! That's what I get for not using a key! So I use Entity Framework to delete one. Because I know the duplicate is the only order put in today, I do this:

var duplicateOrder = myModel.orders.First(x => x.order_date == DateTime.Today);
myModel.orders.Remove(duplicateOrder);

Guess what? I just deleted both the duplicate AND the original! That's because I told Entity Framework that order_number/cutomer_name was my primary key. So when I told it to remove duplicateOrder, what it did in the background was something like:

DELETE FROM orders
WHERE order_number = (duplicateOrder's order number)
AND customer_name = (duplicateOrder's customer name)

And with that warning... you should now be good to go!

jQuery - Call ajax every 10 seconds

You could try setInterval() instead:

var i = setInterval(function(){
   //Call ajax here
},10000)

Fatal error: Call to a member function bind_param() on boolean

Sometimes explicitly stating your table column names (especially in an insert query) may help. For example, the query:

INSERT INTO tableName(param1, param2, param3) VALUES(?, ?, ?)

may work better as opposed to:

INSERT INTO tableName VALUES(?, ?, ?)

List file using ls command in Linux with full path

You could easily use the following to list only files:

ls -d -1 $PWD/*.*

the following to list directories:

ls -d -1 $PWD/**

the following to list everything (files/dirs):

ls -d -1 $PWD/**/*

More helpful options:

-d list directories not their content

-R recursive

-1 list one file per line

-l use long listing format

-a list all including entries starting with . and ..

-A list all but don't list implied . and ..

for more info, just type the following

ls --help 

Creating hard and soft links using PowerShell

You can use this utility:

c:\Windows\system32\fsutil.exe create hardlink

Create an array with random values

A little late to the party, but I use randojs.com for randomness because it makes stuff like this super easy. You can get a randomly shuffled array of numbers from 0 through 39 just like this:

_x000D_
_x000D_
console.log(randoSequence(40));
_x000D_
<script src="https://randojs.com/1.0.0.js"></script>
_x000D_
_x000D_
_x000D_

No fuss with the logistics of it all- plus it's super readable and easy to understand :)

Convert True/False value read from file to boolean

If you want to be case-insensitive, you can just do:

b = True if bool_str.lower() == 'true' else False

Example usage:

>>> bool_str = 'False'
>>> b = True if bool_str.lower() == 'true' else False
>>> b
False
>>> bool_str = 'true'
>>> b = True if bool_str.lower() == 'true' else False
>>> b
True

How to write a:hover in inline CSS?

I had to avoid javascript, but could go with server side code.

so I generated an id, created a style block, generated the link with that id. Yes its valid HTML.

_x000D_
_x000D_
a {_x000D_
  text-decoration: none;_x000D_
  color: blue; _x000D_
}_x000D_
_x000D_
a:hover {_x000D_
  color: blue;_x000D_
  font-weight: bold;_x000D_
}
_x000D_
<!-- some code in the interpreter you use, to generate the data-hover id -->_x000D_
<style>_x000D_
  a[data-hover="rnd-id-123"] { color: green;  } _x000D_
  a[data-hover="rnd-id-123"]:hover { color: red; }_x000D_
</style>_x000D_
<a data-hover="rnd-id-123">some link 1</a>_x000D_
_x000D_
<br>_x000D_
_x000D_
<!-- some code in the interpreter you use, to generate the data-hover id -->_x000D_
<style>_x000D_
  a[data-hover="rnd-id-456"] { color: purple;  }_x000D_
  a[data-hover="rnd-id-456"]:hover { color: orange; }_x000D_
</style>_x000D_
<a data-hover="rnd-id-456">some link 2</a>
_x000D_
_x000D_
_x000D_

URL encoding the space character: + or %20?

I would recommend %20.

Are you hard-coding them?

This is not very consistent across languages, though. If I'm not mistaken, in PHP urlencode() treats spaces as + whereas Python's urlencode() treats them as %20.

EDIT:

It seems I'm mistaken. Python's urlencode() (at least in 2.7.2) uses quote_plus() instead of quote() and thus encodes spaces as "+". It seems also that the W3C recommendation is the "+" as per here: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1

And in fact, you can follow this interesting debate on Python's own issue tracker about what to use to encode spaces: http://bugs.python.org/issue13866.

EDIT #2:

I understand that the most common way of encoding " " is as "+", but just a note, it may be just me, but I find this a bit confusing:

import urllib
print(urllib.urlencode({' ' : '+ '})

>>> '+=%2B+'

Spring security CORS Filter

There's 8 hours of my life I will never get back...

Make sure that you set both Exposed Headers AND Allowed Headers in your CorsConfiguration

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
    configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
    configuration.setExposedHeaders(Arrays.asList("Authorization", "content-type"));
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "content-type"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

How do you initialise a dynamic array in C++?

you have to initialize it "by hand" :

char* c = new char[length];
for(int i = 0;i<length;i++)
    c[i]='\0';

How to center a Window in Java?

Actually frame.getHeight() and getwidth() doesnt return values , check it by System.out.println(frame.getHeight()); directly put the values for width and height ,then it will work fine in center. eg: as below

Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();      
int x=(int)((dimension.getWidth() - 450)/2);
int y=(int)((dimension.getHeight() - 450)/2);
jf.setLocation(x, y);  

both 450 is my frame width n height

How can I make my match non greedy in vim?

With \v (as suggested in several comments)

:%s/\v(style|class)\=".{-}"//g

Just get column names from hive table

Best way to do this is setting the below property:

set hive.cli.print.header=true;
set hive.resultset.use.unique.column.names=false;

How do I use a delimiter with Scanner.useDelimiter in Java?

For example:

String myInput = null;
Scanner myscan = new Scanner(System.in).useDelimiter("\\n");
System.out.println("Enter your input: ");
myInput = myscan.next();
System.out.println(myInput);

This will let you use Enter as a delimiter.

Thus, if you input:

Hello world (ENTER)

it will print 'Hello World'.

Add a Progress Bar in WebView

The best approch which worked for me is

webView.setWebViewClient(new WebViewClient() {

    @Override public void onPageStarted(WebView view, String url, Bitmap favicon) {
          super.onPageStarted(view, url, favicon);
          mProgressBar.setVisibility(ProgressBar.VISIBLE);
          webView.setVisibility(View.INVISIBLE);
        }

    @Override public void onPageCommitVisible(WebView view, String url) {
      super.onPageCommitVisible(view, url);
      mProgressBar.setVisibility(ProgressBar.GONE);
      webView.setVisibility(View.VISIBLE);
      isWebViewLoadingFirstPage=false;
    }
}

How to add days to the current date?

Two or three ways (depends what you want), say we are at Current Date is (in tsql code) -

DECLARE @myCurrentDate datetime = '11Apr2014 10:02:25 AM'

(BTW - did you mean 11April2014 or 04Nov2014 in your original post? hard to tell, as datetime is culture biased. In Israel 11/04/2015 means 11April2014. I know in the USA 11/04/2014 it means 04Nov2014. tommatoes tomatos I guess)

  1. SELECT @myCurrentDate + 360 - by default datetime calculations followed by + (some integer), just add that in days. So you would get 2015-04-06 10:02:25.000 - not exactly what you wanted, but rather just a ball park figure for a close date next year.

  2. SELECT DateADD(DAY, 365, @myCurrentDate) or DateADD(dd, 365, @myCurrentDate) will give you '2015-04-11 10:02:25.000'. These two are syntatic sugar (exacly the same). This is what you wanted, I should think. But it's still wrong, because if the date was a "3 out of 4" year (say DECLARE @myCurrentDate datetime = '11Apr2011 10:02:25 AM') you would get '2012-04-10 10:02:25.000'. because 2012 had 366 days, remember? (29Feb2012 consumes an "extra" day. Almost every fourth year has 29Feb).

  3. So what I think you meant was

    SELECT DateADD(year, 1, @myCurrentDate)
    

    which gives 2015-04-11 10:02:25.000.

  4. or better yet

    SELECT DateADD(year, 1, DateADD(day, DateDiff(day, 0, @myCurrentDate), 0))
    

    which gives you 2015-04-11 00:00:00.000 (because datetime also has time, right?). Subtle, ah?

CSS align images and text on same line

try to insert your img inside your h4 DEMO

<h4 class='liketext'><img style='height: 24px; width: 24px; margin-right: 4px;' src='design/like.png'/>$likes</h4>
<h4 class='liketext'> <img style='height: 24px; width: 24px; margin-right: 4px;' src='design/dislike.png'/>$dislikes</h4>?

How to merge two json string in Python?

Merging json objects is fairly straight forward but has a few edge cases when dealing with key collisions. The biggest issues have to do with one object having a value of a simple type and the other having a complex type (Array or Object). You have to decide how you want to implement that. Our choice when we implemented this for json passed to chef-solo was to merge Objects and use the first source Object's value in all other cases.

This was our solution:

from collections import Mapping
import json


original = json.loads(jsonStringA)
addition = json.loads(jsonStringB)

for key, value in addition.iteritems():
    if key in original:
        original_value = original[key]
        if isinstance(value, Mapping) and isinstance(original_value, Mapping):
            merge_dicts(original_value, value)
        elif not (isinstance(value, Mapping) or 
                  isinstance(original_value, Mapping)):
            original[key] = value
        else:
            raise ValueError('Attempting to merge {} with value {}'.format(
                key, original_value))
    else:
        original[key] = value

You could add another case after the first case to check for lists if you want to merge those as well, or for specific cases when special keys are encountered.

AngularJS dynamic routing

As of AngularJS 1.1.3, you can now do exactly what you want using the new catch-all parameter.

https://github.com/angular/angular.js/commit/7eafbb98c64c0dc079d7d3ec589f1270b7f6fea5

From the commit:

This allows routeProvider to accept parameters that matches substrings even when they contain slashes if they are prefixed with an asterisk instead of a colon. For example, routes like edit/color/:color/largecode/*largecode will match with something like this http://appdomain.com/edit/color/brown/largecode/code/with/slashs.

I have tested it out myself (using 1.1.5) and it works great. Just keep in mind that each new URL will reload your controller, so to keep any kind of state, you may need to use a custom service.

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

Setting core.filemode to false does work, but make sure the settings in ~/.gitconfig aren't being overridden by those in .git/config.

How can I override the OnBeforeUnload dialog and replace it with my own?

While there isn't anything you can do about the box in some circumstances, you can intercept someone clicking on a link. For me, this was worth the effort for most scenarios and as a fallback, I've left the unload event.

I've used Boxy instead of the standard jQuery Dialog, it is available here: http://onehackoranother.com/projects/jquery/boxy/

$(':input').change(function() {
    if(!is_dirty){
        // When the user changes a field on this page, set our is_dirty flag.
        is_dirty = true;
    }
});

$('a').mousedown(function(e) {
    if(is_dirty) {
        // if the user navigates away from this page via an anchor link, 
        //    popup a new boxy confirmation.
        answer = Boxy.confirm("You have made some changes which you might want to save.");
    }
});

window.onbeforeunload = function() {
if((is_dirty)&&(!answer)){
            // call this if the box wasn't shown.
    return 'You have made some changes which you might want to save.';
    }
};

You could attach to another event, and filter more on what kind of anchor was clicked, but this works for me and what I want to do and serves as an example for others to use or improve. Thought I would share this for those wanting this solution.

I have cut out code, so this may not work as is.

How do you use bcrypt for hashing passwords in PHP?

Version 5.5 of PHP will have built-in support for BCrypt, the functions password_hash() and password_verify(). Actually these are just wrappers around the function crypt(), and shall make it easier to use it correctly. It takes care of the generation of a safe random salt, and provides good default values.

The easiest way to use this functions will be:

$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
$isPasswordCorrect = password_verify($password, $existingHashFromDb);

This code will hash the password with BCrypt (algorithm 2y), generates a random salt from the OS random source, and uses the default cost parameter (at the moment this is 10). The second line checks, if the user entered password matches an already stored hash-value.

Should you want to change the cost parameter, you can do it like this, increasing the cost parameter by 1, doubles the needed time to calculate the hash value:

$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 11));

In contrast to the "cost" parameter, it is best to omit the "salt" parameter, because the function already does its best to create a cryptographically safe salt.

For PHP version 5.3.7 and later, there exists a compatibility pack, from the same author that made the password_hash() function. For PHP versions before 5.3.7 there is no support for crypt() with 2y, the unicode safe BCrypt algorithm. One could replace it instead with 2a, which is the best alternative for earlier PHP versions.

WHERE statement after a UNION in SQL?

If you want to apply the WHERE clause to the result of the UNION, then you have to embed the UNION in the FROM clause:

SELECT *
  FROM (SELECT * FROM TableA
        UNION
        SELECT * FROM TableB
       ) AS U
 WHERE U.Col1 = ...

I'm assuming TableA and TableB are union-compatible. You could also apply a WHERE clause to each of the individual SELECT statements in the UNION, of course.

Convert List<String> to List<Integer> directly

You can use the Lambda functions of Java 8 to achieve this without looping

    String string = "1, 2, 3, 4";
    List<Integer> list = Arrays.asList(string.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());

How to exit in Node.js

Just a note that using process.exit([number]) is not recommended practice.

Calling process.exit() will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations to process.stdout and process.stderr.

In most situations, it is not actually necessary to call process.exit() explicitly. The Node.js process will exit on its own if there is no additional work pending in the event loop. The process.exitCode property can be set to tell the process which exit code to use when the process exits gracefully.

For instance, the following example illustrates a misuse of the process.exit() method that could lead to data printed to stdout being truncated and lost:

// This is an example of what *not* to do:
if (someConditionNotMet()) {
  printUsageToStdout();
  process.exit(1);
}

The reason this is problematic is because writes to process.stdout in Node.js are sometimes asynchronous and may occur over multiple ticks of the Node.js event loop. Calling process.exit(), however, forces the process to exit before those additional writes to stdout can be performed.

Rather than calling process.exit() directly, the code should set the process.exitCode and allow the process to exit naturally by avoiding scheduling any additional work for the event loop:

// How to properly set the exit code while letting
// the process exit gracefully.
if (someConditionNotMet()) {
  printUsageToStdout();  
  process.exitCode = 1;
}

MySQL - Trigger for updating same table after insert

This is how I update a row in the same table on insert

activationCode and email are rows in the table USER. On insert I don't specify a value for activationCode, it will be created on the fly by MySQL.

Change username with your MySQL username and db_name with your db name.

CREATE DEFINER=`username`@`localhost` 
       TRIGGER `db_name`.`user_BEFORE_INSERT` 
       BEFORE INSERT ON `user` 
       FOR EACH ROW
         BEGIN
            SET new.activationCode = MD5(new.email);
         END

How to give a Linux user sudo access?

You need run visudo and in the editor that it opens write:

igor    ALL=(ALL) ALL

That line grants all permissions to user igor.

If you want permit to run only some commands, you need to list them in the line:

igor    ALL=(ALL) /bin/kill, /bin/ps

Does adding a duplicate value to a HashSet/HashMap replace the previous value

HashMap basically contains Entry which subsequently contains Key(Object) and Value(Object).Internally HashSet are HashMap and HashMap do replace values as some of you already pointed..but does it really replaces the keys???No ..and that is the trick here. HashMap keeps its value as key in the underlying HashMap and value is just a dummy object.So if u try to reinsert same Value in HashMap(Key in underlying Map).It just replaces the dummy value and not the Key(Value for HashSet).

Look at the below code for HashSet Class:

public boolean  [More ...] add(E e) {

   return map.put(e, PRESENT)==null;
}

Here e is the value for HashSet but key for underlying map.and key is never replaced. Hope i am able to clear the confusion.

How to print SQL statement in codeigniter model

You can display the ActiveRecord generated SQL:

Before the query runs:

$this->db->_compile_select(); 

And after it has run:

$this->db->last_query(); 

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

Based on the syntax provided

 Select * Where Amount = min(Amount)

You could do using:

 library(sqldf)

Using @Kara Woo's example df

  sqldf("select * from df where Amount in (select min(Amount) from df)")
  #Name Amount
 #1    B    120
 #2    E    120

How to properly use unit-testing's assertRaises() with NoneType objects?

The problem is the TypeError gets raised 'before' assertRaises gets called since the arguments to assertRaises need to be evaluated before the method can be called. You need to pass a lambda expression like:

self.assertRaises(TypeError, lambda: self.testListNone[:1])

How can I multiply all items in a list together with Python?

Found this question today but I noticed that it does not have the case where there are None's in the list. So, the complete solution would be:

from functools import reduce

a = [None, 1, 2, 3, None, 4]
print(reduce(lambda x, y: (x if x else 1) * (y if y else 1), a))

In the case of addition, we have:

print(reduce(lambda x, y: (x if x else 0) + (y if y else 0), a))

C# - Winforms - Global Variables

They have already answered how to use a global variable.

I will tell you why the use of global variables is a bad idea as a result of this question carried out in stackoverflow in Spanish.

Explicit translation of the text in Spanish:

Impact of the change

The problem with global variables is that they create hidden dependencies. When it comes to large applications, you yourself do not know / remember / you are clear about the objects you have and their relationships.

So, you can not have a clear notion of how many objects your global variable is using. And if you want to change something of the global variable, for example, the meaning of each of its possible values, or its type? How many classes or compilation units will that change affect? If the amount is small, it may be worth making the change. If the impact will be great, it may be worth looking for another solution.

But what is the impact? Because a global variable can be used anywhere in the code, it can be very difficult to measure it.

In addition, always try to have a variable with the shortest possible life time, so that the amount of code that makes use of that variable is the minimum possible, and thus better understand its purpose, and who modifies it.

A global variable lasts for the duration of the program, and therefore, anyone can use the variable, either to read it, or even worse, to change its value, making it more difficult to know what value the variable will have at any given program point. .

Order of destruction

Another problem is the order of destruction. Variables are always destroyed in reverse order of their creation, whether they are local or global / static variables (an exception is the primitive types, int,enums, etc., which are never destroyed if they are global / static until they end the program).

The problem is that it is difficult to know the order of construction of the global (or static) variables. In principle, it is indeterminate.

If all your global / static variables are in a single compilation unit (that is, you only have a .cpp), then the order of construction is the same as the writing one (that is, variables defined before, are built before).

But if you have more than one .cpp each with its own global / static variables, the global construction order is indeterminate. Of course, the order in each compilation unit (each .cpp) in particular, is respected: if the global variableA is defined before B,A will be built before B, but It is possible that between A andB variables of other .cpp are initialized. For example, if you have three units with the following global / static variables:

Image1

In the executable it could be created in this order (or in any other order as long as the relative order is respected within each .cpp):

Image2

Why is this important? Because if there are relations between different static global objects, for example, that some use others in their destructors, perhaps, in the destructor of a global variable, you use another global object from another compilation unit that turns out to be already destroyed ( have been built later).

Hidden dependencies and * test cases *

I tried to find the source that I will use in this example, but I can not find it (anyway, it was to exemplify the use of singletons, although the example is applicable to global and static variables). Hidden dependencies also create new problems related to controlling the behavior of an object, if it depends on the state of a global variable.

Imagine you have a payment system, and you want to test it to see how it works, since you need to make changes, and the code is from another person (or yours, but from a few years ago). You open a new main, and you call the corresponding function of your global object that provides a bank payment service with a card, and it turns out that you enter your data and they charge you. How, in a simple test, have I used a production version? How can I do a simple payment test?

After asking other co-workers, it turns out that you have to "mark true", a global bool that indicates whether we are in test mode or not, before beginning the collection process. Your object that provides the payment service depends on another object that provides the mode of payment, and that dependency occurs in an invisible way for the programmer.

In other words, the global variables (or singletones), make it impossible to pass to "test mode", since global variables can not be replaced by "testing" instances (unless you modify the code where said code is created or defined). global variable, but we assume that the tests are done without modifying the mother code).

Solution

This is solved by means of what is called * dependency injection *, which consists in passing as a parameter all the dependencies that an object needs in its constructor or in the corresponding method. In this way, the programmer ** sees ** what has to happen to him, since he has to write it in code, making the developers gain a lot of time.

If there are too many global objects, and there are too many parameters in the functions that need them, you can always group your "global objects" into a class, style * factory *, that builds and returns the instance of the "global object" (simulated) that you want , passing the factory as a parameter to the objects that need the global object as dependence.

If you pass to test mode, you can always create a testing factory (which returns different versions of the same objects), and pass it as a parameter without having to modify the target class.

But is it always bad?

Not necessarily, there may be good uses for global variables. For example, constant values ??(the PI value). Being a constant value, there is no risk of not knowing its value at a given point in the program by any type of modification from another module. In addition, constant values ??tend to be primitive and are unlikely to change their definition.

It is more convenient, in this case, to use global variables to avoid having to pass the variables as parameters, simplifying the signatures of the functions.

Another can be non-intrusive "global" services, such as a logging class (saving what happens in a file, which is usually optional and configurable in a program, and therefore does not affect the application's nuclear behavior), or std :: cout,std :: cin or std :: cerr, which are also global objects.

Any other thing, even if its life time coincides almost with that of the program, always pass it as a parameter. Even the variable could be global in a module, only in it without any other having access, but that, in any case, the dependencies are always present as parameters.

Answer by: Peregring-lk

How can I add a variable to console.log?

You can pass multiple args to log:

console.log("story", name, "story");

How to use sed/grep to extract text between two words?

You can use \1 (refer to http://www.grymoire.com/Unix/Sed.html#uh-4):

echo "Hello is a String" | sed 's/Hello\(.*\)String/\1/g'

The contents that is inside the brackets will be stored as \1.

Removing duplicates from a list of lists

Strangely, the answers above removes the 'duplicates' but what if I want to remove the duplicated value also?? The following should be useful and does not create a new object in memory!

def dictRemoveDuplicates(self):
    a=[[1,'somevalue1'],[1,'somevalue2'],[2,'somevalue1'],[3,'somevalue4'],[5,'somevalue5'],[5,'somevalue1'],[5,'somevalue1'],[5,'somevalue8'],[6,'somevalue9'],[6,'somevalue0'],[6,'somevalue1'],[7,'somevalue7']]


print(a)
temp = 0
position = -1
for pageNo, item in a:
    position+=1
    if pageNo != temp:
        temp = pageNo
        continue
    else:
        a[position] = 0
        a[position - 1] = 0
a = [x for x in a if x != 0]         
print(a)

and the o/p is:

[[1, 'somevalue1'], [1, 'somevalue2'], [2, 'somevalue1'], [3, 'somevalue4'], [5, 'somevalue5'], [5, 'somevalue1'], [5, 'somevalue1'], [5, 'somevalue8'], [6, 'somevalue9'], [6, 'somevalue0'], [6, 'somevalue1'], [7, 'somevalue7']]
[[2, 'somevalue1'], [3, 'somevalue4'], [7, 'somevalue7']]

Max tcp/ip connections on Windows Server 2008

How many thousands of users?

I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.

Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.

If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.

Edited to add details from the comment below...

If you're already thinking of multiple servers I'd take the following approach.

  1. Use the free tools that I link to and prove to yourself that you can create a reasonable number of connections onto your target OS (beware of the Windows limits on dynamic ports which may cause your client connections to fail, search for MAX_USER_PORT).

  2. during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html

Git Stash vs Shelve in IntelliJ IDEA

git shelve doesn't exist in Git.

Only git stash:

  • when you want to record the current state of the working directory and the index, but want to go back to a clean working directory.
  • which saves your local modifications away and reverts the working directory to match the HEAD commit.

You had a 2008 old project git shelve to isolate modifications in a branch, but that wouldn't be very useful nowadays.

As documented in Intellij IDEA shelve dialog, the feature "shelving and unshelving" is not linked to a VCS (Version Control System tool) but to the IDE itself, to temporarily storing pending changes you have not committed yet in changelist.

Note that since Git 2.13 (Q2 2017), you now can stash individual files too.

package R does not exist

I forgot to add the "name" of my "package" at the top of my java class. Check if yours is actually added.

Cannot find libcrypto in Ubuntu

I solved this on 12.10 by installing libssl-dev.

sudo apt-get install libssl-dev

SQL select only rows with max value on a column

NOT mySQL, but for other people finding this question and using SQL, another way to resolve the problem is using Cross Apply in MS SQL

WITH DocIds AS (SELECT DISTINCT id FROM docs)

SELECT d2.id, d2.rev, d2.content
FROM DocIds d1
CROSS APPLY (
  SELECT Top 1 * FROM docs d
  WHERE d.id = d1.id
  ORDER BY rev DESC
) d2

Here's an example in SqlFiddle

MySQL - ERROR 1045 - Access denied

  1. Go to mysql console
  2. Enter use mysql;
  3. UPDATE mysql.user SET Password= PASSWORD ('') WHERE User='root' FLUSH PRIVILEGES; exit PASSWORD ('') is must empty
  4. Then go to wamp/apps/phpmyadmin../config.inc.php
  5. Find $cfg ['Servers']['$I']['password']='root';
  6. Replace the ['password'] with ['your old password']
  7. Save the file
  8. Restart the all services and goto localhost/phpmyadmin

APK signing error : Failed to read key from keystore

For someone not using the signing configs and trying to test out the Cordova Release command by typing all the parameters at command line, you may need to enclose your passwords with single quotes if you have special characters in your password

cordova run android --release -- --keystore=../my-release-key.keystore --storePassword='password' --alias=alias_name --password='password'

How to limit file upload type file size in PHP?

Something that your code doesn't account for is displaying multiple errors. As you have noted above it is possible for the user to upload a file >2MB of the wrong type, but your code can only report one of the issues. Try something like:

if(isset($_FILES['uploaded_file'])) {
    $errors     = array();
    $maxsize    = 2097152;
    $acceptable = array(
        'application/pdf',
        'image/jpeg',
        'image/jpg',
        'image/gif',
        'image/png'
    );

    if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
        $errors[] = 'File too large. File must be less than 2 megabytes.';
    }

    if((!in_array($_FILES['uploaded_file']['type'], $acceptable)) && (!empty($_FILES["uploaded_file"]["type"]))) {
        $errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
    }

    if(count($errors) === 0) {
        move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
    } else {
        foreach($errors as $error) {
            echo '<script>alert("'.$error.'");</script>';
        }

        die(); //Ensure no more processing is done
    }
}

Look into the docs for move_uploaded_file() (it's called move not store) for more.

Can we have multiple <tbody> in same <table>?

According to this example it can be done: w3-struct-tables.

How should I use Outlook to send code snippets?

If you do not want to attach code in a file (this was a good tip, ChssPly76, I need to check it out), you can try changing the default message format messages to rich text (Tools - Options - Mail Format - Message format) instead of HTML. I learned that Outlook's HTML formatting screws code layout (btw, Outlook uses MS Word's HTML rendering engine which sucks big time), but rich text works fine. So if I copy code from Visual Studio and paste it in Outlook message, when using rich text, it looks pretty good, but when in HTML mode, it's a disaster. To disable smart quotes, auto-correction, and other artifacts, set up the appropriate option via Tools - Options - Spelling - Spelling and AutoCorrection; you may also want to play with copy-paste settings (Tools - Options - Mail Format - Editor Options - Cut, copy, and paste).

iPhone App Minus App Store?

If you patch /Developer/Platforms/iPhoneOS.platform/Info.plist and then try to debug a application running on the device using a real development provisionen profile from Apple it will probably not work. Symptoms are weird error messages from com.apple.debugserver and that you can use any bundle identifier without getting a error when building in Xcode. The solution is to restore Info.plist.

How to force a html5 form validation without submitting it via jQuery

This way works well for me:

  1. Add onSubmit attribute in your form, don't forget to include return in the value.

    <form id='frm-contact' method='POST' action='' onSubmit="return contact()">
    
  2. Define the function.

    function contact(params) {
        $.ajax({
            url: 'sendmail.php',
            type: "POST",
            dataType: "json",
            timeout: 5000,
            data: { params:params },
            success: function (data, textStatus, jqXHR) {
                // callback
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(jqXHR.responseText);
            }
        });
    
        return false;
    }
    

How to add a border just on the top side of a UIView

Note: most solutions here are not adaptive and will not resize. The solutions that will resize will have a massive impact on your startup time since they use a lot of CPU.

You can use this solution beneath. It works on UIBezierPaths which are lighter than layers, causing quick startup times. It is easy to use, see instructions beneath.

class ResizeBorderView: UIView {
    var color = UIColor.white
    var lineWidth: CGFloat = 1
    var edges = [UIRectEdge](){
        didSet {
            setNeedsDisplay()
        }
    }
    override func draw(_ rect: CGRect) {
        if edges.contains(.top) || edges.contains(.all){
            let path = UIBezierPath()
            path.lineWidth = lineWidth
            color.setStroke()
            UIColor.blue.setFill()
            path.move(to: CGPoint(x: 0, y: 0 + lineWidth / 2))
            path.addLine(to: CGPoint(x: self.bounds.width, y: 0 + lineWidth / 2))
            path.stroke()
        }
        if edges.contains(.bottom) || edges.contains(.all){
            let path = UIBezierPath()
            path.lineWidth = lineWidth
            color.setStroke()
            UIColor.blue.setFill()
            path.move(to: CGPoint(x: 0, y: self.bounds.height - lineWidth / 2))
            path.addLine(to: CGPoint(x: self.bounds.width, y: self.bounds.height - lineWidth / 2))
            path.stroke()
        }
        if edges.contains(.left) || edges.contains(.all){
            let path = UIBezierPath()
            path.lineWidth = lineWidth
            color.setStroke()
            UIColor.blue.setFill()
            path.move(to: CGPoint(x: 0 + lineWidth / 2, y: 0))
            path.addLine(to: CGPoint(x: 0 + lineWidth / 2, y: self.bounds.height))
            path.stroke()
        }
        if edges.contains(.right) || edges.contains(.all){
            let path = UIBezierPath()
            path.lineWidth = lineWidth
            color.setStroke()
            UIColor.blue.setFill()
            path.move(to: CGPoint(x: self.bounds.width - lineWidth / 2, y: 0))
            path.addLine(to: CGPoint(x: self.bounds.width - lineWidth / 2, y: self.bounds.height))
            path.stroke()
        }
    }
}
  1. Set your UIView's class to ResizeBorderView
  2. Set the color and line width by using yourview.color and yourview.lineWidth in your viewDidAppear method
  3. Set the edges, example: yourview.edges = [.right, .left] ([.all]) for all
  4. Enjoy quick start and resizing borders

Trying to get property of non-object in

Check the manual for mysql_fetch_object(). It returns an object, not an array of objects.

I'm guessing you want something like this

$results = mysql_query("SELECT * FROM sidemenu WHERE `menu_id`='".$menu."' ORDER BY `id` ASC LIMIT 1", $con);

$sidemenus = array();
while ($sidemenu = mysql_fetch_object($results)) {
    $sidemenus[] = $sidemenu;
}

Might I suggest you have a look at PDO. PDOStatement::fetchAll(PDO::FETCH_OBJ) does what you assumed mysql_fetch_object() to do

Eventviewer eventid for lock and unlock

The event IDs to look for in pre-Vista Windows are 528, 538, and 680. 528 usually stands for successful unlock of workstation.

The codes for newer Windows versions differ, see below answers for more infos.

Order of execution of tests in TestNG

By Specifying test methods to be executed in testNg.xml we can execute the test cases in desired order

_x000D_
_x000D_
<suite>_x000D_
<test name="selenium1">_x000D_
   <classes>_x000D_
   <class name="com.test.SeleniumTest" >_x000D_
       <methods><include name="methodB"></include>_x000D_
           <include name="methodA"></include>_x000D_
       </methods>    _x000D_
    </class>_x000D_
  </classes>_x000D_
 _x000D_
 </test>_x000D_
</suite>
_x000D_
_x000D_
_x000D_

Append text using StreamWriter

using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
  writer.WriteLine("whatever you text is");
}

The second "true" parameter tells it to append.

http://msdn.microsoft.com/en-us/library/36b035cb.aspx

jQuery validation plugin: accept only alphabetical characters?

 $('.AlphabetsOnly').keypress(function (e) {
        var regex = new RegExp(/^[a-zA-Z\s]+$/);
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        else {
            e.preventDefault();
            return false;
        }
    });

Python dictionary: are keys() and values() always the same order?

Found this:

If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.

On 2.x documentation and 3.x documentation.

No notification sound when sending notification from firebase in android

With HTTP v1 API it is different

Documentation

Example:

{
 "message":{
    "topic":"news",
    "notification":{
       "body":"Very good news",
       "title":"Good news"
    },
    "android":{
       "notification":{
          "body":"Very good news",
          "title":"Good news",
          "sound":"default"
       }
    }
  }
}

Multiple Java versions running concurrently under Windows

It should be possible changing setting the JAVA_HOME environment variable differently for specific applications.

When starting from the command line or from a batch script you can use set JAVA_HOME=C:\...\j2dskXXX to change the JAVA_HOME environment.

It is possible that you also need to change the PATH environment variable to use the correct java binary. To do this you can use set PATH=%JAVA_HOME%\bin;%PATH%.

How to have a a razor action link open in a new tab?

With Named arguments:

@Html.ActionLink(linkText: "TestTab", actionName: "TestAction", controllerName: "TestController", routeValues: null, htmlAttributes: new { target = "_blank"})

How to pass the id of an element that triggers an `onclick` event to the event handling function

The element that triggered the event can be different than the one you bound the handler to because events bubble up the DOM tree.

So if you want to get the ID of the element the event handler is bound to, you can do this easily with this.id (this refers to the element).

But if you want to get the element where the event originated, then you have to access it with event.target in W3C compatible browsers and event.srcElement in IE 8 and below.

I would avoid writing a lot of JavaScript in the onXXXX HTML attributes. I would only pass the event object and put the code to extract the element in the handler (or in an extra function):

<div onlick="doWithThisElement(event)">

Then the handler would look like this:

function doWithThisElement(event) {
    event = event || window.event; // IE
    var target = event.target || event.srcElement; // IE

    var id = target.id;
    //...
}

I suggest to read the excellent articles about event handling at quirksmode.org.


Btw

<link onclick="doWithThisElement(id_of_this_element)" />

does hardly make sense (<link> is an element that can only appear in the <head>, binding an event handler (if even possible) will have no effect).

In Git, what is the difference between origin/master vs origin master?

origin is a name for remote git url. There can be many more remotes example below.

bangalore => bangalore.example.com:project.git

boston => boston.example.com:project.git

as far as origin/master (example bangalore/master) goes, it is pointer to "master" commit on bangalore site . You see it in your clone.

It is possible that remote bangalore has advanced since you have done "fetch" or "pull"

How to display JavaScript variables in a HTML page without document.write

Similar to above, but I used (this was in CSHTML):

JavaScript:

var value = "Hello World!"<br>
$('.output').html(value);

CSHTML:

<div class="output"></div>

CMake does not find Visual C++ compiler

i found this sollution at stackoverflow and i work for me although not working other sollutions if you have a windows 10 OS, doing the following steps will fix the problem:

1) go to C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Bin

2) then copy RC.exe and RcDll from this file

3) go to C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin and paste the two files you have copied into it.

thats all i hope it is helpful...

Email address validation in C# MVC 4 application: with or without using Regex

Why not just use the EmailAttribute?

[Email(ErrorMessage = "Bad email")]
public string Email { get; set; }

Module not found: Error: Can't resolve 'core-js/es6'

Ended up to have a file named polyfill.js in projectpath\src\polyfill.js That file only contains this line: import 'core-js'; this polyfills not only es-6, but is the correct way to use core-js since version 3.0.0.

I added the polyfill.js to my webpack-file entry attribute like this:

entry: ['./src/main.scss', './src/polyfill.js', './src/main.jsx']

Works perfectly.

I also found some more information here : https://github.com/zloirock/core-js/issues/184

The library author (zloirock) claims:

ES6 changes behaviour almost all features added in ES5, so core-js/es6 entry point includes almost all of them. Also, as you wrote, it's required for fixing broken browser implementations.

(Quotation https://github.com/zloirock/core-js/issues/184 from zloirock)

So I think import 'core-js'; is just fine.

Best way to use PHP to encrypt and decrypt passwords?

The best idea to encrypt/decrypt your data in the database even if you have access to the code is to use 2 different passes a private password (user-pass) for each user and a private code for all users (system-pass).

Scenario

  1. user-pass is stored with md5 in the database and is being used to validate each user to login to the system. This user-pass is different for each user.
  2. Each user entry in the database has in md5 a system-pass for the encryption/decryption of the data. This system-pass is the same for each user.
  3. Any time a user is being removed from the system all data that are encrypted under the old system-pass have to be encrypted again under a new system-pass to avoid security issues.

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

Write to rails console

In addition to already suggested p and puts — well, actually in most cases you do can write logger.info "blah" just as you suggested yourself. It works in console too, not only in server mode.

But if all you want is console debugging, puts and p are much shorter to write, anyway.

How do I properly escape quotes inside HTML attributes?

&quot; is the correct way, the third of your tests:

<option value="&quot;asd">test</option>

You can see this working below, or on jsFiddle.

_x000D_
_x000D_
alert($("option")[0].value);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select>_x000D_
  <option value="&quot;asd">Test</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Alternatively, you can delimit the attribute value with single quotes:

<option value='"asd'>test</option>

PHP - regex to allow letters and numbers only

You left off the / (pattern delimiter) and $ (match end string).

preg_match("/^[a-zA-Z0-9]+$/", $value)

Where is virtualenvwrapper.sh after pip install?

You can use the find command to search for a file:

find / -name virtualenvwrapper.sh

This will search all directories from the root for the file.


on ubuntu 12.04 LTS, installing through pip, it is installed to

/usr/local/bin/virtualenvwrapper.sh


on ubuntu 17.04, installing through pip as a normal user, it is installed to

~/.local/bin/virtualenvwrapper.sh

How to automatically generate a stacktrace when my program crashes

I forgot about the GNOME tech of "apport", but I don't know much about using it. It is used to generate stacktraces and other diagnostics for processing and can automatically file bugs. It's certainly worth checking in to.

Nested iframes, AKA Iframe Inception

I guess your problem is that jQuery is not loaded in your iframes.

The safest approach is to rely on pure DOM-based methods to parse your content.

Or else, start with jQuery, and then once inside your iframes, test once if typeof window.jQuery == 'undefined', if it's true, jQuery is not enabled inside it and fallback on DOM-based method.

How to get a URL parameter in Express?

If you want to grab the query parameter value in the URL, follow below code pieces

//url.localhost:8888/p?tagid=1234
req.query.tagid
OR
req.param.tagid

If you want to grab the URL parameter using Express param function

Express param function to grab a specific parameter. This is considered middleware and will run before the route is called.

This can be used for validations or grabbing important information about item.

An example for this would be:

// parameter middleware that will run before the next routes
app.param('tagid', function(req, res, next, tagid) {

// check if the tagid exists
// do some validations
// add something to the tagid
var modified = tagid+ '123';

// save name to the request
req.tagid= modified;

next();
});

// http://localhost:8080/api/tags/98
app.get('/api/tags/:tagid', function(req, res) {
// the tagid was found and is available in req.tagid
res.send('New tag id ' + req.tagid+ '!');
});

How to succinctly write a formula with many variables from a data frame?

You can check the package leaps and in particular the function regsubsets() functions for model selection. As stated in the documentation:

Model selection by exhaustive search, forward or backward stepwise, or sequential replacement

Make .gitignore ignore everything except a few files

Had the similar issue as OP but none of top 10 upvoted answer actually worked.
I finally found out the following

Wrong syntax :

*
!bin/script.sh

Correct syntax :

*
!bin
!bin/script.sh

Explanation from gitignore man page :

An optional prefix "!" which negates the pattern; any matching file excluded by a previous pattern will become included again. It is not possible to re-include a file if a parent directory of that file is excluded. Git doesn’t list excluded directories for performance reasons, so any patterns on contained files have no effect, no matter where they are defined.

Which means that "Wrong syntax" above is wrong because bin/script.sh cannot be reincluded as bin/ is ignored. That's all.

Extended example :

$ tree .

.
+-- .gitignore
+-- bin
    +-- ignore.txt
    +-- sub
        +-- folder
            +-- path
                +-- other.sh
                +-- script.sh

$ cat .gitignore

*
!.gitignore
!bin
!bin/sub
!bin/sub/folder
!bin/sub/folder/path
!bin/sub/folder/path/script.sh

$ git status --untracked-files --ignored

On branch master

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        .gitignore
        bin/sub/folder/path/script.sh

Ignored files:
  (use "git add -f <file>..." to include in what will be committed)
        bin/ignore.txt
        bin/sub/folder/path/other.sh

nothing added to commit but untracked files present (use "git add" to track)

How are echo and print different in PHP?

From: http://web.archive.org/web/20090221144611/http://faqts.com/knowledge_base/view.phtml/aid/1/fid/40

  1. Speed. There is a difference between the two, but speed-wise it should be irrelevant which one you use. echo is marginally faster since it doesn't set a return value if you really want to get down to the nitty gritty.

  2. Expression. print() behaves like a function in that you can do: $ret = print "Hello World"; And $ret will be 1. That means that print can be used as part of a more complex expression where echo cannot. An example from the PHP Manual:

$b ? print "true" : print "false";

print is also part of the precedence table which it needs to be if it is to be used within a complex expression. It is just about at the bottom of the precedence list though. Only , AND OR XOR are lower.

  1. Parameter(s). The grammar is: echo expression [, expression[, expression] ... ] But echo ( expression, expression ) is not valid. This would be valid: echo ("howdy"),("partner"); the same as: echo "howdy","partner"; (Putting the brackets in that simple example serves no purpose since there is no operator precedence issue with a single term like that.)

So, echo without parentheses can take multiple parameters, which get concatenated:

   echo  "and a ", 1, 2, 3;   // comma-separated without parentheses
   echo ("and a 123");        // just one parameter with parentheses

print() can only take one parameter:

   print ("and a 123");
   print  "and a 123";

How to update/refresh specific item in RecyclerView

I got to solve this issue by catching the position of the item that needed to be modified and then in the adapter call

public void refreshBlockOverlay(int position) {
    notifyItemChanged(position);
}

, this will call onBindViewHolder(ViewHolder holder, int position) for this specific item at this specific position.

How to echo JSON in PHP

if you want to encode or decode an array from or to JSON you can use these functions

$myJSONString = json_encode($myArray);
$myArray = json_decode($myString);

json_encode will result in a JSON string, built from an (multi-dimensional) array. json_decode will result in an Array, built from a well formed JSON string

with json_decode you can take the results from the API and only output what you want, for example:

echo $myArray['payload']['ign'];

Looping through a Scripting.Dictionary using index/item number

According to the documentation of the Item property:

Sets or returns an item for a specified key in a Dictionary object.

In your case, you don't have an item whose key is 1 so doing:

s = d.Item(i)

actually creates a new key / value pair in your dictionary, and the value is empty because you have not used the optional newItem argument.

The Dictionary also has the Items method which allows looping over the indices:

a = d.Items
For i = 0 To d.Count - 1
    s = a(i)
Next i

Bash write to file without echo?

Only redirection won't work, since there's nothing to connect the now-open file descriptors. So no, there is no way like this.

Does height and width not apply to span?

As per comment from @Paul, If display: block is specified, span stops to be an inline element and an element after it appears on next line.

I came here to find solution to my span height problem and I got a solution of my own

Adding overflow:hidden; and keeing it inline will solve the problem just tested in IE8 Quirks mode

Django URL Redirect

Another way of doing it is using HttpResponsePermanentRedirect like so:

In view.py

def url_redirect(request):
    return HttpResponsePermanentRedirect("/new_url/")

In the url.py

url(r'^old_url/$', "website.views.url_redirect", name="url-redirect"),

Return string Input with parse.string

You don't need to parse the string, it's defined as a string already.

Just do:

    private static String getStringInput (String prompt) {
     String input = EZJ.getUserInput(prompt);
     return input;
    }

Angular 4 - get input value

If you want to read only one field value, I think, using the template reference variables is the easiest way

Template

<input #phone placeholder="phone number" />

<input type="button" value="Call" (click)="callPhone(phone.value)" />

**Component** 
 
callPhone(phone): void 
{
  
console.log(phone);

}

If you have a number of fields, using the reactive form one of the best ways.

How do I detect a click outside an element?

NOTE: Using stopEventPropagation() is something that should be avoided as it breaks normal event flow in the DOM. See this article for more information. Consider using this method instead

Attach a click event to the document body which closes the window. Attach a separate click event to the container which stops propagation to the document body.

$(window).click(function() {
//Hide the menus if visible
});

$('#menucontainer').click(function(event){
    event.stopPropagation();
});

Convert timestamp to date in MySQL query

To just get a date you can cast it

cast(user.registration as date)

and to get a specific format use date_format

date_format(registration, '%Y-%m-%d')

SQLFiddle demo

Bin size in Matplotlib (Histogram)

I guess the easy way would be to calculate the minimum and maximum of the data you have, then calculate L = max - min. Then you divide L by the desired bin width (I'm assuming this is what you mean by bin size) and use the ceiling of this value as the number of bins.

Counting how many times a certain char appears in a string before any other char appears

The simplest approach would be to use LINQ:

var count = text.TakeWhile(c => c == '$').Count();

There are certainly more efficient approaches, but that's probably the simplest.

Is there a 'foreach' function in Python 3?

If I understood you right, you mean that if you have a function 'func', you want to check for each item in list if func(item) returns true; if you get true for all, then do something.

You can use 'all'.

For example: I want to get all prime numbers in range 0-10 in a list:

from math import sqrt
primes = [x for x in range(10) if x > 2 and all(x % i !=0 for i in range(2, int(sqrt(x)) + 1))]

Automatically deleting related rows in Laravel (Eloquent ORM)

I believe this is a perfect use-case for Eloquent events (http://laravel.com/docs/eloquent#model-events). You can use the "deleting" event to do the cleanup:

class User extends Eloquent
{
    public function photos()
    {
        return $this->has_many('Photo');
    }

    // this is a recommended way to declare event handlers
    public static function boot() {
        parent::boot();

        static::deleting(function($user) { // before delete() method call this
             $user->photos()->delete();
             // do the rest of the cleanup...
        });
    }
}

You should probably also put the whole thing inside a transaction, to ensure the referential integrity..

Semi-transparent color layer over background-image?

You need then a wrapping element with the bg image and in it the content element with the bg color:

<div id="Wrapper">
  <div id="Content">
    <!-- content here -->
  </div>
</div>

and the css:

#Wrapper{
    background:url(../img/bg/diagonalnoise.png); 
    width:300px; 
    height:300px;
}

#Content{
    background-color:rgba(248,247,216,0.7); 
    width:100%; 
    height:100%;
}

Managing jQuery plugin dependency in webpack

This works in webpack 3:

in the webpack.config.babel.js file:

resolve: {
    alias: {
         jquery: "jquery/src/jquery"
    },
 ....
}

And use ProvidePlugin

new webpack.ProvidePlugin({
        '$': 'jquery',
        'jQuery': 'jquery',
    })

Fill remaining vertical space with CSS using display:flex

The example below includes scrolling behaviour if the content of the expanded centre component extends past its bounds. Also the centre component takes 100% of remaining space in the viewport.

jsfiddle here

html, body, .r_flex_container{
    height: 100%;
    display: flex;
    flex-direction: column;
    background: red;
    margin: 0;
}
.r_flex_container {
    display:flex;
    flex-flow: column nowrap;
    background-color:blue;
}

.r_flex_fixed_child {
    flex:none;
    background-color:black;
    color:white;

}
.r_flex_expand_child {
    flex:auto;
    background-color:yellow;
    overflow-y:scroll;
}

Example of html that can be used to demonstrate this behaviour

<html>
<body>
    <div class="r_flex_container">
      <div class="r_flex_fixed_child">
        <p> This is the fixed 'header' child of the flex container </p>
      </div>
      <div class="r_flex_expand_child">
            <article>this child container expands to use all of the space given to it -  but could be shared with other expanding childs in which case they would get equal space after the fixed container space is allocated. 
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,
            </article>
      </div>
      <div class="r_flex_fixed_child">
        this is the fixed footer child of the flex container
        asdfadsf
        <p> another line</p>
      </div>

    </div>
</body>
</html>

How to set focus to a button widget programmatically?

Try this:

btn.requestFocusFromTouch();

How to run a function in jquery

You can also do this - Since you want one function to be used everywhere, you can do so by directly calling JqueryObject.function(). For example if you want to create your own function to manipulate any CSS on an element:

jQuery.fn.doSomething = function () {
   this.css("position","absolute");
   return this;
}

And the way to call it:

$("#someRandomDiv").doSomething();

How to use function srand() with time.h?

Try to call randomize() before rand() to initialize random generator.

(look at: srand() — why call it only once?)

Preventing SQL injection in Node.js

The easiest way is to handle all of your database interactions in its own module that you export to your routes. If your route has no context of the database then SQL can't touch it anyway.

REST API error return good practices

I know this is extremely late to the party, but now, in year 2013, we have a few media types to cover error handling in a common distributed (RESTful) fashion. See "vnd.error", application/vnd.error+json (https://github.com/blongden/vnd.error) and "Problem Details for HTTP APIs", application/problem+json (https://tools.ietf.org/html/draft-nottingham-http-problem-05).

Git diff -w ignore whitespace only at start & end of lines

This is an old question, but is still regularly viewed/needed. I want to post to caution readers like me that whitespace as mentioned in the OP's question is not the same as Regex's definition, to include newlines, tabs, and space characters -- Git asks you to be explicit. See some options here: https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration

As stated, git diff -b or git diff --ignore-space-change will ignore spaces at line ends. If you desire that setting to be your default behavior, the following line adds that intent to your .gitconfig file, so it will always ignore the space at line ends:

git config --global core.whitespace trailing-space

In my case, I found this question because I was interested in ignoring "carriage return whitespace differences", so I needed this:

git diff --ignore-cr-at-eol or git config --global core.whitespace cr-at-eol from here.

You can also make it the default only for that repo by omitting the --global parameter, and checking in the settings file for that repo. For the CR problem I faced, it goes away after check-in if warncrlf or autocrlf = true in the [core] section of the .gitconfig file.

Location Services not working in iOS 8

In order to access the users location in iOS. You need to add two keys

NSLocationWhenInUseUsageDescription

NSLocationAlwaysUsageDescription

into the Info.plist file.

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Because I want to know where you are!</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>Want to know where you are!</string>

See this below image.

Info.plist image

how to change language for DataTable

There are language files uploaded in a CDN on the dataTables website https://datatables.net/plug-ins/i18n/ So you only have to replace "Spanish" with whatever language you are using in the following example.

https://datatables.net/plug-ins/i18n/Spanish

$('table.dataTable').DataTable( {
    language: {
        url: '//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json'
    }
});

Excel - find cell with same value in another worksheet and enter the value to the left of it

Assuming employee numbers are in the first column and their names are in the second:

=VLOOKUP(A1, Sheet2!A:B, 2,false)

Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

first run below commands as super user sudo code . --user-data-dir='.' it will open the visual code studio import the folder of your project and set the launch.json as below

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceFolder}/app/release/web.js",
            "outFiles": [
                "${workspaceFolder}/**/*.js"
            ],
            "runtimeExecutable": "/root/.nvm/versions/node/v8.9.4/bin/node"
        }
    ]
}

path of runtimeExecutable will be output of "which node" command.

Run the server in debug mode cheers

What is the correct way of reading from a TCP socket in C/C++?

This is an article that I always refer to when working with sockets..

THE WORLD OF SELECT()

It will show you how to reliably use 'select()' and contains some other useful links at the bottom for further info on sockets.

Git push error pre-receive hook declined

In my case, my team lead to created a repo(repo was empty) and assign me as developer so when I pushed to the code directly to master the error I was facing ! [remote rejected] master -> master (pre-receive hook declined) So how it was fixed that he assigned to me as maintainer so I was able to push the code directly to the master.

What are the safe characters for making URLs?

From the context you describe, I suspect that what you're actually trying to make is something called an 'SEO slug'. The best general known practice for those is:

  1. Convert to lower-case
  2. Convert entire sequences of characters other than a-z and 0-9 to one hyphen (-) (not underscores)
  3. Remove 'stop words' from the URL, i.e. not-meaningfully-indexable words like 'a', 'an', and 'the'; Google 'stop words' for extensive lists

So, as an example, an article titled "The Usage of !@%$* to Represent Swearing In Comics" would get a slug of "usage-represent-swearing-comics".

How to read input with multiple lines in Java

 public class Sol {

   public static void main(String[] args) {

   Scanner sc = new Scanner(System.in); 

   while(sc.hasNextLine()){

   System.out.println(sc.nextLine());

  }
 }
}

Concatenating strings in Razor

You can use:

@foreach (var item in Model)
{
  ...
  @Html.DisplayFor(modelItem => item.address + " " + item.city) 
  ...

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

Ok so here's how I figured this out. It all has to do with CORS policy. Before the POST request, Chrome was doing a preflight OPTIONS request, which should be handled and acknowledged by the server prior to the actual request. Now this is really not what I wanted for such a simple server. Hence, resetting the headers client side prevents the preflight:

app.config(function ($httpProvider) {
  $httpProvider.defaults.headers.common = {};
  $httpProvider.defaults.headers.post = {};
  $httpProvider.defaults.headers.put = {};
  $httpProvider.defaults.headers.patch = {};
});

The browser will now send a POST directly. Hope this helps a lot of folks out there... My real problem was not understanding CORS enough.

Link to a great explanation: http://www.html5rocks.com/en/tutorials/cors/

Kudos to this answer for showing me the way.

List all indexes on ElasticSearch server?

I would also recommend doing /_cat/indices which gives a nice human readable list of your indexes.

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

I had this problem with a brand new web service. Solved it by adding read-only access for Everyone on Properties->Security for the folder that the service was in.

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

var fs = require("fs");
var filename = "./index.html";

function start(resp) {
    resp.writeHead(200, {
        "Content-Type": "text/html"
    });
    fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        resp.write(data);
        resp.end();
    });
}

Finish all previous activities

If you are using startActivityForResult() in your previous activities, just override OnActivityResult() and call the finish(); method inside it in all activities.. This will do the job...

How can I connect to MySQL on a WAMP server?

Try opening Port 3306, and using that in the connection string not 8080.

How do I execute cmd commands through a batch file?

So, make an actual batch file: open up notepad, type the commands you want to run, and save as a .bat file. Then double click the .bat file to run it.

Try something like this for a start:

c:\
cd c:\Program files\IIS Express
start iisexpress /path:"C:\FormsAdmin.Site" /port:8088 /clr:v2.0
start http://localhost:8088/default.aspx
pause

Controlling fps with requestAnimationFrame?

Skipping requestAnimationFrame cause not smooth(desired) animation at custom fps.

_x000D_
_x000D_
// Input/output DOM elements_x000D_
var $results = $("#results");_x000D_
var $fps = $("#fps");_x000D_
var $period = $("#period");_x000D_
_x000D_
// Array of FPS samples for graphing_x000D_
_x000D_
// Animation state/parameters_x000D_
var fpsInterval, lastDrawTime, frameCount_timed, frameCount, lastSampleTime, _x000D_
  currentFps=0, currentFps_timed=0;_x000D_
var intervalID, requestID;_x000D_
_x000D_
// Setup canvas being animated_x000D_
var canvas = document.getElementById("c");_x000D_
var canvas_timed = document.getElementById("c2");_x000D_
canvas_timed.width = canvas.width = 300;_x000D_
canvas_timed.height = canvas.height = 300;_x000D_
var ctx = canvas.getContext("2d");_x000D_
var ctx2 = canvas_timed.getContext("2d");_x000D_
_x000D_
_x000D_
// Setup input event handlers_x000D_
_x000D_
$fps.on('click change keyup', function() {_x000D_
    if (this.value > 0) {_x000D_
        fpsInterval = 1000 / +this.value;_x000D_
    }_x000D_
});_x000D_
_x000D_
$period.on('click change keyup', function() {_x000D_
    if (this.value > 0) {_x000D_
        if (intervalID) {_x000D_
            clearInterval(intervalID);_x000D_
        }_x000D_
        intervalID = setInterval(sampleFps, +this.value);_x000D_
    }_x000D_
});_x000D_
_x000D_
_x000D_
function startAnimating(fps, sampleFreq) {_x000D_
_x000D_
    ctx.fillStyle = ctx2.fillStyle = "#000";_x000D_
    ctx.fillRect(0, 0, canvas.width, canvas.height);_x000D_
    ctx2.fillRect(0, 0, canvas.width, canvas.height);_x000D_
    ctx2.font = ctx.font = "32px sans";_x000D_
    _x000D_
    fpsInterval = 1000 / fps;_x000D_
    lastDrawTime = performance.now();_x000D_
    lastSampleTime = lastDrawTime;_x000D_
    frameCount = 0;_x000D_
    frameCount_timed = 0;_x000D_
    animate();_x000D_
    _x000D_
    intervalID = setInterval(sampleFps, sampleFreq);_x000D_
  animate_timed()_x000D_
}_x000D_
_x000D_
function sampleFps() {_x000D_
    // sample FPS_x000D_
    var now = performance.now();_x000D_
    if (frameCount > 0) {_x000D_
        currentFps =_x000D_
            (frameCount / (now - lastSampleTime) * 1000).toFixed(2);_x000D_
        currentFps_timed =_x000D_
            (frameCount_timed / (now - lastSampleTime) * 1000).toFixed(2);_x000D_
        $results.text(currentFps + " | " + currentFps_timed);_x000D_
        _x000D_
        frameCount = 0;_x000D_
        frameCount_timed = 0;_x000D_
    }_x000D_
    lastSampleTime = now;_x000D_
}_x000D_
_x000D_
function drawNextFrame(now, canvas, ctx, fpsCount) {_x000D_
    // Just draw an oscillating seconds-hand_x000D_
    _x000D_
    var length = Math.min(canvas.width, canvas.height) / 2.1;_x000D_
    var step = 15000;_x000D_
    var theta = (now % step) / step * 2 * Math.PI;_x000D_
_x000D_
    var xCenter = canvas.width / 2;_x000D_
    var yCenter = canvas.height / 2;_x000D_
    _x000D_
    var x = xCenter + length * Math.cos(theta);_x000D_
    var y = yCenter + length * Math.sin(theta);_x000D_
    _x000D_
    ctx.beginPath();_x000D_
    ctx.moveTo(xCenter, yCenter);_x000D_
    ctx.lineTo(x, y);_x000D_
   ctx.fillStyle = ctx.strokeStyle = 'white';_x000D_
    ctx.stroke();_x000D_
    _x000D_
    var theta2 = theta + 3.14/6;_x000D_
    _x000D_
    ctx.beginPath();_x000D_
    ctx.moveTo(xCenter, yCenter);_x000D_
    ctx.lineTo(x, y);_x000D_
    ctx.arc(xCenter, yCenter, length*2, theta, theta2);_x000D_
_x000D_
    ctx.fillStyle = "rgba(0,0,0,.1)"_x000D_
    ctx.fill();_x000D_
    _x000D_
    ctx.fillStyle = "#000";_x000D_
    ctx.fillRect(0,0,100,30);_x000D_
    _x000D_
    ctx.fillStyle = "#080";_x000D_
    ctx.fillText(fpsCount,10,30);_x000D_
}_x000D_
_x000D_
// redraw second canvas each fpsInterval (1000/fps)_x000D_
function animate_timed() {_x000D_
    frameCount_timed++;_x000D_
    drawNextFrame( performance.now(), canvas_timed, ctx2, currentFps_timed);_x000D_
    _x000D_
    setTimeout(animate_timed, fpsInterval);_x000D_
}_x000D_
_x000D_
function animate(now) {_x000D_
    // request another frame_x000D_
    requestAnimationFrame(animate);_x000D_
    _x000D_
    // calc elapsed time since last loop_x000D_
    var elapsed = now - lastDrawTime;_x000D_
_x000D_
    // if enough time has elapsed, draw the next frame_x000D_
    if (elapsed > fpsInterval) {_x000D_
        // Get ready for next frame by setting lastDrawTime=now, but..._x000D_
        // Also, adjust for fpsInterval not being multiple of 16.67_x000D_
        lastDrawTime = now - (elapsed % fpsInterval);_x000D_
_x000D_
        frameCount++;_x000D_
      drawNextFrame(now, canvas, ctx, currentFps);_x000D_
    }_x000D_
}_x000D_
startAnimating(+$fps.val(), +$period.val());
_x000D_
input{_x000D_
  width:100px;_x000D_
}_x000D_
#tvs{_x000D_
  color:red;_x000D_
  padding:0px 25px;_x000D_
}_x000D_
H3{_x000D_
  font-weight:400;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h3>requestAnimationFrame skipping <span id="tvs">vs.</span> setTimeout() redraw</h3>_x000D_
<div>_x000D_
    <input id="fps" type="number" value="33"/> FPS:_x000D_
    <span id="results"></span>_x000D_
</div>_x000D_
<div>_x000D_
    <input id="period" type="number" value="1000"/> Sample period (fps, ms)_x000D_
</div>_x000D_
<canvas id="c"></canvas><canvas id="c2"></canvas>
_x000D_
_x000D_
_x000D_

Original code by @tavnab.

How to index into a dictionary?

You can't, since dict is unordered. you can use .popitem() to get an arbitrary item, but that will remove it from the dict.

How to reference image resources in XAML?

One of the benefit of using the resource file is accessing the resources by names, so the image can change, the image name can change, as long as the resource is kept up to date correct image will show up.

Here is a cleaner approach to accomplish this: Assuming Resources.resx is in 'UI.Images' namespace, add the namespace reference in your xaml like this:

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UI="clr-namespace:UI.Images" 

Set your Image source like this:

<Image Source={Binding {x:Static UI:Resources.Search}} /> where 'Search' is name of the resource.

How to delete an item in a list if it exists?

1) Almost-English style:

Test for presence using the in operator, then apply the remove method.

if thing in some_list: some_list.remove(thing)

The removemethod will remove only the first occurrence of thing, in order to remove all occurrences you can use while instead of if.

while thing in some_list: some_list.remove(thing)    
  • Simple enough, probably my choice.for small lists (can't resist one-liners)

2) Duck-typed, EAFP style:

This shoot-first-ask-questions-last attitude is common in Python. Instead of testing in advance if the object is suitable, just carry out the operation and catch relevant Exceptions:

try:
    some_list.remove(thing)
except ValueError:
    pass # or scream: thing not in some_list!
except AttributeError:
    call_security("some_list not quacking like a list!")

Off course the second except clause in the example above is not only of questionable humor but totally unnecessary (the point was to illustrate duck-typing for people not familiar with the concept).

If you expect multiple occurrences of thing:

while True:
    try:
        some_list.remove(thing)
    except ValueError:
        break
  • a little verbose for this specific use case, but very idiomatic in Python.
  • this performs better than #1
  • PEP 463 proposed a shorter syntax for try/except simple usage that would be handy here, but it was not approved.

However, with contextlib's suppress() contextmanager (introduced in python 3.4) the above code can be simplified to this:

with suppress(ValueError, AttributeError):
    some_list.remove(thing)

Again, if you expect multiple occurrences of thing:

with suppress(ValueError):
    while True:
        some_list.remove(thing)

3) Functional style:

Around 1993, Python got lambda, reduce(), filter() and map(), courtesy of a Lisp hacker who missed them and submitted working patches*. You can use filter to remove elements from the list:

is_not_thing = lambda x: x is not thing
cleaned_list = filter(is_not_thing, some_list)

There is a shortcut that may be useful for your case: if you want to filter out empty items (in fact items where bool(item) == False, like None, zero, empty strings or other empty collections), you can pass None as the first argument:

cleaned_list = filter(None, some_list)
  • [update]: in Python 2.x, filter(function, iterable) used to be equivalent to [item for item in iterable if function(item)] (or [item for item in iterable if item] if the first argument is None); in Python 3.x, it is now equivalent to (item for item in iterable if function(item)). The subtle difference is that filter used to return a list, now it works like a generator expression - this is OK if you are only iterating over the cleaned list and discarding it, but if you really need a list, you have to enclose the filter() call with the list() constructor.
  • *These Lispy flavored constructs are considered a little alien in Python. Around 2005, Guido was even talking about dropping filter - along with companions map and reduce (they are not gone yet but reduce was moved into the functools module, which is worth a look if you like high order functions).

4) Mathematical style:

List comprehensions became the preferred style for list manipulation in Python since introduced in version 2.0 by PEP 202. The rationale behind it is that List comprehensions provide a more concise way to create lists in situations where map() and filter() and/or nested loops would currently be used.

cleaned_list = [ x for x in some_list if x is not thing ]

Generator expressions were introduced in version 2.4 by PEP 289. A generator expression is better for situations where you don't really need (or want) to have a full list created in memory - like when you just want to iterate over the elements one at a time. If you are only iterating over the list, you can think of a generator expression as a lazy evaluated list comprehension:

for item in (x for x in some_list if x is not thing):
    do_your_thing_with(item)

Notes

  1. you may want to use the inequality operator != instead of is not (the difference is important)
  2. for critics of methods implying a list copy: contrary to popular belief, generator expressions are not always more efficient than list comprehensions - please profile before complaining

Tool to Unminify / Decompress JavaScript

Pretty Diff will beautify (pretty print) JavaScript in a way that conforms to JSLint and JSHint white space algorithms.

What are the differences between a program and an application?

Without more information about the question, the terms 'program' and 'application' are nearly synonymous.

As Saif has indicated, 'application' tends to be used more for non-system related programs. That being said, I don't think it's wrong to describe the operating system as an special application that provides an environment in which to run other applications.

How do I wait for a promise to finish before returning the variable of a function?

Instead of returning a resultsArray you return a promise for a results array and then then that on the call site - this has the added benefit of the caller knowing the function is performing asynchronous I/O. Coding concurrency in JavaScript is based on that - you might want to read this question to get a broader idea:

function resultsByName(name)
{   
    var Card = Parse.Object.extend("Card");
    var query = new Parse.Query(Card);
    query.equalTo("name", name.toString());

    var resultsArray = [];

    return query.find({});                           

}

// later
resultsByName("Some Name").then(function(results){
    // access results here by chaining to the returned promise
});

You can see more examples of using parse promises with queries in Parse's own blog post about it.

SQL Server : GROUP BY clause to get comma-separated values

SELECT  [ReportId], 
        SUBSTRING(d.EmailList,1, LEN(d.EmailList) - 1) EmailList
FROM
        (
            SELECT DISTINCT [ReportId]
            FROM Table1
        ) a
        CROSS APPLY
        (
            SELECT [Email] + ', ' 
            FROM Table1 AS B 
            WHERE A.[ReportId] = B.[ReportId]
            FOR XML PATH('')
        ) D (EmailList) 

SQLFiddle Demo

How do I check if a C++ string is an int?

You can use boost::lexical_cast, as suggested, but if you have any prior knowledge about the strings (i.e. that if a string contains an integer literal it won't have any leading space, or that integers are never written with exponents), then rolling your own function should be both more efficient, and not particularly difficult.

How should I edit an Entity Framework connection string?

You normally define your connection strings in Web.config. After generating the edmx the connection string will get stored in the App.Config. If you want to change the connection string go to the app.config and remove all the connection strings. Now go to the edmx, right click on the designer surface, select Update model from database, choose the connection string from the dropdown, Click next, Add or Refresh (select what you want) and finish.

In the output window it will show something like this,

Generated model file: UpostDataModel.edmx. Loading metadata from the database took 00:00:00.4258157. Generating the model took 00:00:01.5623765. Added the connection string to the App.Config file.

Store mysql query output into a shell variable

myvariable=$(mysql -u user -p'password' -s -N <<QUERY_INPUT
    use databaseName;
    SELECT fieldName FROM tablename WHERE filedName='fieldValue';
QUERY_INPUT
)
echo "myvariable=$myvariable"

How to get the last character of a string in a shell?

echo $str | cut -c $((${#str}))

is a good approach

Error while sending QUERY packet

You cannot have the WHERE clause in an INSERT statement.

insert into table1(data) VALUES(:data) where sno ='45830'

Should be

insert into table1(data) VALUES(:data)


Update: You have removed that from your code (I assume you copied the code in wrong). You want to increase your allowed packet size:

SET GLOBAL max_allowed_packet=32M

Change the 32M (32 megabytes) up/down as required. Here is a link to the MySQL documentation on the subject.

How do I code my submit button go to an email address

You might use Form tag with action attribute to submit the mailto.

Here is an example:

<form method="post" action="mailto:[email protected]" >
<input type="submit" value="Send Email" /> 
</form>

How to find first element of array matching a boolean condition in JavaScript?

It should be clear by now that JavaScript offers no such solution natively; here are the closest two derivatives, the most useful first:

  1. Array.prototype.some(fn) offers the desired behaviour of stopping when a condition is met, but returns only whether an element is present; it's not hard to apply some trickery, such as the solution offered by Bergi's answer.

  2. Array.prototype.filter(fn)[0] makes for a great one-liner but is the least efficient, because you throw away N - 1 elements just to get what you need.

Traditional search methods in JavaScript are characterized by returning the index of the found element instead of the element itself or -1. This avoids having to choose a return value from the domain of all possible types; an index can only be a number and negative values are invalid.

Both solutions above don't support offset searching either, so I've decided to write this:

(function(ns) {
  ns.search = function(array, callback, offset) {
    var size = array.length;

    offset = offset || 0;
    if (offset >= size || offset <= -size) {
      return -1;
    } else if (offset < 0) {
      offset = size - offset;
    }

    while (offset < size) {
      if (callback(array[offset], offset, array)) {
        return offset;
      }
      ++offset;
    }
    return -1;
  };
}(this));

search([1, 2, NaN, 4], Number.isNaN); // 2
search([1, 2, 3, 4], Number.isNaN); // -1
search([1, NaN, 3, NaN], Number.isNaN, 2); // 3

In Java, how to append a string more efficiently?

java.lang.StringBuilder. Use int constructor to create an initial size.

Hide Twitter Bootstrap nav collapse on click

This is the best solution I have used.

$(document).ready(function () {

        $('.nav a').on('click', function () {

            if ($(".btn-navbar").is(":visible") ){ $(".btn-navbar").trigger("click"); } //bootstrap 2.x
            if ($(".navbar-toggle").is(":visible")) { $(".navbar-toggle").trigger("click"); } //bootstrap 3.x
        });

    });

How to upgrade Python version to 3.7?

On ubuntu you can add this PPA Repository and use it to install python 3.7: https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.7

Or a different PPA that provides several Python versions is Deadsnakes: https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa

See also here: https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get (I know it says 3.6 in the url, but the deadsnakes ppa also contains 3.7 so you can use it for 3.7 just the same)

If you want "official" you'd have to install it from the sources from the site, get the code (which you already downloaded) and do this:

tar -xf Python-3.7.0.tar.xz
cd Python-3.7.0
./configure
make
sudo make install        <-- sudo is required.

This might take a while

Total width of element (including padding and border) in jQuery

looks like outerWidth is broken in the latest version of jquery.

The discrepancy happens when

the outer div is floated, the inner div has the width set (smaller than the outer div) the inner div has style="margin:auto"

Retrieving a random item from ArrayList

You must remove the system.out.println message from below the return, like this:

public Item anyItem()
{
    randomGenerator = new Random();
    int index = randomGenerator.nextInt(catalogue.size());
    Item it = catalogue.get(index);
    System.out.println("Managers choice this week" + it + "our recommendation to you");
    return it;
}

the return statement basically says the function will now end. anything included beyond the return statement that is also in scope of it will result in the behavior you experienced

File changed listener in Java

"More NIO features" has file watch functionality, with implementation dependent upon the underlying OS. Should be in JDK7.

Update: Was added to Java SE 7. Chris Janicki offers a link to the relevant Java tutorial.

Typing the Enter/Return key using Python and Selenium

import org.openqa.selenium.Keys

WebElement.sendKeys(Keys.RETURN);

The import statement is for Java. For other languages, it is maybe different. For example, in Python it is from selenium.webdriver.common.keys import Keys

How can I use getSystemService in a non-activity class (LocationManager)?

You can go for this :

getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

When should I use Kruskal as opposed to Prim (and vice versa)?

In kruskal Algorithm we have number of edges and number of vertices on a given graph but on each edge we have some value or weight on behalf of which we can prepare a new graph which must be not cyclic or not close from any side For Example

graph like this _____________ | | | | | | |__________| | Give name to any vertex a,b,c,d,e,f .

Convert INT to DATETIME (SQL)

Try this:

select CONVERT(datetime, convert(varchar(10), 20120103))

How to get a value from the last inserted row?

See the API docs for java.sql.Statement.

Basically, when you call executeUpdate() or executeQuery(), use the Statement.RETURN_GENERATED_KEYS constant. You can then call getGeneratedKeys to get the auto-generated keys of all rows created by that execution. (Assuming your JDBC driver provides it.)

It goes something along the lines of this:

Statement stmt = conn.createStatement();
stmt.execute(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet keyset = stmt.getGeneratedKeys();

JFrame background image

The best way to load an image is through the ImageIO API

BufferedImage img = ImageIO.read(new File("/path/to/some/image"));

There are a number of ways you can render an image to the screen.

You could use a JLabel. This is the simplest method if you don't want to modify the image in anyway...

JLabel background = new JLabel(new ImageIcon(img));

Then simply add it to your window as you see fit. If you need to add components to it, then you can simply set the label's layout manager to whatever you need and add your components.

If, however, you need something more sophisticated, need to change the image somehow or want to apply additional effects, you may need to use custom painting.

First cavert: Don't ever paint directly to a top level container (like JFrame). Top level containers aren't double buffered, so you may end up with some flashing between repaints, other objects live on the window, so changing it's paint process is troublesome and can cause other issues and frames have borders which are rendered inside the viewable area of the window...

Instead, create a custom component, extending from something like JPanel. Override it's paintComponent method and render your output to it, for example...

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(img, 0, 0, this);
}

Take a look at Performing Custom Painting and 2D Graphics for more details

Python not working in command prompt?

You need to add python to your PATH. I could be wrong, but Windows 7 should have the same cmd as Windows 8. Try this in the command line. Using setx permanently makes changes to you PATH. Note there are no equal signs, and quotes are used.

setx PATH "%PYTHONPATH%;C:\python27"

Set the c:\python27 to the directory of the python version you'd like to run from the typing python into the command prompt.

How to make layout with View fill the remaining space?

You should avoid nesting 2 relative layout since relative layout always make 2 pass for drawing (against 1 for any other type of layout). It becomes exponential when you nest them. You should use linear layout with width=0 and weight=1 on the element you want to fill the space left. This answer is better for performance and the practices. Remember: use relative layout ONLY when you don't have other choice.

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

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/prev_button"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:text="&lt;" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ellipsize="end"
            android:singleLine="true"
            android:gravity="center"
            android:text="TextView" />

        <Button
            android:id="@+id/next_button"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:text="&gt;" />
    </LinearLayout>
</LinearLayout>

How to set default font family for entire Android app

Another way to do this for the whole app is using reflection based on this answer

public class TypefaceUtil {
    /**
     * Using reflection to override default typefaces
     * NOTICE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE
     * OVERRIDDEN
     *
     * @param typefaces map of fonts to replace
     */
    public static void overrideFonts(Map<String, Typeface> typefaces) {
        try {
            final Field field = Typeface.class.getDeclaredField("sSystemFontMap");
            field.setAccessible(true);
            Map<String, Typeface> oldFonts = (Map<String, Typeface>) field.get(null);
            if (oldFonts != null) {
                oldFonts.putAll(typefaces);
            } else {
                oldFonts = typefaces;
            }
            field.set(null, oldFonts);
            field.setAccessible(false);
        } catch (Exception e) {
            Log.e("TypefaceUtil", "Can not set custom fonts");
        }
    }

    public static Typeface getTypeface(int fontType, Context context) {
        // here you can load the Typeface from asset or use default ones
        switch (fontType) {
            case BOLD:
                return Typeface.create(SANS_SERIF, Typeface.BOLD);
            case ITALIC:
                return Typeface.create(SANS_SERIF, Typeface.ITALIC);
            case BOLD_ITALIC:
                return Typeface.create(SANS_SERIF, Typeface.BOLD_ITALIC);
            case LIGHT:
                return Typeface.create(SANS_SERIF_LIGHT, Typeface.NORMAL);
            case CONDENSED:
                return Typeface.create(SANS_SERIF_CONDENSED, Typeface.NORMAL);
            case THIN:
                return Typeface.create(SANS_SERIF_MEDIUM, Typeface.NORMAL);
            case MEDIUM:
                return Typeface.create(SANS_SERIF_THIN, Typeface.NORMAL);
            case REGULAR:
            default:
                return Typeface.create(SANS_SERIF, Typeface.NORMAL);
        }
    }
}

then whenever you want to override the fonts you can just call the method and give it a map of typefaces as follows:

Typeface regular = TypefaceUtil.getTypeface(REGULAR, context);
Typeface light = TypefaceUtil.getTypeface(REGULAR, context);
Typeface condensed = TypefaceUtil.getTypeface(CONDENSED, context);
Typeface thin = TypefaceUtil.getTypeface(THIN, context);
Typeface medium = TypefaceUtil.getTypeface(MEDIUM, context);
Map<String, Typeface> fonts = new HashMap<>();
fonts.put("sans-serif", regular);
fonts.put("sans-serif-light", light);
fonts.put("sans-serif-condensed", condensed);
fonts.put("sans-serif-thin", thin);
fonts.put("sans-serif-medium", medium);
TypefaceUtil.overrideFonts(fonts);

for full example check

This only works for Android SDK 21 and above for earlier versions check the full example

bool to int conversion

You tagged your question [C] and [C++] at the same time. The results will be consistent between the languages, but the structure of the the answer is different for each of these languages.

In C language your examples has no relation to bool whatsoever (that applies to C99 as well). In C language relational operators do not produce bool results. Both 4 > 5 and 4 < 5 are expressions that produce results of type int with values 0 or 1. So, there's no "bool to int conversion" of any kind taking place in your examples in C.

In C++ relational operators do indeed produce bool results. bool values are convertible to int type, with true converting to 1 and false converting to 0. This is guaranteed by the language.

P.S. C language also has a dedicated boolean type _Bool (macro-aliased as bool), and its integral conversion rules are essentially the same as in C++. But nevertheless this is not relevant to your specific examples in C. Once again, relational operators in C always produce int (not bool) results regardless of the version of the language specification.

How to check if element has any children in Javascript?

You could also do the following:

if (element.innerHTML.trim() !== '') {
    // It has at least one
} 

This uses the trim() method to treat empty elements which have only whitespaces (in which case hasChildNodes returns true) as being empty.

NB: The above method doesn't filter out comments. (so a comment would classify a a child)

To filter out comments as well, we could make use of the read-only Node.nodeType property where Node.COMMENT_NODE (A Comment node, such as <!-- … -->) has the constant value - 8

if (element.firstChild?.nodeType !== 8 && element.innerHTML.trim() !== '' {
   // It has at least one
}

_x000D_
_x000D_
let divs = document.querySelectorAll('div');
for(element of divs) {
  if (element.firstChild?.nodeType !== 8 && element.innerHTML.trim() !== '') {
   console.log('has children')
  } else { console.log('no children') }
}
_x000D_
<div><span>An element</span>
<div>some text</div>
<div>     </div> <!-- whitespace -->
<div><!-- A comment --></div>
<div></div>
_x000D_
_x000D_
_x000D_

Regular expression to match characters at beginning of line only

Try ^CTR.\*, which literally means start of line, CTR, anything.

This will be case-sensitive, and setting non-case-sensitivity will depend on your programming language, or use ^[Cc][Tt][Rr].\* if cross-environment case-insensitivity matters.

PHP ternary operator vs null coalescing operator

The other answers goes deep and give great explanations. For those who look for quick answer,

$a ?: 'fallback' is $a ? $a : 'fallback'

while

$a ?? 'fallback' is $a = isset($a) ? $a : 'fallback'


The main difference would be when the left operator is either:

  • A falsy value that is NOT null (0, '', false, [], ...)
  • An undefined variable

How to input a string from user into environment variable from batch file

You can use set with the /p argument:

SET /P variable=[promptString]

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

So, simply use something like

set /p Input=Enter some text: 

Later you can use that variable as argument to a command:

myCommand %Input%

Be careful though, that if your input might contain spaces it's probably a good idea to quote it:

myCommand "%Input%"

How do you change the server header returned by nginx?

After I read Parthian Shot's answer, I dig into /usr/sbin/nginx binary file. Then I found out that the file contains these three lines.

Server: nginx/1.12.2
Server: nginx/1.12.2
Server: nginx

Basically first two of them are meant for server_tokens on; directive (Server version included). Then I change the search criteria to match those lines within the binary file.

sed -i 's/Server: nginx/Server: thing/' `which nginx`

After I dig farther I found out that the error message produced by nginx is also included in this file.

<hr><center>nginx</center>

There are three of them, one without the version, two of them included the version. So I run the following command to replace nginx string within the error message.

sed -i 's/center>nginx/center>thing/' `which nginx`

Iterate all files in a directory using a 'for' loop

for %1 in (*.*) do echo %1

Try "HELP FOR" in cmd for a full guide

This is the guide for XP commands. http://www.ss64.com/nt/

ASP.NET MVC: No parameterless constructor defined for this object

I'd added a DropDownList to my form, however in my case it wasn't (and wasn't intended to be) submitted with the form as it was outside of the <form></form> tags:

@Html.DropDownList("myField", Model.MyField)

As the Model contained the field for display only, this also caused the No parameterless constructor defined for this object error because the field wasn't submitted at all.

In this case I fixed it by adding an exclude binding:

public ActionResult Foo(int id, int? page, [Bind(Exclude = "MyField")]MyModel model)

Seeing the console's output in Visual Studio 2010?

You can use the System.Diagnostics.Debug.Write or System.Runtime.InteropServices method to write messages to the Output Window.

What is the difference between private and protected members of C++ classes?

Protected members can only be accessed by descendants of the class, and by code in the same module. Private members can only be accessed by the class they're declared in, and by code in the same module.

Of course friend functions throw this out the window, but oh well.

PhpMyAdmin "Wrong permissions on configuration file, should not be world writable!"

Do the following in your terminal

sudo chmod 755 /opt/lampp/phpmyadmin/config.inc.php

After this you have to restart your server

How to create an empty R vector to add new items

In rpy2, the way to get the very same operator as "[" with R is to use ".rx". See the documentation about extracting with rpy2

For creating vectors, if you know your way around with Python there should not be any issue. See the documentation about creating vectors

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

Run gradle -q dependencies (or gradle -q :projectName:dependencies) to generate a dependency report. You should see where r7 is coming from, such as:

compile - Classpath for compiling the main sources.
+--- com.commonsware.cwac:camera-v9:0.5.4
|    +--- com.actionbarsherlock:actionbarsherlock:4.4.0
|    |    \--- com.google.android:support-v4:r7
|    +--- com.commonsware.cwac:camera:0.5.4
|    \--- com.android.support:support-v4:18.0.+ -> 18.0.0
\--- com.android.support:support-v4:18.0.+ -> 18.0.0

Then, use the exclude directive to block that dependency. In my case, it is coming from my CWAC-Camera library, and so I use:

dependencies {
    compile('com.commonsware.cwac:camera-v9:0.5.4') {
      exclude module: 'support-v4'
    }

    compile 'com.android.support:support-v4:18.0.+'
}

(where the second compile statement indicates what version you actually want)

That should clear matters up, as you will see if you run the dependency report again:

compile - Classpath for compiling the main sources.
+--- com.commonsware.cwac:camera-v9:0.5.4
|    +--- com.actionbarsherlock:actionbarsherlock:4.4.0
|    \--- com.commonsware.cwac:camera:0.5.4
\--- com.android.support:support-v4:18.0.+ -> 18.0.0

How to find where javaw.exe is installed?

Try this

for %i in (javaw.exe) do @echo. %~$PATH:i

How to config routeProvider and locationProvider in angularJS?

The only issue I see are relative links and templates not being properly loaded because of this.

from the docs regarding HTML5 mode

Relative links

Be sure to check all relative links, images, scripts etc. You must either specify the url base in the head of your main html file (<base href="/my-base">) or you must use absolute urls (starting with /) everywhere because relative urls will be resolved to absolute urls using the initial absolute url of the document, which is often different from the root of the application.

In your case you can add a forward slash / in href attributes ($location.path does this automatically) and also to templateUrl when configuring routes. This avoids routes like example.com/tags/another and makes sure templates load properly.

Here's an example that works:

<div>
    <a href="/">Home</a> | 
    <a href="/another">another</a> | 
    <a href="/tags/1">tags/1</a>
</div>
<div ng-view></div>

And

app.config(function($locationProvider, $routeProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider
    .when('/', {
      templateUrl: '/partials/template1.html', 
      controller: 'ctrl1'
    })
    .when('/tags/:tagId', {
      templateUrl: '/partials/template2.html', 
      controller:  'ctrl2'
    })
    .when('/another', {
      templateUrl: '/partials/template1.html', 
      controller:  'ctrl1'
    })
    .otherwise({ redirectTo: '/' });
});

If using Chrome you will need to run this from a server.

How to update UI from another thread running in another class

You are going to have to come back to your main thread (also called UI thread) in order to update the UI. Any other thread trying to update your UI will just cause exceptions to be thrown all over the place.

So because you are in WPF, you can use the Dispatcher and more specifically a beginInvoke on this dispatcher. This will allow you to execute what needs done (typically Update the UI) in the UI thread.

You migh also want to "register" the UI in your business, by maintaining a reference to a control/form, so you can use its dispatcher.

Update a table using JOIN in SQL Server?

Seems like SQL Server 2012 can handle the old update syntax of Teradata too:

UPDATE a
SET a.CalculatedColumn= b.[Calculated Column]
FROM table1 a, table2 b 
WHERE 
    b.[common field]= a.commonfield
AND a.BatchNO = '110'

If I remember correctly, 2008R2 was giving error when I tried similar query.

"git pull" or "git merge" between master and development branches

Be careful with rebase. If you're sharing your develop branch with anybody, rebase can make a mess of things. Rebase is good only for your own local branches.

Rule of thumb, if you've pushed the branch to origin, don't use rebase. Instead, use merge.

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

How to add bootstrap in angular 6 project?

For Angular Version 11+

Configuration

The styles and scripts options in your angular.json configuration now allow to reference a package directly:

before: "styles": ["../node_modules/bootstrap/dist/css/bootstrap.css"]
after: "styles": ["bootstrap/dist/css/bootstrap.css"]

          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ng6",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css","bootstrap/dist/css/bootstrap.min.css"

            ],
            "scripts": [
                       "jquery/dist/jquery.min.js",
                       "bootstrap/dist/js/bootstrap.min.js"
                       ]
          },

Angular Version 10 and below

You are using Angular v6 not 2

Angular v6 Onwards

CLI projects in angular 6 onwards will be using angular.json instead of .angular-cli.json for build and project configuration.

Each CLI workspace has projects, each project has targets, and each target can have configurations.Docs

. {
  "projects": {
    "my-project-name": {
      "projectType": "application",
      "architect": {
        "build": {
          "configurations": {
            "production": {},
            "demo": {},
            "staging": {},
          }
        },
        "serve": {},
        "extract-i18n": {},
        "test": {},
      }
    },
    "my-project-name-e2e": {}
  },
}

OPTION-1
execute npm install bootstrap@4 jquery --save
The JavaScript parts of Bootstrap are dependent on jQuery. So you need the jQuery JavaScript library file too.

In your angular.json add the file paths to the styles and scripts array in under build target
NOTE: Before v6 the Angular CLI project configuration was stored in <PATH_TO_PROJECT>/.angular-cli.json. As of v6 the location of the file changed to angular.json. Since there is no longer a leading dot, the file is no longer hidden by default and is on the same level.
which also means that file paths in angular.json should not contain leading dots and slash

i.e you can provide an absolute path instead of a relative path

In .angular-cli.json file Path was "../node_modules/"
In angular.json it is "node_modules/"

 "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ng6",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css","node_modules/bootstrap/dist/css/bootstrap.min.css"
               
            ],
            "scripts": ["node_modules/jquery/dist/jquery.min.js",
                       "node_modules/bootstrap/dist/js/bootstrap.min.js"]
          },

OPTION 2
Add files from CDN (Content Delivery Network) to your project CDN LINK

Open file src/index.html and insert

the <link> element at the end of the head section to include the Bootstrap CSS file
a <script> element to include jQuery at the bottom of the body section
a <script> element to include Popper.js at the bottom of the body section
a <script> element to include the Bootstrap JavaScript file at the bottom of the body section

  <!doctype html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Angular</title>
      <base href="/">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="icon" type="image/x-icon" href="favicon.ico">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    </head>
    <body>
      <app-root>Loading...</app-root>
      <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    </body>
    </html>

OPTION 3
Execute npm install bootstrap
In src/styles.css add the following line:

@import "~bootstrap/dist/css/bootstrap.css";

OPTION-4
ng-bootstrap It contains a set of native Angular directives based on Bootstrap’s markup and CSS. As a result, it's not dependent on jQuery or Bootstrap’s JavaScript

npm install --save @ng-bootstrap/ng-bootstrap

After Installation import it in your root module and register it in @NgModule imports` array

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
@NgModule({
  declarations: [AppComponent, ...],
  imports: [NgbModule.forRoot(), ...],
  bootstrap: [AppComponent]
})

NOTE
ng-bootstrap requires Bootstrap's 4 css to be added in your project. you need to Install it explicitly via:
npm install bootstrap@4 --save In your angular.json add the file paths to the styles array in under build target

   "styles": [
      "src/styles.css",
      "node_modules/bootstrap/dist/css/bootstrap.min.css"
   ],

P.S Do Restart Your server

`ng serve || npm start`

TypeError: 'tuple' object does not support item assignment when swapping values

Evaluating "1,2,3" results in (1, 2, 3), a tuple. As you've discovered, tuples are immutable. Convert to a list before processing.

Calling a class function inside of __init__

How about:

class MyClass(object):
    def __init__(self, filename):
        self.filename = filename 
        self.stats = parse_file(filename)

def parse_file(filename):
    #do some parsing
    return results_from_parse

By the way, if you have variables named stat1, stat2, etc., the situation is begging for a tuple: stats = (...).

So let parse_file return a tuple, and store the tuple in self.stats.

Then, for example, you can access what used to be called stat3 with self.stats[2].

PHP syntax question: What does the question mark and colon mean?

It's the ternary form of the if-else operator. The above statement basically reads like this:

if ($add_review) then {
    return FALSE; //$add_review evaluated as True
} else {
    return $arg //$add_review evaluated as False
}

See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/

JQuery Ajax - How to Detect Network Connection error when making Ajax call

Since I can't duplicate the issue I can only suggest to try with a timeout on the ajax call. In jQuery you can set it with the $.ajaxSetup (and it will be global for all your $.ajax calls) or you can set it specifically for your call like this:

$.ajax({
    type: 'GET',
    url: 'http://www.mywebapp.com/keepAlive',
    timeout: 15000,
    success: function(data) {},
    error: function(XMLHttpRequest, textStatus, errorThrown) {}
})

JQuery will register a 15 seconds timeout on your call; after that without an http response code from the server jQuery will execute the error callback with the textStatus value set to "timeout". With this you can at least stop the ajax call but you won't be able to differentiate the real network issues from the loss of connections.

Don't change link color when a link is clicked

You need to use an explicit color value (e.g. #000 or blue) for the color-property. none is invalid here. The initial value is browser-specific and cannot be restored using CSS. Keep in mind that there are some other pseudo-classes than :active, too.

Get records of current month

Try this query:

SELECT *
FROM table 
WHERE MONTH(FROM_UNIXTIME(columnName))= MONTH(CURDATE())

Create MSI or setup project with Visual Studio 2012

ISLE (InstallShield Limited Edition) is the "replacement" of the Visual Studio Setup and Deploy project, but many users think Microsoft took wrong step with removing .vdproj support from Visual Studio 2012 (and later ones) and supporting third-party company software.

Many people asked for returning it back (Bring back the basic setup and deployment project type Visual Studio Installer), but Microsoft is deaf to our voices... really sad.

As WiX is really complicated, I think it is worth to try some free installation systems - NSIS or Inno Setup. Both are scriptable and easy to learn - but powerful as original SADP.

I have created a really nice Visual Studio extension for NSIS and Inno Setup with many features (intellisense, syntax highlighting, navigation bars, compilation directly from Visual Studio, etc.). You can try it at www.visual-installer.com (sorry for self promo :)

Download Inno Setup (jrsoftware.org/isdl.php) or NSIS (nsis.sourceforge.net/Download) and install V&I (unsigned-softworks.sk/visual-installer/downloads.html).

All installers are simple Next/Next/Next...

In Visual Studio, select menu File -> New -> Project, choose NSISProject or Inno Setup, and a new project will be created (with full sources).

wampserver doesn't go green - stays orange

After trying all the other solutions posted here (Skype, updates to C++ Redistributable), I found that another process was using port 80. The culprit was Microsoft Internet Information Server (IIS). You can stop the service from the command line on Windows 7/Vista:

net stop was /y

Or set the service to not start automatically by going to Services: click Start, click Control Panel, click Performance and Maintenance, click Administrative Tools, and then double-click Services. There, locate "WAS Service" and "World Wide Web Publication Service" and set them to manual or deactivate them completely.

Then restart the WAMP server.

More info: http://www.sitepoint.com/unblock-port-80-on-windows-run-apache/

Change first commit of project with Git?

git rebase -i allows you to conveniently edit any previous commits, except for the root commit. The following commands show you how to do this manually.

# tag the old root, "git rev-list ..." will return the hash of first commit
git tag root `git rev-list HEAD | tail -1`

# switch to a new branch pointing at the first commit
git checkout -b new-root root

# make any edits and then commit them with:
git commit --amend

# check out the previous branch (i.e. master)
git checkout @{-1}

# replace old root with amended version
git rebase --onto new-root root

# you might encounter merge conflicts, fix any conflicts and continue with:
# git rebase --continue

# delete the branch "new-root"
git branch -d new-root

# delete the tag "root"
git tag -d root

SQL Server - Create a copy of a database table and place it in the same database?

You need to write SSIS to copy the table and its data, constraints and triggers. We have in our organization a software called Kal Admin by kalrom Systems that has a free version for downloading (I think that the copy tables feature is optional)

JavaScript/jQuery to download file via POST with JSON data

Solution

Content-Disposition attachment seems to work for me:

self.set_header("Content-Type", "application/json")
self.set_header("Content-Disposition", 'attachment; filename=learned_data.json')

Workaround

application/octet-stream

I had something similar happening to me with a JSON, for me on the server side I was setting the header to self.set_header("Content-Type", "application/json") however when i changed it to:

self.set_header("Content-Type", "application/octet-stream")

It automatically downloaded it.

Also know that in order for the file to still keep the .json suffix you will need to it on filename header:

self.set_header("Content-Disposition", 'filename=learned_data.json')

Hyper-V: Create shared folder between host and guest with internal network

Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Prerequisites

  1. Ensure that Enhanced session mode settings are enabled on the Hyper-V host.

    Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".

    hyper-v-settings

    Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.

    use-enhanced-session-mode

  2. Enable Hyper-V Guest Services for your virtual machine

    Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.

    enable-guest-services

Steps to share devices with Hyper-v virtual machine:

  1. Start a virtual machine and click Show Options in the pop-up windows.

    connect-to-vm

    Or click "Edit Session Settings..." in the Actions panel on the right

    edit-session-sessions

    It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.

  2. View local resources. Then, select the "More..." menu.

    click-more

  3. From there, you can choose which devices to share. Removable drives are especially useful for file sharing.

    choose-the-devices-that-you-want-to-use

  4. Choose to "Save my settings for future connections to this virtual machine".

    save-my-settings-for-future-connections-to-this-vm

  5. Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.

    shared-drives-from-local-pc

Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Implement Stack using Two Queues

We can do this with one queue:

push:

  1. enqueue new element.
  2. If n is the number of elements in the queue, then remove and insert element n-1 times.

pop:

  1. dequeue

.

push 1


front                     
+----+----+----+----+----+----+
| 1  |    |    |    |    |    |    insert 1
+----+----+----+----+----+----+


push2

front                     
+----+----+----+----+----+----+
| 1  | 2  |    |    |    |    |    insert 2
+----+----+----+----+----+----+

     front                     
+----+----+----+----+----+----+
|    | 2  |  1 |    |    |    |    remove and insert 1
+----+----+----+----+----+----+




 insert 3


      front                     
+----+----+----+----+----+----+
|    | 2  |  1 |  3 |    |    |    insert 3
+----+----+----+----+----+----+

           front                     
+----+----+----+----+----+----+
|    |    |  1 |  3 |  2 |    |    remove and insert 2
+----+----+----+----+----+----+

                front                     
+----+----+----+----+----+----+
|    |    |    |  3 |  2 |  1 |    remove and insert 1
+----+----+----+----+----+----+

Sample implementation:

int stack_pop (queue_data *q)
{
  return queue_remove (q);
}

void stack_push (queue_data *q, int val)
{
  int old_count = queue_get_element_count (q), i;

  queue_insert (q, val);
  for (i=0; i<old_count; i++)
  {
    queue_insert (q, queue_remove (q));
  }
}

How to check the value given is a positive or negative integer?

To check a number is positive, negative or negative zero. Check its sign using Math.sign() method it will provide you -1,-0,0 and 1 on the basis of positive negative and negative zero or zero numbers

 Math.sign(-3) // -1
 Math.sign(3) // 1
 Math.sign(-0) // -0
 Math.sign(0) // 0

grep --ignore-case --only

This is a known bug on the initial 2.5.1, and has been fixed in early 2007 (Redhat 2.5.1-5) according to the bug reports. Unfortunately Apple is still using 2.5.1 even on Mac OS X 10.7.2.

You could get a newer version via Homebrew (3.0) or MacPorts (2.26) or fink (3.0-1).


Edit: Apparently it has been fixed on OS X 10.11 (or maybe earlier), even though the grep version reported is still 2.5.1.

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

How to check if a column exists in Pandas

Just to suggest another way without using if statements, you can use the get() method for DataFrames. For performing the sum based on the question:

df['sum'] = df.get('A', df['B']) + df['C']

The DataFrame get method has similar behavior as python dictionaries.

How can I list ALL grants a user received?

Assuming you want to list grants on all objects a particular user has received:

select * from all_tab_privs_recd where grantee = 'your user'

This will not return objects owned by the user. If you need those, use all_tab_privs view instead.

C++ passing an array pointer as a function argument

I'm guessing this will help.

When passed as functions arguments, arrays act the same way as pointers. So you don't need to reference them. Simply type: int x[] or int x[a] . Both ways will work. I guess its the same thing Konrad Rudolf was saying, figured as much.

Is there an XSL "contains" directive?

Use the standard XPath function contains().

Function: boolean contains(string, string)

The contains function returns true if the first argument string contains the second argument string, and otherwise returns false

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

You can try to set

<property name="hibernate.enable_lazy_load_no_trans">true</property>

in hibernate.cfg.xml or persistence.xml

The problem to keep in mind with this property are well explained here

How can I reorder a list?

Is the final order defined by a list of indices ?

>>> items = [1, None, "chicken", int]
>>> order = [3, 0, 1, 2]

>>> ordered_list = [items[i] for i in order]
>>> ordered_list
[<type 'int'>, 1, None, 'chicken']

edit: meh. AJ was faster... How can I reorder a list in python?

How to select date without time in SQL

You can try this one too.

SELECT CONVERT(DATE, GETDATE(), 120)

Python: instance has no attribute

Your class doesn't have a __init__(), so by the time it's instantiated, the attribute atoms is not present. You'd have to do C.setdata('something') so C.atoms becomes available.

>>> C = Residues()
>>> C.atoms.append('thing')

Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'

>>> C.setdata('something')
>>> C.atoms.append('thing')   # now it works
>>> 

Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.

To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms list you could add a constructor:

def __init__(self):
    self.atoms = []

JavaScript + Unicode regexes

I'm answering this question
What would be the equivalent for \p{Lu} or \p{Ll} in regExp for js?
since it was marked as an exact duplicate of the current old question.

Querying the UCD Database of Unicode 12, \p{Lu} generates 1,788 code points.

Converting to UTF-16 yields the class construct equivalency.
It's only a 4k character string and is easily doable in any regex engines.

(?:[\u0041-\u005A\u00C0-\u00D6\u00D8-\u00DE\u0100\u0102\u0104\u0106\u0108\u010A\u010C\u010E\u0110\u0112\u0114\u0116\u0118\u011A\u011C\u011E\u0120\u0122\u0124\u0126\u0128\u012A\u012C\u012E\u0130\u0132\u0134\u0136\u0139\u013B\u013D\u013F\u0141\u0143\u0145\u0147\u014A\u014C\u014E\u0150\u0152\u0154\u0156\u0158\u015A\u015C\u015E\u0160\u0162\u0164\u0166\u0168\u016A\u016C\u016E\u0170\u0172\u0174\u0176\u0178-\u0179\u017B\u017D\u0181-\u0182\u0184\u0186-\u0187\u0189-\u018B\u018E-\u0191\u0193-\u0194\u0196-\u0198\u019C-\u019D\u019F-\u01A0\u01A2\u01A4\u01A6-\u01A7\u01A9\u01AC\u01AE-\u01AF\u01B1-\u01B3\u01B5\u01B7-\u01B8\u01BC\u01C4\u01C7\u01CA\u01CD\u01CF\u01D1\u01D3\u01D5\u01D7\u01D9\u01DB\u01DE\u01E0\u01E2\u01E4\u01E6\u01E8\u01EA\u01EC\u01EE\u01F1\u01F4\u01F6-\u01F8\u01FA\u01FC\u01FE\u0200\u0202\u0204\u0206\u0208\u020A\u020C\u020E\u0210\u0212\u0214\u0216\u0218\u021A\u021C\u021E\u0220\u0222\u0224\u0226\u0228\u022A\u022C\u022E\u0230\u0232\u023A-\u023B\u023D-\u023E\u0241\u0243-\u0246\u0248\u024A\u024C\u024E\u0370\u0372\u0376\u037F\u0386\u0388-\u038A\u038C\u038E-\u038F\u0391-\u03A1\u03A3-\u03AB\u03CF\u03D2-\u03D4\u03D8\u03DA\u03DC\u03DE\u03E0\u03E2\u03E4\u03E6\u03E8\u03EA\u03EC\u03EE\u03F4\u03F7\u03F9-\u03FA\u03FD-\u042F\u0460\u0462\u0464\u0466\u0468\u046A\u046C\u046E\u0470\u0472\u0474\u0476\u0478\u047A\u047C\u047E\u0480\u048A\u048C\u048E\u0490\u0492\u0494\u0496\u0498\u049A\u049C\u049E\u04A0\u04A2\u04A4\u04A6\u04A8\u04AA\u04AC\u04AE\u04B0\u04B2\u04B4\u04B6\u04B8\u04BA\u04BC\u04BE\u04C0-\u04C1\u04C3\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04D2\u04D4\u04D6\u04D8\u04DA\u04DC\u04DE\u04E0\u04E2\u04E4\u04E6\u04E8\u04EA\u04EC\u04EE\u04F0\u04F2\u04F4\u04F6\u04F8\u04FA\u04FC\u04FE\u0500\u0502\u0504\u0506\u0508\u050A\u050C\u050E\u0510\u0512\u0514\u0516\u0518\u051A\u051C\u051E\u0520\u0522\u0524\u0526\u0528\u052A\u052C\u052E\u0531-\u0556\u10A0-\u10C5\u10C7\u10CD\u13A0-\u13F5\u1C90-\u1CBA\u1CBD-\u1CBF\u1E00\u1E02\u1E04\u1E06\u1E08\u1E0A\u1E0C\u1E0E\u1E10\u1E12\u1E14\u1E16\u1E18\u1E1A\u1E1C\u1E1E\u1E20\u1E22\u1E24\u1E26\u1E28\u1E2A\u1E2C\u1E2E\u1E30\u1E32\u1E34\u1E36\u1E38\u1E3A\u1E3C\u1E3E\u1E40\u1E42\u1E44\u1E46\u1E48\u1E4A\u1E4C\u1E4E\u1E50\u1E52\u1E54\u1E56\u1E58\u1E5A\u1E5C\u1E5E\u1E60\u1E62\u1E64\u1E66\u1E68\u1E6A\u1E6C\u1E6E\u1E70\u1E72\u1E74\u1E76\u1E78\u1E7A\u1E7C\u1E7E\u1E80\u1E82\u1E84\u1E86\u1E88\u1E8A\u1E8C\u1E8E\u1E90\u1E92\u1E94\u1E9E\u1EA0\u1EA2\u1EA4\u1EA6\u1EA8\u1EAA\u1EAC\u1EAE\u1EB0\u1EB2\u1EB4\u1EB6\u1EB8\u1EBA\u1EBC\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1EC8\u1ECA\u1ECC\u1ECE\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EDA\u1EDC\u1EDE\u1EE0\u1EE2\u1EE4\u1EE6\u1EE8\u1EEA\u1EEC\u1EEE\u1EF0\u1EF2\u1EF4\u1EF6\u1EF8\u1EFA\u1EFC\u1EFE\u1F08-\u1F0F\u1F18-\u1F1D\u1F28-\u1F2F\u1F38-\u1F3F\u1F48-\u1F4D\u1F59\u1F5B\u1F5D\u1F5F\u1F68-\u1F6F\u1FB8-\u1FBB\u1FC8-\u1FCB\u1FD8-\u1FDB\u1FE8-\u1FEC\u1FF8-\u1FFB\u2102\u2107\u210B-\u210D\u2110-\u2112\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u2130-\u2133\u213E-\u213F\u2145\u2183\u2C00-\u2C2E\u2C60\u2C62-\u2C64\u2C67\u2C69\u2C6B\u2C6D-\u2C70\u2C72\u2C75\u2C7E-\u2C80\u2C82\u2C84\u2C86\u2C88\u2C8A\u2C8C\u2C8E\u2C90\u2C92\u2C94\u2C96\u2C98\u2C9A\u2C9C\u2C9E\u2CA0\u2CA2\u2CA4\u2CA6\u2CA8\u2CAA\u2CAC\u2CAE\u2CB0\u2CB2\u2CB4\u2CB6\u2CB8\u2CBA\u2CBC\u2CBE\u2CC0\u2CC2\u2CC4\u2CC6\u2CC8\u2CCA\u2CCC\u2CCE\u2CD0\u2CD2\u2CD4\u2CD6\u2CD8\u2CDA\u2CDC\u2CDE\u2CE0\u2CE2\u2CEB\u2CED\u2CF2\uA640\uA642\uA644\uA646\uA648\uA64A\uA64C\uA64E\uA650\uA652\uA654\uA656\uA658\uA65A\uA65C\uA65E\uA660\uA662\uA664\uA666\uA668\uA66A\uA66C\uA680\uA682\uA684\uA686\uA688\uA68A\uA68C\uA68E\uA690\uA692\uA694\uA696\uA698\uA69A\uA722\uA724\uA726\uA728\uA72A\uA72C\uA72E\uA732\uA734\uA736\uA738\uA73A\uA73C\uA73E\uA740\uA742\uA744\uA746\uA748\uA74A\uA74C\uA74E\uA750\uA752\uA754\uA756\uA758\uA75A\uA75C\uA75E\uA760\uA762\uA764\uA766\uA768\uA76A\uA76C\uA76E\uA779\uA77B\uA77D-\uA77E\uA780\uA782\uA784\uA786\uA78B\uA78D\uA790\uA792\uA796\uA798\uA79A\uA79C\uA79E\uA7A0\uA7A2\uA7A4\uA7A6\uA7A8\uA7AA-\uA7AE\uA7B0-\uA7B4\uA7B6\uA7B8\uA7BA\uA7BC\uA7BE\uA7C2\uA7C4-\uA7C6\uFF21-\uFF3A]|(?:\uD801[\uDC00-\uDC27\uDCB0-\uDCD3]|\uD803[\uDC80-\uDCB2]|\uD806[\uDCA0-\uDCBF]|\uD81B[\uDE40-\uDE5F]|\uD835[\uDC00-\uDC19\uDC34-\uDC4D\uDC68-\uDC81\uDC9C\uDC9E-\uDC9F\uDCA2\uDCA5-\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB5\uDCD0-\uDCE9\uDD04-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD38-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD6C-\uDD85\uDDA0-\uDDB9\uDDD4-\uDDED\uDE08-\uDE21\uDE3C-\uDE55\uDE70-\uDE89\uDEA8-\uDEC0\uDEE2-\uDEFA\uDF1C-\uDF34\uDF56-\uDF6E\uDF90-\uDFA8\uDFCA]|\uD83A[\uDD00-\uDD21]))

Querying the UCD database of Unicode 12, \p{Ll} generates 2,151 code points.

Converting to UTF-16 yields the class construct equivalency.

(?:[\u0061-\u007A\u00B5\u00DF-\u00F6\u00F8-\u00FF\u0101\u0103\u0105\u0107\u0109\u010B\u010D\u010F\u0111\u0113\u0115\u0117\u0119\u011B\u011D\u011F\u0121\u0123\u0125\u0127\u0129\u012B\u012D\u012F\u0131\u0133\u0135\u0137-\u0138\u013A\u013C\u013E\u0140\u0142\u0144\u0146\u0148-\u0149\u014B\u014D\u014F\u0151\u0153\u0155\u0157\u0159\u015B\u015D\u015F\u0161\u0163\u0165\u0167\u0169\u016B\u016D\u016F\u0171\u0173\u0175\u0177\u017A\u017C\u017E-\u0180\u0183\u0185\u0188\u018C-\u018D\u0192\u0195\u0199-\u019B\u019E\u01A1\u01A3\u01A5\u01A8\u01AA-\u01AB\u01AD\u01B0\u01B4\u01B6\u01B9-\u01BA\u01BD-\u01BF\u01C6\u01C9\u01CC\u01CE\u01D0\u01D2\u01D4\u01D6\u01D8\u01DA\u01DC-\u01DD\u01DF\u01E1\u01E3\u01E5\u01E7\u01E9\u01EB\u01ED\u01EF-\u01F0\u01F3\u01F5\u01F9\u01FB\u01FD\u01FF\u0201\u0203\u0205\u0207\u0209\u020B\u020D\u020F\u0211\u0213\u0215\u0217\u0219\u021B\u021D\u021F\u0221\u0223\u0225\u0227\u0229\u022B\u022D\u022F\u0231\u0233-\u0239\u023C\u023F-\u0240\u0242\u0247\u0249\u024B\u024D\u024F-\u0293\u0295-\u02AF\u0371\u0373\u0377\u037B-\u037D\u0390\u03AC-\u03CE\u03D0-\u03D1\u03D5-\u03D7\u03D9\u03DB\u03DD\u03DF\u03E1\u03E3\u03E5\u03E7\u03E9\u03EB\u03ED\u03EF-\u03F3\u03F5\u03F8\u03FB-\u03FC\u0430-\u045F\u0461\u0463\u0465\u0467\u0469\u046B\u046D\u046F\u0471\u0473\u0475\u0477\u0479\u047B\u047D\u047F\u0481\u048B\u048D\u048F\u0491\u0493\u0495\u0497\u0499\u049B\u049D\u049F\u04A1\u04A3\u04A5\u04A7\u04A9\u04AB\u04AD\u04AF\u04B1\u04B3\u04B5\u04B7\u04B9\u04BB\u04BD\u04BF\u04C2\u04C4\u04C6\u04C8\u04CA\u04CC\u04CE-\u04CF\u04D1\u04D3\u04D5\u04D7\u04D9\u04DB\u04DD\u04DF\u04E1\u04E3\u04E5\u04E7\u04E9\u04EB\u04ED\u04EF\u04F1\u04F3\u04F5\u04F7\u04F9\u04FB\u04FD\u04FF\u0501\u0503\u0505\u0507\u0509\u050B\u050D\u050F\u0511\u0513\u0515\u0517\u0519\u051B\u051D\u051F\u0521\u0523\u0525\u0527\u0529\u052B\u052D\u052F\u0560-\u0588\u10D0-\u10FA\u10FD-\u10FF\u13F8-\u13FD\u1C80-\u1C88\u1D00-\u1D2B\u1D6B-\u1D77\u1D79-\u1D9A\u1E01\u1E03\u1E05\u1E07\u1E09\u1E0B\u1E0D\u1E0F\u1E11\u1E13\u1E15\u1E17\u1E19\u1E1B\u1E1D\u1E1F\u1E21\u1E23\u1E25\u1E27\u1E29\u1E2B\u1E2D\u1E2F\u1E31\u1E33\u1E35\u1E37\u1E39\u1E3B\u1E3D\u1E3F\u1E41\u1E43\u1E45\u1E47\u1E49\u1E4B\u1E4D\u1E4F\u1E51\u1E53\u1E55\u1E57\u1E59\u1E5B\u1E5D\u1E5F\u1E61\u1E63\u1E65\u1E67\u1E69\u1E6B\u1E6D\u1E6F\u1E71\u1E73\u1E75\u1E77\u1E79\u1E7B\u1E7D\u1E7F\u1E81\u1E83\u1E85\u1E87\u1E89\u1E8B\u1E8D\u1E8F\u1E91\u1E93\u1E95-\u1E9D\u1E9F\u1EA1\u1EA3\u1EA5\u1EA7\u1EA9\u1EAB\u1EAD\u1EAF\u1EB1\u1EB3\u1EB5\u1EB7\u1EB9\u1EBB\u1EBD\u1EBF\u1EC1\u1EC3\u1EC5\u1EC7\u1EC9\u1ECB\u1ECD\u1ECF\u1ED1\u1ED3\u1ED5\u1ED7\u1ED9\u1EDB\u1EDD\u1EDF\u1EE1\u1EE3\u1EE5\u1EE7\u1EE9\u1EEB\u1EED\u1EEF\u1EF1\u1EF3\u1EF5\u1EF7\u1EF9\u1EFB\u1EFD\u1EFF-\u1F07\u1F10-\u1F15\u1F20-\u1F27\u1F30-\u1F37\u1F40-\u1F45\u1F50-\u1F57\u1F60-\u1F67\u1F70-\u1F7D\u1F80-\u1F87\u1F90-\u1F97\u1FA0-\u1FA7\u1FB0-\u1FB4\u1FB6-\u1FB7\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FC7\u1FD0-\u1FD3\u1FD6-\u1FD7\u1FE0-\u1FE7\u1FF2-\u1FF4\u1FF6-\u1FF7\u210A\u210E-\u210F\u2113\u212F\u2134\u2139\u213C-\u213D\u2146-\u2149\u214E\u2184\u2C30-\u2C5E\u2C61\u2C65-\u2C66\u2C68\u2C6A\u2C6C\u2C71\u2C73-\u2C74\u2C76-\u2C7B\u2C81\u2C83\u2C85\u2C87\u2C89\u2C8B\u2C8D\u2C8F\u2C91\u2C93\u2C95\u2C97\u2C99\u2C9B\u2C9D\u2C9F\u2CA1\u2CA3\u2CA5\u2CA7\u2CA9\u2CAB\u2CAD\u2CAF\u2CB1\u2CB3\u2CB5\u2CB7\u2CB9\u2CBB\u2CBD\u2CBF\u2CC1\u2CC3\u2CC5\u2CC7\u2CC9\u2CCB\u2CCD\u2CCF\u2CD1\u2CD3\u2CD5\u2CD7\u2CD9\u2CDB\u2CDD\u2CDF\u2CE1\u2CE3-\u2CE4\u2CEC\u2CEE\u2CF3\u2D00-\u2D25\u2D27\u2D2D\uA641\uA643\uA645\uA647\uA649\uA64B\uA64D\uA64F\uA651\uA653\uA655\uA657\uA659\uA65B\uA65D\uA65F\uA661\uA663\uA665\uA667\uA669\uA66B\uA66D\uA681\uA683\uA685\uA687\uA689\uA68B\uA68D\uA68F\uA691\uA693\uA695\uA697\uA699\uA69B\uA723\uA725\uA727\uA729\uA72B\uA72D\uA72F-\uA731\uA733\uA735\uA737\uA739\uA73B\uA73D\uA73F\uA741\uA743\uA745\uA747\uA749\uA74B\uA74D\uA74F\uA751\uA753\uA755\uA757\uA759\uA75B\uA75D\uA75F\uA761\uA763\uA765\uA767\uA769\uA76B\uA76D\uA76F\uA771-\uA778\uA77A\uA77C\uA77F\uA781\uA783\uA785\uA787\uA78C\uA78E\uA791\uA793-\uA795\uA797\uA799\uA79B\uA79D\uA79F\uA7A1\uA7A3\uA7A5\uA7A7\uA7A9\uA7AF\uA7B5\uA7B7\uA7B9\uA7BB\uA7BD\uA7BF\uA7C3\uA7FA\uAB30-\uAB5A\uAB60-\uAB67\uAB70-\uABBF\uFB00-\uFB06\uFB13-\uFB17\uFF41-\uFF5A]|(?:\uD801[\uDC28-\uDC4F\uDCD8-\uDCFB]|\uD803[\uDCC0-\uDCF2]|\uD806[\uDCC0-\uDCDF]|\uD81B[\uDE60-\uDE7F]|\uD835[\uDC1A-\uDC33\uDC4E-\uDC54\uDC56-\uDC67\uDC82-\uDC9B\uDCB6-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDCCF\uDCEA-\uDD03\uDD1E-\uDD37\uDD52-\uDD6B\uDD86-\uDD9F\uDDBA-\uDDD3\uDDEE-\uDE07\uDE22-\uDE3B\uDE56-\uDE6F\uDE8A-\uDEA5\uDEC2-\uDEDA\uDEDC-\uDEE1\uDEFC-\uDF14\uDF16-\uDF1B\uDF36-\uDF4E\uDF50-\uDF55\uDF70-\uDF88\uDF8A-\uDF8F\uDFAA-\uDFC2\uDFC4-\uDFC9\uDFCB]|\uD83A[\uDD22-\uDD43]))

Note that a regex implementation of \p{Lu} or \p{Pl} actually calls a
non standard function to test the value.

The character classes shown here are done differently and are linear, standard
and pretty slow, when jammed into mostly a single class.


Some insight on how a Regex engine (in general) implements Unicode Property Classes:

Examine these performance characteristics between the property
and the class block (like above)

Regex1:  LONG CLASS 
< none >
Completed iterations:   50  /  50     ( x 1 )
Matches found per iteration:   1788
Elapsed Time:    0.73 s,   727.58 ms,   727584 µs
Matches per sec:   122,872


Regex2:   \p{Lu}
Options:  < ICU - none >
Completed iterations:   50  /  50     ( x 1 )
Matches found per iteration:   1788
Elapsed Time:    0.07 s,   65.32 ms,   65323 µs
Matches per sec:   1,368,583

Wow what a difference !!

Lets see how Properties might be implemented

Array of Pointers [ 10FFFF ] where each index is is a Code Point

  • Each pointer in the Array is to a structure of classification.

    • A Classification structure contains fixed field elemets.
      Some are NULL and do not pertain.
      Some contain category classifications.

      Example : General Category
      This is a bitmapped element that uses 17 out of 64 bits.
      Whatever this Code Point supports has bit(s) set as a mask.

      -Close_Punctuation
      -Connector_Punctuation
      -Control
      -Currency_Symbol
      -Dash_Punctuation
      -Decimal_Number
      -Enclosing_Mark
      -Final_Punctuation
      -Format
      -Initial_Punctuation
      -Letter_Number
      -Line_Separator
      -Lowercase_Letter
      -Math_Symbol
      -Modifier_Letter
      -Modifier_Symbol
      -Nonspacing_Mark
      -Open_Punctuation
      -Other_Letter
      -Other_Number
      -Other_Punctuation
      -Other_Symbol
      -Paragraph_Separator
      -Private_Use
      -Space_Separator
      -Spacing_Mark
      -Surrogate
      -Titlecase_Letter
      -Unassigned
      -Uppercase_Letter

When a regex is parsed with something like this \p{Lu} it
is translated directly into

  • Classification Structure element offset : General Category
  • A check of that element for bit item : Uppercase_Letter

Another example, when a regex is parsed with punctuation property \p{P} it
is translated into

  • Classification Structure element offset : General Category
  • A check of that element for any of these items bits, which are joined into a mask :

    -Close_Punctuation
    -Connector_Punctuation
    -Dash_Punctuation
    -Final_Punctuation
    -Initial_Punctuation
    -Open_Punctuation
    -Other_Punctuation

The offset and bit or bit(mask) are stored as a regex step for that property.

The lookup table is created once for all Unicode Code Points using this array.

When a character is checked, it is as simple as using the CP as an index into this array and checking the Classification Structure's specific element for that bit(mask).

This structure is expandable and indirect to provide much more complex look ups. This is just a simple example.


Compare that direct lookup with a character class search :

All classes are a linear list of items searched from left to right.
In this comparison, given our target string contains only the complete Upper Case Unicode Letters only, the law of averages would predict that half of the items in the class would have to be ranged checked to find a match.

This is a huge disadvantage in performance.

However, if the lookup tables are not there or are not up to date with the latest Unicode release (12 as of this date)
then this would be the only way.

In fact, it is mostly the only way to get the complete Emoji
characters as there is no specific property (or reasoning) to their assignment.

Connect Device to Mac localhost Server?

  1. Connect your iPhone to your Mac via USB.

  2. Go to Network Utility (cmd+space and type "network utility")

  3. Go to the "Info" tab

  4. Click on the drop down menu that says "Wi-Fi" and select "iPhone USB" as shown here:

    Photo for Step 4

  5. You'll find an IP address like "xxx.xxx.xx.xx" or similar. Open Safari browser on your iPhone and enter IP_address:port_number

    Example: 169.254.72.86:3000

[NOTE: If the IP address field is blank, make sure your iPhone is connected via USB, quit Network Utility, open it again and check for the IP address.]

rails generate model

You need to create new rails application first. Run

rails new mebay
cd mebay
bundle install
rails generate model ...

And try to find Rails 3 tutorial, there are a lot of changes since 2.1 Guides (http://guides.rubyonrails.org/getting_started.html) are good start point.

How to give a pattern for new line in grep?

You can use this way...

grep -P '^\s$' file
  • -P is used for Perl regular expressions (an extension to POSIX grep).
  • \s match the white space characters; if followed by *, it matches an empty line also.
  • ^ matches the beginning of the line. $ matches the end of the line.

select the TOP N rows from a table

In MySql, you can get 10 rows starting from row 20 using:

SELECT * FROM Reflow  
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC
LIMIT 10 OFFSET 20 --Equivalent to LIMIT 20, 10

How can I add or update a query string parameter?

It's so simple with URLSearchParams, supported in all modern browsers (caniuse).

_x000D_
_x000D_
let p = new URLSearchParams();
p.set("foo", "bar");
p.set("name", "Jack & Jill?");
console.log("http://example.com/?" + p.toString());
_x000D_
_x000D_
_x000D_

If you want to modify the existing URL, construct the object like this: new URLSearchParams(window.location.search) and assign the string to window.location.search.

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

Its as simple as this:

CREATE FUNCTION InlineMax
(
    @p1 sql_variant,
    @p2 sql_variant
)  RETURNS sql_variant
AS
BEGIN
    RETURN CASE 
        WHEN @p1 IS NULL AND @p2 IS NOT NULL THEN @p2 
        WHEN @p2 IS NULL AND @p1 IS NOT NULL THEN @p1
        WHEN @p1 > @p2 THEN @p1
        ELSE @p2 END
END;