Programs & Examples On #Stretchblt

Changing the highlight color when selecting text in an HTML text input

Thanks for the links, but it does seem as if the actual text highlighting just isn't exposed.

As far as the actual issue at hand, I ended up opting for a different approach by eliminating the need for a text input altogether and using innerHTML with some JavaScript. Not only does it get around the text highlighting, it actually looks much cleaner.

This granular of a tweak to an HTML form control is just another good argument for eliminating form controls altogether. Haha!

Oracle "(+)" Operator

In Oracle, (+) denotes the "optional" table in the JOIN. So in your query,

SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id=b.id(+)

it's a LEFT OUTER JOIN of table 'b' to table 'a'. It will return all data of table 'a' without losing its data when the other side (optional table 'b') has no data.

Diagram of Left Outer Join

The modern standard syntax for the same query would be

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a
LEFT JOIN b ON a.id=b.id

or with a shorthand for a.id=b.id (not supported by all databases):

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a
LEFT JOIN b USING(id)

If you remove (+) then it will be normal inner join query

Older syntax, in both Oracle and other databases:

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id=b.id

More modern syntax:

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a
INNER JOIN b ON a.id=b.id

Or simply:

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a
JOIN b ON a.id=b.id

Diagram of Inner Join

It will only return all data where both 'a' & 'b' tables 'id' value is same, means common part.

If you want to make your query a Right Join

This is just the same as a LEFT JOIN, but switches which table is optional.

Diagram of Right Outer Join

Old Oracle syntax:

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id(+)=b.id

Modern standard syntax:

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a
RIGHT JOIN b ON a.id=b.id

Ref & help:

https://asktom.oracle.com/pls/asktom/f?p=100:11:::::P11_QUESTION_ID:6585774577187

Left Outer Join using + sign in Oracle 11g

https://www.w3schools.com/sql/sql_join_left.asp

How to check if a variable exists in a FreeMarker template?

Also I think if_exists was used like:

Hi ${userName?if_exists}, How are you?

which will not break if userName is null, the result if null would be:

Hi , How are you?

if_exists is now deprecated and has been replaced with the default operator ! as in

Hi ${userName!}, How are you?

the default operator also supports a default value, such as:

Hi ${userName!"John Doe"}, How are you?

How to handle a single quote in Oracle SQL

Use two single-quotes

SQL> SELECT 'D''COSTA' name FROM DUAL;

NAME
-------
D'COSTA

Alternatively, use the new (10g+) quoting method:

SQL> SELECT q'$D'COSTA$' NAME FROM DUAL;

NAME
-------
D'COSTA

XML string to XML document

Using Linq to xml

Add a reference to System.Xml.Linq

and use

XDocument.Parse(string xmlString)

Edit: Sample follows, xml data (TestConfig.xml)..

<?xml version="1.0"?>
<Tests>
  <Test TestId="0001" TestType="CMD">
    <Name>Convert number to string</Name>
    <CommandLine>Examp1.EXE</CommandLine>
    <Input>1</Input>
    <Output>One</Output>
  </Test>
  <Test TestId="0002" TestType="CMD">
    <Name>Find succeeding characters</Name>
    <CommandLine>Examp2.EXE</CommandLine>
    <Input>abc</Input>
    <Output>def</Output>
  </Test>
  <Test TestId="0003" TestType="GUI">
    <Name>Convert multiple numbers to strings</Name>
    <CommandLine>Examp2.EXE /Verbose</CommandLine>
    <Input>123</Input>
    <Output>One Two Three</Output>
  </Test>
  <Test TestId="0004" TestType="GUI">
    <Name>Find correlated key</Name>
    <CommandLine>Examp3.EXE</CommandLine>
    <Input>a1</Input>
    <Output>b1</Output>
  </Test>
  <Test TestId="0005" TestType="GUI">
    <Name>Count characters</Name>
    <CommandLine>FinalExamp.EXE</CommandLine>
    <Input>This is a test</Input>
    <Output>14</Output>
  </Test>
  <Test TestId="0006" TestType="GUI">
    <Name>Another Test</Name>
    <CommandLine>Examp2.EXE</CommandLine>
    <Input>Test Input</Input>
    <Output>10</Output>
  </Test>
</Tests>

C# usage...

XElement root = XElement.Load("TestConfig.xml");
IEnumerable<XElement> tests =
    from el in root.Elements("Test")
    where (string)el.Element("CommandLine") == "Examp2.EXE"
    select el;
foreach (XElement el in tests)
    Console.WriteLine((string)el.Attribute("TestId"));

This code produces the following output: 0002 0006

Difference between Width:100% and width:100vw?

vw and vh stand for viewport width and viewport height respectively.

The difference between using width: 100vw instead of width: 100% is that while 100% will make the element fit all the space available, the viewport width has a specific measure, in this case the width of the available screen, including the document margin.

If you set the style body { margin: 0 }, 100vw should behave the same as 100%.

Additional notes

Using vw as unit for everything in your website, including font sizes and heights, will make it so that the site is always displayed proportionally to the device's screen width regardless of it's resolution. This makes it super easy to ensure your website is displayed properly in both workstation and mobile.

You can set font-size: 1vw (or whatever size suits your project) in your body CSS and everything specified in rem units will automatically scale according to the device screen, so it's easy to port existing projects and even frameworks (such as Bootstrap) to this concept.

How do I rename a column in a database table using SQL?

In Informix, you can use:

RENAME COLUMN TableName.OldName TO NewName;

This was implemented before the SQL standard addressed the issue - if it is addressed in the SQL standard. My copy of the SQL 9075:2003 standard does not show it as being standard (amongst other things, RENAME is not one of the keywords). I don't know whether it is actually in SQL 9075:2008.

MySQL add days to a date

For your need:

UPDATE classes 
SET `date` = DATE_ADD(`date`, INTERVAL 2 DAY)
WHERE id = 161

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

You need the Microsoft.AspNet.WebApi.Core package.

You can see it in the .csproj file:

<Reference Include="System.Web.Http, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.0.0\lib\net45\System.Web.Http.dll</HintPath>
</Reference>

Python creating a dictionary of lists

easy way is:

a = [1,2]
d = {}
for i in a:
  d[i]=[i, ]

print(d)
{'1': [1, ], '2':[2, ]}

Jquery, set value of td in a table?

use .html() along with selector to get/set HTML:

 $('#detailInfo').html('changed value');

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

Uncaught TypeError: undefined is not a function example_app.js:7

This error message tells the whole story. On this line, you are trying to execute a function. However, whatever is being executed is not a function! Instead, it's undefined.

So what's on example_app.js line 7? Looks like this:

var tasks = new ExampleApp.Collections.Tasks(data.tasks);

There is only one function being run on that line. We found the problem! ExampleApp.Collections.Tasks is undefined.

So lets look at where that is declared:

var Tasks = Backbone.Collection.extend({
    model: Task,
    url: '/tasks'
});

If that's all the code for this collection, then the root cause is right here. You assign the constructor to global variable, called Tasks. But you never add it to the ExampleApp.Collections object, a place you later expect it to be.

Change that to this, and I bet you'd be good.

ExampleApp.Collections.Tasks = Backbone.Collection.extend({
    model: Task,
    url: '/tasks'
});

See how important the proper names and line numbers are in figuring this out? Never ever regard errors as binary (it works or it doesn't). Instead read the error, in most cases the error message itself gives you the critical clues you need to trace through to find the real issue.


In Javascript, when you execute a function, it's evaluated like:

expression.that('returns').aFunctionObject(); // js
execute -> expression.that('returns').aFunctionObject // what the JS engine does

That expression can be complex. So when you see undefined is not a function it means that expression did not return a function object. So you have to figure out why what you are trying to execute isn't a function.

And in this case, it was because you didn't put something where you thought you did.

Get all photos from Instagram which have a specific hashtag with PHP

If you only need to display the images base on a tag, then there is not to include the wrapper class "instagram.class.php". As the Media & Tag Endpoints in Instagram API do not require authentication. You can use the following curl based function to retrieve results based on your tag.

 function callInstagram($url)
    {
    $ch = curl_init();
    curl_setopt_array($ch, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => 2
    ));

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
    }

    $tag = 'YOUR_TAG_HERE';
    $client_id = "YOUR_CLIENT_ID";
    $url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id;

    $inst_stream = callInstagram($url);
    $results = json_decode($inst_stream, true);

    //Now parse through the $results array to display your results... 
    foreach($results['data'] as $item){
        $image_link = $item['images']['low_resolution']['url'];
        echo '<img src="'.$image_link.'" />';
    }

How can I remove the string "\n" from within a Ruby string?

When you want to remove a string, rather than replace it you can use String#delete (or its mutator equivalent String#delete!), e.g.:

x = "foo\nfoo"
x.delete!("\n")

x now equals "foofoo"

In this specific case String#delete is more readable than gsub since you are not actually replacing the string with anything.

How to align td elements in center

margin:auto; text-align, if this won't work - try adding display:block; and set there width:200px; (in case your TD is too small).

How to avoid page refresh after button click event in asp.net

if you have some codes in your Page_Load method and you don't want that those execute after button click use if(!IsPostBack) on Page_Load

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
       // put codes here
    }
}

asp:Button is a server control and for send request to server and get response need page refresh. You can use JQuery and Ajax to prevent full Page refresh

Save Screen (program) output to a file

For the Mac terminal:

script -a -t 0 out.txt screen /dev/ttyUSB0 115200

Details

  • script: A built-in application to "make a typescript of terminal session"
  • -a: Append to output file
  • -t 0: Time between writing to output file is 0 seconds, so out.txt is updated for every new character
  • out.txt: Is just the output file name
  • screen /dev/ttyUSB0 115200: Command from question for connecting to an external device

You can then use tail to see that the file is updating.

tail -100 out.txt

How do I generate a random int number?

Why not use int randomNumber = Random.Range(start_range, end_range) ?

How can I find and run the keytool

Few observations while I was getting the same problem (Windows). 1. Shell pipe is important. 2. If you are using OpenSSL or Cygwin, definitely you have to install it. 3. keytool comes with JDK so either you have to point to it in the command or you have cd to the JDK/bin folder (where the exe resides) 4. The debug keystore is typically located at ~/.android/debug.keystore 5. password is "android" whether you -keypass it or type it when prompted. 6. For the alias name, you can open (DO NOT SAVE, just open and close) the keystore file with any editor and read it. 7. MOST IMPORTANT - There is a difference is specifying the keystore path within quotes and without. I got it working by using the keystore path within the double quotes. As remix090378 said and as per the instruction, this command indeed worked - cd C:\Program Files\Java\jdk1.7.0_09\bin

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\userName.android\debug.keystore" -list -v

Ruby on Rails form_for select field with class

This work for me

<%= f.select :status, [["Single", "single"], ["Married", "married"], ["Engaged", "engaged"], ["In a Relationship", "relationship"]], {}, {class: "form-control"} %>

Convert a list of characters into a string

This may be the fastest way:

>> from array import array
>> a = ['a','b','c','d']
>> array('B', map(ord,a)).tostring()
'abcd'

How to get the current date/time in Java

If you want the current date as String, try this:

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));

or

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));

http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

If you download the project from github or copy from other place, then the dependencies library do not exists, there will be this issue.

You just need to cd to the project/project_name directory in terminal , use ls to check whether there is a Podfile file.

if there exists the Podfile, you just need to install the dependencyies:

pod install

"NODE_ENV" is not recognized as an internal or external command, operable command or batch file

If anyone else came here like me trying to find a solution for the error:

'env' is not recognized as an internal or external command

The reason I got this is that I was migrating an angular solution from a mac development machine over to a windows 10 desktop. This is how I resolved it.

  1. run npm install --save-dev cross-env

  2. go into my package.json file and change all the script references from env <whatever> to cross-env <whatever>

Then my commands like: npm run start:some_random_environment_var now run fine on Windows 10.

Display all views on oracle database

Open a new worksheet on the related instance (Alt-F10) and run the following query

SELECT view_name, owner
FROM sys.all_views 
ORDER BY owner, view_name

Using Tkinter in python to edit the title bar

For anybody who runs into the issue of having two windows open, and runs across this question. Here is how I stumbled upon a solution.

The reason the code in this question is producing two windows is because

Frame.__init__(self, parent)

is being run before

self.root = Tk()

The simple fix is to run Tk() before running Frame.__init_()

self.root = Tk()
Frame.__init__(self, parent)

Why that is the case, I'm not entirely sure.

git clone from another directory

None of these worked for me. I am using git-bash on windows. Found out the problem was with my file path formatting.

WRONG:

git clone F:\DEV\MY_REPO\.git

CORRECT:

git clone /F/DEV/MY_REPO/.git

These commands are done from the folder you want the repo folder to appear in.

Try-catch speeding up my code?

9 years later and the bug is still there! You can see it easily with:

   static void Main( string[] args )
    {
      int hundredMillion = 1000000;
      DateTime start = DateTime.Now;
      double sqrt;
      for (int i=0; i < hundredMillion; i++)
      {
        sqrt = Math.Sqrt( DateTime.Now.ToOADate() );
      }
      DateTime end = DateTime.Now;

      double sqrtMs = (end - start).TotalMilliseconds;

      Console.WriteLine( "Elapsed milliseconds: " + sqrtMs );

      DateTime start2 = DateTime.Now;

      double sqrt2;
      for (int i = 0; i < hundredMillion; i++)
      {
        try
        {
          sqrt2 = Math.Sqrt( DateTime.Now.ToOADate() );
        }
        catch (Exception e)
        {
          int br = 0;
        }
      }
      DateTime end2 = DateTime.Now;

      double sqrtMsTryCatch = (end2 - start2).TotalMilliseconds;

      Console.WriteLine( "Elapsed milliseconds: " + sqrtMsTryCatch );

      Console.WriteLine( "ratio is " + sqrtMsTryCatch / sqrtMs );

      Console.ReadLine();
    }

The ratio is less than one on my machine, running the latest version of MSVS 2019, .NET 4.6.1

How to get current route

To get the route segments:

import { ActivatedRoute, UrlSegment } from '@angular/router';

constructor( route: ActivatedRoute) {}

getRoutes() { const segments: UrlSegment[] = this.route.snapshot.url; }

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

Drop all tables command

Or at a shell prompt, in just two lines, without a named temporary file, assuming $db is the SQLite database name:

echo "SELECT 'DROP TABLE ' || name ||';' FROM sqlite_master WHERE type = 'table';" |
    sqlite3 -readonly "$db" | sqlite3 "$db"

How to return multiple values in one column (T-SQL)?

Well... I see that an answer was already accepted... but I think you should see another solutions anyway:

/* EXAMPLE */
DECLARE @UserAliases TABLE(UserId INT , Alias VARCHAR(10))
INSERT INTO @UserAliases (UserId,Alias) SELECT 1,'MrX'
     UNION ALL SELECT 1,'MrY' UNION ALL SELECT 1,'MrA'
     UNION ALL SELECT 2,'Abc' UNION ALL SELECT 2,'Xyz'

/* QUERY */
;WITH tmp AS ( SELECT DISTINCT UserId FROM @UserAliases )
SELECT 
    LEFT(tmp.UserId, 10) +
    '/ ' +
    STUFF(
            (   SELECT ', '+Alias 
                FROM @UserAliases 
                WHERE UserId = tmp.UserId 
                FOR XML PATH('') 
            ) 
            , 1, 2, ''
        ) AS [UserId/Alias]
FROM tmp

/* -- OUTPUT
  UserId/Alias
  1/ MrX, MrY, MrA
  2/ Abc, Xyz    
*/

<input type="file"> limit selectable files by extensions

Easy way of doing it would be:

<input type="file" accept=".gif,.jpg,.jpeg,.png,.doc,.docx">

Works with all browsers, except IE9. I haven't tested it in IE10+.

How do I find the location of my Python site-packages directory?

Let's say you have installed the package 'django'. import it and type in dir(django). It will show you, all the functions and attributes with that module. Type in the python interpreter -

>>> import django
>>> dir(django)
['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'get_version']
>>> print django.__path__
['/Library/Python/2.6/site-packages/django']

You can do the same thing if you have installed mercurial.

This is for Snow Leopard. But I think it should work in general as well.

How to get just the parent directory name of a specific file

From java 7 I would prefer to use Path. You only need to put path into:

Path dddDirectoryPath = Paths.get("C:/aaa/bbb/ccc/ddd/test.java");

and create some get method:

public String getLastDirectoryName(Path directoryPath) {
   int nameCount = directoryPath.getNameCount();
   return directoryPath.getName(nameCount - 1);
}

How to get multiple select box values using jQuery?

var selected=[];
 $('#multipleSelect :selected').each(function(){
     selected[$(this).val()]=$(this).text();
    });
console.log(selected);

Yet another approch to this problem. The selected array will have the indexes as the option values and the each array item will have the text as its value.

for example

<select id="multipleSelect" multiple="multiple">
    <option value="abc">Text 1</option>
    <option value="def">Text 2</option>
    <option value="ghi">Text 3</option>
</select>

if say option 1 and 2 are selected.

the selected array will be :

selected['abc']=1; 
selected['def']=2.

remove space between paragraph and unordered list

I got pretty good results with my HTML mailing list by using the following:

p { margin-bottom: 0; }
ul { margin-top: 0; }

This does not reset all margin values but only those that create such a gap before ordered list, and still doesn't assume anything about default margin values.

Div not expanding even with content inside

You have a fixed height on .infohold, so the .albumhold div will only add up to the height of .infohold (20px) + .albumpic (110px) plus any padding or margin which I haven't included there.

Try removing the fixed height on .infohold and see what happens.

Find kth smallest element in a binary search tree in Optimum way

For a binary search tree, an inorder traversal will return elements ... in order.

Just do an inorder traversal and stop after traversing k elements.

O(1) for constant values of k.

Allow only numbers and dot in script

Instead of using this:

onkeypress="return fun_AllowOnlyAmountAndDot(this);"

You should use this:

onkeypress="return fun_AllowOnlyAmountAndDot(this.id);"

How to compare two maps by their values

If anyone is looking to do it in Java 8 streams below is the example.

import java.util.HashMap;
import java.util.Map;

public class CompareTwoMaps {

    public static void main(String[] args) {

        Map<String, String> a = new HashMap<>();
        a.put("foo", "bar" + "bar");
        a.put("zoo", "bar" + "bar");

        Map<String, String> b = new HashMap<>();
        b.put(new String("foo"), "bar" + "bar");
        b.put(new String("zoo"), "bar" + "bar");

        System.out.println("result = " + areEqual(a, b));
    }

    private static boolean areEqual(Map<String, String> first, Map<String, String> second) {
        return first.entrySet().stream()
                .allMatch(e -> e.getValue().equals(second.get(e.getKey())));
    }
}

GROUP BY and COUNT in PostgreSQL

Using OVER() and LIMIT 1:

SELECT COUNT(1) OVER()
FROM posts 
   INNER JOIN votes ON votes.post_id = posts.id 
GROUP BY posts.id
LIMIT 1;

Is there any JSON Web Token (JWT) example in C#?

Here is a working example:

http://zavitax.wordpress.com/2012/12/17/logging-in-with-google-service-account-in-c-jwt/

It took quite some time to collect the pieces scattered over the web, the docs are rather incomplete...

Read a text file in R line by line

You should take care with readLines(...) and big files. Reading all lines at memory can be risky. Below is a example of how to read file and process just one line at time:

processFile = function(filepath) {
  con = file(filepath, "r")
  while ( TRUE ) {
    line = readLines(con, n = 1)
    if ( length(line) == 0 ) {
      break
    }
    print(line)
  }

  close(con)
}

Understand the risk of reading a line at memory too. Big files without line breaks can fill your memory too.

Calling constructors in c++ without new

In append to JaredPar answer

1-usual ctor, 2nd-function-like-ctor with temporary object.

Compile this source somewhere here http://melpon.org/wandbox/ with different compilers

// turn off rvo for clang, gcc with '-fno-elide-constructors'

#include <stdio.h>
class Thing {
public:
    Thing(const char*){puts(__FUNCTION__ );}
    Thing(const Thing&){puts(__FUNCTION__ );}   
    ~Thing(){puts(__FUNCTION__);}
};
int main(int /*argc*/, const char** /*argv*/) {
    Thing myThing = Thing("asdf");
}

And you will see the result.

From ISO/IEC 14882 2003-10-15

8.5, part 12

Your 1st,2nd construction are called direct-initialization

12.1, part 13

A functional notation type conversion (5.2.3) can be used to create new objects of its type. [Note: The syntax looks like an explicit call of the constructor. ] ... An object created in this way is unnamed. [Note: 12.2 describes the lifetime of temporary objects. ] [Note: explicit constructor calls do not yield lvalues, see 3.10. ]


Where to read about RVO:

12 Special member functions / 12.8 Copying class objects/ Part 15

When certain criteria are met, an implementation is allowed to omit the copy construction of a class object, even if the copy constructor and/or destructor for the object have side effects.

Turn off it with compiler flag from comment to view such copy-behavior)

How to compare two strings are equal in value, what is the best method?

You should use some form of the String#equals(Object) method. However, there is some subtlety in how you should do it:

If you have a string literal then you should use it like this:

"Hello".equals(someString);

This is because the string literal "Hello" can never be null, so you will never run into a NullPointerException.

If you have a string and another object then you should use:

myString.equals(myObject);

You can make sure you are actually getting string equality by doing this. For all you know, myObject could be of a class that always returns true in its equals method!

Start with the object less likely to be null because this:

String foo = null;
String bar = "hello";
foo.equals(bar);

will throw a NullPointerException, but this:

String foo = null;
String bar = "hello";
bar.equals(foo);

will not. String#equals(Object) will correctly handle the case when its parameter is null, so you only need to worry about the object you are dereferencing--the first object.

Node Sass couldn't find a binding for your current environment

remove the /node-modules folder and install it again or run the gradle task deploy after it removed

/Users/warren/Sites/random-docs/my-cms/node_modules/node-sass/vendor/darwin-x64-11/binding.node

It solves your problem.

Can I force a UITableView to hide the separator between empty cells?

If you use iOS 7 SDK, this is very simple.

Just add this line in your viewDidLoad method:

self.yourTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

Replace only text inside a div using jquery

Text shouldn't be on its own. Put it into a span element.

Change it to this:

<div id="one">
       <div class="first"></div>
       <span>"Hi I am text"</span>
       <div class="second"></div>
       <div class="third"></div>
</div>
$('#one span').text('Hi I am replace');

Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

Obviously that previous posts are useful, but any of above are not helpful in my case. The reason was in wrong sequence of loading scripts. For example, in my case, controller editCtrl.js depends on (uses) ui-bootstrap-tpls.js, so it should be loaded first. This caused an error:

<script src="scripts/app/station/editCtrl.js"></script>
<script src="scripts/angular-ui/ui-bootstrap-tpls.js"></script>

This is right, works:

<script src="scripts/angular-ui/ui-bootstrap-tpls.js"></script>
<script src="scripts/app/station/editCtrl.js"></script>

So, to fix the error you need first declare all scripts without dependencies, and then scripts that depends on previously declared.

Using underscores in Java variables and method names

Personally, I think a language shouldn't make rules about coding style. It is a matter of preferences, usage, convenience, concept about readability.
Now, a project must set coding rules, for consistency across listings. You might not agree with these rules, but you should stick to them if you want to contribute (or work in a team).

At least, IDEs like Eclispe are agnostic, allowing to set rules like variable prefixes or suffixes, various styles of brace placement and space management, etc. So you can use it to reformat code along your guidelines.

Note: I am among those keeping their old habits from C/C++, coding Java with m_ prefixes for member variables (and s_ for static ones), prefixing booleans with an initial b, using an initial uppercase letter for function names and aligning braces... The horror for Java fundamentalists! ;-)
Funnily, that's the conventions used where I work... probably because the main initial developer comes from MFC world! :-D

What is offsetHeight, clientHeight, scrollHeight?

Offset Means "the amount or distance by which something is out of line". Margin or Borders are something which makes the actual height or width of an HTML element "out of line". It will help you to remember that :

  • offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar.

On the other hand, clientHeight is something which is you can say kind of the opposite of OffsetHeight. It doesn't include the border or margins. It does include the padding because it is something that resides inside of the HTML container, so it doesn't count as extra measurements like margin or border. So :

  • clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin.

ScrollHeight is all the scrollable area, so your scroll will never run over your margin or border, so that's why scrollHeight doesn't include margin or borders but yeah padding does. So:

  • scrollHeight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar. The height is measured in the same way as clientHeight: it includes the element's padding, but not its border, margin or horizontal scrollbar.

Get selected value from combo box in C# WPF

How about these:

string yourstringname = (yourComboBox.SelectedItem as ComboBoxItem).Content.ToString();

How to get the response of XMLHttpRequest?

You can get it by XMLHttpRequest.responseText in XMLHttpRequest.onreadystatechange when XMLHttpRequest.readyState equals to XMLHttpRequest.DONE.

Here's an example (not compatible with IE6/7).

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.

$.get('http://example.com', function(responseText) {
    alert(responseText);
});

Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.

JQuery select2 set default value from an option in list?

If you are using an array data source you can do something like below -

$(".select").select2({
    data: data_names
});
data_names.forEach(function(name) {
    if (name.selected) {
        $(".select").select2('val', name.id);
    }
});

This assumes that out of your data set the one item which you want to set as default has an additional attribute called selected and we use that to set the value.

How to uncheck a checkbox in pure JavaScript?

Recommended, without jQuery:

Give your <input> an ID and refer to that. Also, remove the checked="" part of the <input> tag if you want the checkbox to start out unticked. Then it's:

document.getElementById("my-checkbox").checked = true;

Pure JavaScript, with no Element ID (#1):

var inputs = document.getElementsByTagName('input');

for(var i = 0; i<inputs.length; i++){

  if(typeof inputs[i].getAttribute === 'function' && inputs[i].getAttribute('name') === 'copyNewAddrToBilling'){

    inputs[i].checked = true;

    break;

  }
}

Pure Javascript, with no Element ID (#2):

document.querySelectorAll('.text input[name="copyNewAddrToBilling"]')[0].checked = true;

document.querySelector('.text input[name="copyNewAddrToBilling"]').checked = true;

Note that the querySelectorAll and querySelector methods are supported in these browsers: IE8+, Chrome 4+, Safari 3.1+, Firefox 3.5+ and all mobile browsers.

If the element may be missing, you should test for its existence, e.g.:

var input = document.querySelector('.text input[name="copyNewAddrToBilling"]');
if (!input) { return; }

With jQuery:

$('.text input[name="copyNewAddrToBilling"]').prop('checked', true);

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

Exporting the DISPLAY variable is definitely the solution but depending on your setup you may have to do this in a slightly different way.

In my case, I have two different processes: the first one starts Xvfb, the other one launches the tests. So my shell scripting knowledge is a bit rusty but I figured out that exporting the DISPLAY variable from the first process didn't make it available in the second process.

Fortunately, Selenium WebDriver allows you to 'redefine' your environment. This is my function for creating a driver for Chrome in JS. Pretty sure the equivalent exists for your programming language:

const caps = require('selenium-webdriver/lib/capabilities');
const chrome = require('selenium-webdriver/chrome');
const chromedriver = require('chromedriver');

module.exports = function (cfg) {
    let serviceBuilder = new chrome.ServiceBuilder(chromedriver.path);
    let options = chrome.Options.fromCapabilities(caps.Capabilities.chrome());
    let service;
    let myENV = new Map();

    // 're-export' the `DISPLAY` variable
    myENV.set('DISPLAY', ':1');
    serviceBuilder.setEnvironment(myENV);

    service = serviceBuilder.build();

    options.addArguments('disable-setuid-sandbox');
    options.addArguments('no-sandbox');
    options.addArguments('allow-insecure-localhost');
    options.excludeSwitches('test-type');

    return chrome.Driver.createSession(options, service);
};

Undefined reference to `sin`

I had the same problem, which went away after I listed my library last: gcc prog.c -lm

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

These are class stereotypes used in analysis.

  • boundary classes are ones at the boundary of the system - the classes that you or other systems interact with

  • entity classes classes are your typical business entities like "person" and "bank account"

  • control classes implement some business logic or other

Add a property to a JavaScript object using a variable as the name?

With ECMAScript 2015 you can do it directly in object declaration using bracket notation:

var obj = {
  [key]: value
}

Where key can be any sort of expression (e.g. a variable) returning a value:

var obj = {
  ['hello']: 'World',
  [x + 2]: 42,
  [someObject.getId()]: someVar
}

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

In many cases, the needed 'current time' is rather $^T, which is the time at which the script started running, in whole seconds (assuming only 60 second minutes) since the UNIX epoch.

This to prevent that an early part of a script uses a different date (or daylight-saving status) than a later part of a script, for example in query-conditions and other derived values.

For that variant of 'current time', one can use a constant, also to document that it was frozen at compile time:

use constant YMD_HMS_AT_START => POSIX::strftime( "%F %T", localtime $^T );

Alternative higher resolution startup time:

0+ [ Time::HiRes::stat("/proc/$$") ]->[10]

MySQL check if a table exists without throwing an exception

Here is the my solution that I prefer when using stored procedures. Custom mysql function for check the table exists in current database.

delimiter $$

CREATE FUNCTION TABLE_EXISTS(_table_name VARCHAR(45))
RETURNS BOOLEAN
DETERMINISTIC READS SQL DATA
BEGIN
    DECLARE _exists  TINYINT(1) DEFAULT 0;

    SELECT COUNT(*) INTO _exists
    FROM information_schema.tables 
    WHERE table_schema =  DATABASE()
    AND table_name =  _table_name;

    RETURN _exists;

END$$

SELECT TABLE_EXISTS('you_table_name') as _exists

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

google-services.json for different productFlavors

The point of the google-services plugin is to simplify integration of Google features.

Since it only generates android-resources from the google-services.json file, over-complicated gradle-logic negates this point, I think.

So if the Google-docs don’t say which resources are needed for specific Google-features, I would suggest to generate the JSON-file for each relevant buildtype/flavor, see what resources get generated by the plugin and then put those resources manually into their respective src/buildtypeORflavor/res directories.

Delete the references to google-services plugin and the JSON-file after that, and you are done.

For detailed information about the inner workings of google-services gradle-plugin see my other answer:

https://stackoverflow.com/a/33083898/433421

Hash table in JavaScript

Using the function above, you would do:

var myHash = new Hash('one',[1,10,5],'two', [2], 'three',[3,30,300]);

Of course, the following would also work:

var myHash = {}; // New object
myHash['one'] = [1,10,5];
myHash['two'] = [2];
myHash['three'] = [3, 30, 300];

since all objects in JavaScript are hash tables! It would, however, be harder to iterate over since using foreach(var item in object) would also get you all its functions, etc., but that might be enough depending on your needs.

Properties order in Margin

Margin="1,2,3,4"
  1. Left,
  2. Top,
  3. Right,
  4. Bottom

It is also possible to specify just two sizes like this:

Margin="1,2"
  1. Left AND right
  2. Top AND bottom

Finally you can specify a single size:

Margin="1"
  1. used for all sides

The order is the same as in WinForms.

Swapping pointers in C (char, int)

The first thing you need to understand is that when you pass something to a function, that something is copied to the function's arguments.

Suppose you have the following:

void swap1(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
    assert(a == 17);
    assert(b == 42);
    // they're swapped!
}

int x = 42;
int y = 17;
swap1(x, y);
assert(x == 42);
assert(y == 17);
// no, they're not swapped!

The original variables will not be swapped, because their values are copied into the function's arguments. The function then proceeds to swap the values of those arguments, and then returns. The original values are not changed, because the function only swaps its own private copies.

Now how do we work around this? The function needs a way to refer to the original variables, not copies of their values. How can we refer to other variables in C? Using pointers.

If we pass pointers to our variables into the function, the function can swap the values in our variables, instead of its own argument copies.

void swap2(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
    assert(*a == 17);
    assert(*b == 42);
    // they're swapped!
}

int x = 42;
int y = 17;
swap2(&x, &y); // give the function pointers to our variables
assert(x == 17);
assert(y == 42);
// yes, they're swapped!

Notice how inside the function we're not assigning to the pointers, but assigning to what they point to. And the pointers point to our variables x and y. The function is changing directly the values stored in our variables through the pointers we give it. And that's exactly what we needed.

Now what happens if we have two pointer variables and want to swap the pointers themselves (as opposed to the values they point to)? If we pass pointers, the pointers will simply be copied (not the values they point to) to the arguments.

void swap3(int* a, int* b) {
    int* temp = a;
    a = b;
    b = temp;
    assert(*a == 17);
    assert(*b == 42);
    // they're swapped!
}
void swap4(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
    assert(*a == 17);
    assert(*b == 42);
    // they're swapped!
}

int x = 42;
int y = 17;
int* xp = &x;
int* yp = &y;
swap3(xp, yp);
assert(xp == &x);
assert(yp == &y);
assert(x == 42);
assert(y == 17);
// Didn't swap anything!
swap4(xp, yp);
assert(xp == &x);
assert(yp == &y);
assert(x == 17);
assert(y == 42);
// Swapped the stored values instead!

The function swap3 only swaps its own private copies of our pointers that it gets in its arguments. It's the same issue we had with swap1. And swap4 is changing the values our variables point to, not the pointers! We're giving the function a means to refer to the variables x and y but we want them to refer to xp and yp.

How do we do that? We pass it their addresses!

void swap5(int** a, int** b) {
    int* temp = *a;
    *a = *b;
    *b = temp;
    assert(**a == 17);
    assert(**b == 42);
    // they're swapped!
}


int x = 42;
int y = 17;
int* xp = &x;
int* yp = &y;
swap5(&xp, &yp);
assert(xp == &y);
assert(yp == &x);
assert(x == 42);
assert(y == 17);
// swapped only the pointers variables

This way it swaps our pointer variables (notice how xp now points to y) but not the values they point to. We gave it a way to refer to our pointer variables, so it can change them!

By now it should be easy to understand how to swap two strings in the form of char* variables. The swap function needs to receive pointers to char*.

void swapStrings(char** a, char** b){
    char *temp = *a;
    *a = *b;
    *b = temp;
    assert(strcmp(*a, "world") == 0);
    assert(strcmp(*b, "Hello") == 0);
}

char* x = "Hello";
char* y = "world";
swapStrings(&x, &y);
assert(strcmp(x, "world") == 0);
assert(strcmp(y, "Hello") == 0);

How to print VARCHAR(MAX) using Print Statement?

Here is how this should be done:

DECLARE @String NVARCHAR(MAX);
DECLARE @CurrentEnd BIGINT; /* track the length of the next substring */
DECLARE @offset tinyint; /*tracks the amount of offset needed */
set @string = replace(  replace(@string, char(13) + char(10), char(10))   , char(13), char(10))

WHILE LEN(@String) > 1
BEGIN
    IF CHARINDEX(CHAR(10), @String) between 1 AND 4000
    BEGIN
           SET @CurrentEnd =  CHARINDEX(char(10), @String) -1
           set @offset = 2
    END
    ELSE
    BEGIN
           SET @CurrentEnd = 4000
            set @offset = 1
    END   
    PRINT SUBSTRING(@String, 1, @CurrentEnd) 
    set @string = SUBSTRING(@String, @CurrentEnd+@offset, LEN(@String))   
END /*End While loop*/

Taken from http://ask.sqlservercentral.com/questions/3102/any-way-around-the-print-limit-of-nvarcharmax-in-s.html

What are Aggregates and PODs and how/why are they special?

How to read:

This article is rather long. If you want to know about both aggregates and PODs (Plain Old Data) take time and read it. If you are interested just in aggregates, read only the first part. If you are interested only in PODs then you must first read the definition, implications, and examples of aggregates and then you may jump to PODs but I would still recommend reading the first part in its entirety. The notion of aggregates is essential for defining PODs. If you find any errors (even minor, including grammar, stylistics, formatting, syntax, etc.) please leave a comment, I'll edit.

This answer applies to C++03. For other C++ standards see:

What are aggregates and why they are special

Formal definition from the C++ standard (C++03 8.5.1 §1):

An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).

So, OK, let's parse this definition. First of all, any array is an aggregate. A class can also be an aggregate if… wait! nothing is said about structs or unions, can't they be aggregates? Yes, they can. In C++, the term class refers to all classes, structs, and unions. So, a class (or struct, or union) is an aggregate if and only if it satisfies the criteria from the above definitions. What do these criteria imply?

  • This does not mean an aggregate class cannot have constructors, in fact it can have a default constructor and/or a copy constructor as long as they are implicitly declared by the compiler, and not explicitly by the user

  • No private or protected non-static data members. You can have as many private and protected member functions (but not constructors) as well as as many private or protected static data members and member functions as you like and not violate the rules for aggregate classes

  • An aggregate class can have a user-declared/user-defined copy-assignment operator and/or destructor

  • An array is an aggregate even if it is an array of non-aggregate class type.

Now let's look at some examples:

class NotAggregate1
{
  virtual void f() {} //remember? no virtual functions
};

class NotAggregate2
{
  int x; //x is private by default and non-static 
};

class NotAggregate3
{
public:
  NotAggregate3(int) {} //oops, user-defined constructor
};

class Aggregate1
{
public:
  NotAggregate1 member1;   //ok, public member
  Aggregate1& operator=(Aggregate1 const & rhs) {/* */} //ok, copy-assignment  
private:
  void f() {} // ok, just a private function
};

You get the idea. Now let's see how aggregates are special. They, unlike non-aggregate classes, can be initialized with curly braces {}. This initialization syntax is commonly known for arrays, and we just learnt that these are aggregates. So, let's start with them.

Type array_name[n] = {a1, a2, …, am};

if(m == n)
the ith element of the array is initialized with ai
else if(m < n)
the first m elements of the array are initialized with a1, a2, …, am and the other n - m elements are, if possible, value-initialized (see below for the explanation of the term)
else if(m > n)
the compiler will issue an error
else (this is the case when n isn't specified at all like int a[] = {1, 2, 3};)
the size of the array (n) is assumed to be equal to m, so int a[] = {1, 2, 3}; is equivalent to int a[3] = {1, 2, 3};

When an object of scalar type (bool, int, char, double, pointers, etc.) is value-initialized it means it is initialized with 0 for that type (false for bool, 0.0 for double, etc.). When an object of class type with a user-declared default constructor is value-initialized its default constructor is called. If the default constructor is implicitly defined then all nonstatic members are recursively value-initialized. This definition is imprecise and a bit incorrect but it should give you the basic idea. A reference cannot be value-initialized. Value-initialization for a non-aggregate class can fail if, for example, the class has no appropriate default constructor.

Examples of array initialization:

class A
{
public:
  A(int) {} //no default constructor
};
class B
{
public:
  B() {} //default constructor available
};
int main()
{
  A a1[3] = {A(2), A(1), A(14)}; //OK n == m
  A a2[3] = {A(2)}; //ERROR A has no default constructor. Unable to value-initialize a2[1] and a2[2]
  B b1[3] = {B()}; //OK b1[1] and b1[2] are value initialized, in this case with the default-ctor
  int Array1[1000] = {0}; //All elements are initialized with 0;
  int Array2[1000] = {1}; //Attention: only the first element is 1, the rest are 0;
  bool Array3[1000] = {}; //the braces can be empty too. All elements initialized with false
  int Array4[1000]; //no initializer. This is different from an empty {} initializer in that
  //the elements in this case are not value-initialized, but have indeterminate values 
  //(unless, of course, Array4 is a global array)
  int array[2] = {1, 2, 3, 4}; //ERROR, too many initializers
}

Now let's see how aggregate classes can be initialized with braces. Pretty much the same way. Instead of the array elements we will initialize the non-static data members in the order of their appearance in the class definition (they are all public by definition). If there are fewer initializers than members, the rest are value-initialized. If it is impossible to value-initialize one of the members which were not explicitly initialized, we get a compile-time error. If there are more initializers than necessary, we get a compile-time error as well.

struct X
{
  int i1;
  int i2;
};
struct Y
{
  char c;
  X x;
  int i[2];
  float f; 
protected:
  static double d;
private:
  void g(){}      
}; 

Y y = {'a', {10, 20}, {20, 30}};

In the above example y.c is initialized with 'a', y.x.i1 with 10, y.x.i2 with 20, y.i[0] with 20, y.i[1] with 30 and y.f is value-initialized, that is, initialized with 0.0. The protected static member d is not initialized at all, because it is static.

Aggregate unions are different in that you may initialize only their first member with braces. I think that if you are advanced enough in C++ to even consider using unions (their use may be very dangerous and must be thought of carefully), you could look up the rules for unions in the standard yourself :).

Now that we know what's special about aggregates, let's try to understand the restrictions on classes; that is, why they are there. We should understand that memberwise initialization with braces implies that the class is nothing more than the sum of its members. If a user-defined constructor is present, it means that the user needs to do some extra work to initialize the members therefore brace initialization would be incorrect. If virtual functions are present, it means that the objects of this class have (on most implementations) a pointer to the so-called vtable of the class, which is set in the constructor, so brace-initialization would be insufficient. You could figure out the rest of the restrictions in a similar manner as an exercise :).

So enough about the aggregates. Now we can define a stricter set of types, to wit, PODs

What are PODs and why they are special

Formal definition from the C++ standard (C++03 9 §4):

A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined copy assignment operator and no user-defined destructor. Similarly, a POD-union is an aggregate union that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined copy assignment operator and no user-defined destructor. A POD class is a class that is either a POD-struct or a POD-union.

Wow, this one's tougher to parse, isn't it? :) Let's leave unions out (on the same grounds as above) and rephrase in a bit clearer way:

An aggregate class is called a POD if it has no user-defined copy-assignment operator and destructor and none of its nonstatic members is a non-POD class, array of non-POD, or a reference.

What does this definition imply? (Did I mention POD stands for Plain Old Data?)

  • All POD classes are aggregates, or, to put it the other way around, if a class is not an aggregate then it is sure not a POD
  • Classes, just like structs, can be PODs even though the standard term is POD-struct for both cases
  • Just like in the case of aggregates, it doesn't matter what static members the class has

Examples:

struct POD
{
  int x;
  char y;
  void f() {} //no harm if there's a function
  static std::vector<char> v; //static members do not matter
};

struct AggregateButNotPOD1
{
  int x;
  ~AggregateButNotPOD1() {} //user-defined destructor
};

struct AggregateButNotPOD2
{
  AggregateButNotPOD1 arrOfNonPod[3]; //array of non-POD class
};

POD-classes, POD-unions, scalar types, and arrays of such types are collectively called POD-types.
PODs are special in many ways. I'll provide just some examples.

  • POD-classes are the closest to C structs. Unlike them, PODs can have member functions and arbitrary static members, but neither of these two change the memory layout of the object. So if you want to write a more or less portable dynamic library that can be used from C and even .NET, you should try to make all your exported functions take and return only parameters of POD-types.

  • The lifetime of objects of non-POD class type begins when the constructor has finished and ends when the destructor has finished. For POD classes, the lifetime begins when storage for the object is occupied and finishes when that storage is released or reused.

  • For objects of POD types it is guaranteed by the standard that when you memcpy the contents of your object into an array of char or unsigned char, and then memcpy the contents back into your object, the object will hold its original value. Do note that there is no such guarantee for objects of non-POD types. Also, you can safely copy POD objects with memcpy. The following example assumes T is a POD-type:

    #define N sizeof(T)
    char buf[N];
    T obj; // obj initialized to its original value
    memcpy(buf, &obj, N); // between these two calls to memcpy,
    // obj might be modified
    memcpy(&obj, buf, N); // at this point, each subobject of obj of scalar type
    // holds its original value
    
  • goto statement. As you may know, it is illegal (the compiler should issue an error) to make a jump via goto from a point where some variable was not yet in scope to a point where it is already in scope. This restriction applies only if the variable is of non-POD type. In the following example f() is ill-formed whereas g() is well-formed. Note that Microsoft's compiler is too liberal with this rule—it just issues a warning in both cases.

    int f()
    {
      struct NonPOD {NonPOD() {}};
      goto label;
      NonPOD x;
    label:
      return 0;
    }
    
    int g()
    {
      struct POD {int i; char c;};
      goto label;
      POD x;
    label:
      return 0;
    }
    
  • It is guaranteed that there will be no padding in the beginning of a POD object. In other words, if a POD-class A's first member is of type T, you can safely reinterpret_cast from A* to T* and get the pointer to the first member and vice versa.

The list goes on and on…

Conclusion

It is important to understand what exactly a POD is because many language features, as you see, behave differently for them.

What is the difference between i++ and ++i?

int i = 0;
Console.WriteLine(i++); // Prints 0. Then value of "i" becomes 1.
Console.WriteLine(--i); // Value of "i" becomes 0. Then prints 0.

Does this answer your question ?

Function to calculate distance between two coordinates

Calculate the Distance between Two Points in javascript

function distance(lat1, lon1, lat2, lon2, unit) {
        var radlat1 = Math.PI * lat1/180
        var radlat2 = Math.PI * lat2/180
        var theta = lon1-lon2
        var radtheta = Math.PI * theta/180
        var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
        dist = Math.acos(dist)
        dist = dist * 180/Math.PI
        dist = dist * 60 * 1.1515
        if (unit=="K") { dist = dist * 1.609344 }
        if (unit=="N") { dist = dist * 0.8684 }
        return dist
}

For more details refer this: Reference Link

ie8 var w= window.open() - "Message: Invalid argument."

This is an old posting but maybe still useful for someone.

I had the same error message. In the end the problem was an invalid name for the second argument, i.e., I had a line like:

   window.open('/somefile.html', 'a window title', 'width=300');

The problem was 'a window title' as it is not valid. It worked fine with the following line:

   window.open('/somefile.html', '', 'width=300');

In fact, reading carefully I realized that Microsoft does not support a name as second argument. When you look at the official documentation page, you see that Microsoft only allows the following arguments, If using that argument at all:

  • _blank
  • _media
  • _parent
  • _search
  • _self
  • _top

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

ooh! neat question.

Matlab's for loop takes a matrix as input and iterates over its columns. Matlab also handles practically everything by value (no pass-by-reference) so I would expect that it takes a snapshot of the for-loop's input so it's immutable.

here's an example which may help illustrate:

>> A = zeros(4); A(:) = 1:16

A =

     1     5     9    13
     2     6    10    14
     3     7    11    15
     4     8    12    16

>> i = 1; for col = A; disp(col'); A(:,i) = i; i = i + 1; end;
     1     2     3     4

     5     6     7     8

     9    10    11    12

    13    14    15    16

>> A

A =

     1     2     3     4
     1     2     3     4
     1     2     3     4
     1     2     3     4

In Java, can you modify a List while iterating through it?

Use Java 8's removeIf(),

To remove safely,

letters.removeIf(x -> !x.equals("A"));

How can I plot separate Pandas DataFrames as subplots?

You can use the familiar Matplotlib style calling a figure and subplot, but you simply need to specify the current axis using plt.gca(). An example:

plt.figure(1)
plt.subplot(2,2,1)
df.A.plot() #no need to specify for first axis
plt.subplot(2,2,2)
df.B.plot(ax=plt.gca())
plt.subplot(2,2,3)
df.C.plot(ax=plt.gca())

etc...

How to tag an older commit in Git?

OK, You can simply do:

git tag -a <tag> <commit-hash>

So if you want to add tag: 1.0.2 to commit e50f795, just simply do:

git tag -a 1.0.2 e50f795

Also you add a message at the end, using -m, something like this:

git tag -a 1.0.2 e50f795 -m "my message"

After all, you need to push it to the remote, to do that, simply do:

git push origin 1.0.2 

If you have many tags which you don't want to mention them one by one, just simply do:

git push origin --tags

to push all tags together...

Also, I created the steps in the image below, for more clarification of the steps: creating tag on a commit hash

You can also dd the tag in Hub or using tools like SourceTree, to avoid the previous steps, I logged-in to my Bitbucket in this case and doing it from there:

  1. Go to your branch and find the commit you want to add the tag to and click on it:

find your commit in bitbucket

  1. In the commit page, on the right, find where it says No tags and click on the + icon:

find where it says No tags

  1. In the tag name box, add your tag:

add tag name

  1. Now you see that the tag has successfully created:

enter image description here

Why is &#65279; appearing in my HTML?

Here's my 2 cents: I had the same problem and I tried using Notepad++ to convert to UTF-8 no BOM, and also the old "copy to MS notepad then back again" trick, all to no avail. My problem was solved by making sure all files (and 'included' files) were the same file system; I had some files that were Windows format and some that had been copied off a remote Linux server, so were in UNIX format.

What is mapDispatchToProps?

Now suppose there is an action for redux as:

export function addTodo(text) {
  return {
    type: ADD_TODO,
    text
  }
}

When you do import it,

import {addTodo} from './actions';

class Greeting extends React.Component {

    handleOnClick = () => {
        this.props.onTodoClick(); // This prop acts as key to callback prop for mapDispatchToProps
    }

    render() {
        return <button onClick={this.handleOnClick}>Hello Redux</button>;
    }
}

const mapDispatchToProps = dispatch => {
    return {
      onTodoClick: () => { // handles onTodoClick prop's call here
        dispatch(addTodo())
      }
    }
}

export default connect(
    null,
    mapDispatchToProps
)(Greeting);

As function name says mapDispatchToProps(), map dispatch action to props(our component's props)

So prop onTodoClick is a key to mapDispatchToProps function which delegates furthere to dispatch action addTodo.

Also if you want to trim the code and bypass manual implementation, then you can do this,

import {addTodo} from './actions';
class Greeting extends React.Component {

    handleOnClick = () => {
        this.props.addTodo();
    }

    render() {
        return <button onClick={this.handleOnClick}>Hello Redux</button>;
    }
}

export default connect(
    null,
    {addTodo}
)(Greeting);

Which exactly means

const mapDispatchToProps = dispatch => {
    return {
      addTodo: () => { 
        dispatch(addTodo())
      }
    }
}

How to add a named sheet at the end of all Excel sheets?


Try switching the order of your code. You must create the worksheet first in order to name it.

Private Sub CreateSheet()
    Dim ws As Worksheet
    Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
    ws.Name = "Tempo"
End Sub

thanks,

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

You can also use copy con [filename] in a Windows command window (cmd.exe):

C:\copy con yourfile.txt [enter]
C:\CTRL + Z [enter] //hold CTRL key & press "Z" then press Enter key.
^Z
    1 Files Copied.

This will create a file named yourfile.txt in the local directory.

How can I use numpy.correlate to do autocorrelation?

A simple solution without pandas:

import numpy as np

def auto_corrcoef(x):
   return np.corrcoef(x[1:-1], x[2:])[0,1]

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

My case is, it doesn't work wherever I call it, no matter I path the file or not, if I open it with powershell.

but it works if I open it with cmd.

RegEx match open tags except XHTML self-contained tags

There are some nice regexes for replacing HTML with BBCode here. For all you nay-sayers, note that he's not trying to fully parse HTML, just to sanitize it. He can probably afford to kill off tags that his simple "parser" can't understand.

For example:

$store =~ s/http:/http:\/\//gi;
$store =~ s/https:/https:\/\//gi;
$baseurl = $store;

if (!$query->param("ascii")) {
    $html =~ s/\s\s+/\n/gi;
    $html =~ s/<pre(.*?)>(.*?)<\/pre>/\[code]$2\[\/code]/sgmi;
}

$html =~ s/\n//gi;
$html =~ s/\r\r//gi;
$html =~ s/$baseurl//gi;
$html =~ s/<h[1-7](.*?)>(.*?)<\/h[1-7]>/\n\[b]$2\[\/b]\n/sgmi;
$html =~ s/<p>/\n\n/gi;
$html =~ s/<br(.*?)>/\n/gi;
$html =~ s/<textarea(.*?)>(.*?)<\/textarea>/\[code]$2\[\/code]/sgmi;
$html =~ s/<b>(.*?)<\/b>/\[b]$1\[\/b]/gi;
$html =~ s/<i>(.*?)<\/i>/\[i]$1\[\/i]/gi;
$html =~ s/<u>(.*?)<\/u>/\[u]$1\[\/u]/gi;
$html =~ s/<em>(.*?)<\/em>/\[i]$1\[\/i]/gi;
$html =~ s/<strong>(.*?)<\/strong>/\[b]$1\[\/b]/gi;
$html =~ s/<cite>(.*?)<\/cite>/\[i]$1\[\/i]/gi;
$html =~ s/<font color="(.*?)">(.*?)<\/font>/\[color=$1]$2\[\/color]/sgmi;
$html =~ s/<font color=(.*?)>(.*?)<\/font>/\[color=$1]$2\[\/color]/sgmi;
$html =~ s/<link(.*?)>//gi;
$html =~ s/<li(.*?)>(.*?)<\/li>/\[\*]$2/gi;
$html =~ s/<ul(.*?)>/\[list]/gi;
$html =~ s/<\/ul>/\[\/list]/gi;
$html =~ s/<div>/\n/gi;
$html =~ s/<\/div>/\n/gi;
$html =~ s/<td(.*?)>/ /gi;
$html =~ s/<tr(.*?)>/\n/gi;

$html =~ s/<img(.*?)src="(.*?)"(.*?)>/\[img]$baseurl\/$2\[\/img]/gi;
$html =~ s/<a(.*?)href="(.*?)"(.*?)>(.*?)<\/a>/\[url=$baseurl\/$2]$4\[\/url]/gi;
$html =~ s/\[url=$baseurl\/http:\/\/(.*?)](.*?)\[\/url]/\[url=http:\/\/$1]$2\[\/url]/gi;
$html =~ s/\[img]$baseurl\/http:\/\/(.*?)\[\/img]/\[img]http:\/\/$1\[\/img]/gi;

$html =~ s/<head>(.*?)<\/head>//sgmi;
$html =~ s/<object>(.*?)<\/object>//sgmi;
$html =~ s/<script(.*?)>(.*?)<\/script>//sgmi;
$html =~ s/<style(.*?)>(.*?)<\/style>//sgmi;
$html =~ s/<title>(.*?)<\/title>//sgmi;
$html =~ s/<!--(.*?)-->/\n/sgmi;

$html =~ s/\/\//\//gi;
$html =~ s/http:\//http:\/\//gi;
$html =~ s/https:\//https:\/\//gi;

$html =~ s/<(?:[^>'"]*|(['"]).*?\1)*>//gsi;
$html =~ s/\r\r//gi;
$html =~ s/\[img]\//\[img]/gi;
$html =~ s/\[url=\//\[url=/gi;

Setting a width and height on an A tag

It's not an exact duplicate (so far as I can find), but this is a common problem.

display:block is what you need. but you should read the spec to understand why.

jQuery Event Keypress: Which key was pressed?

Actually this is better:

 var code = e.keyCode || e.which;
 if(code == 13) { //Enter keycode
   //Do something
 }

keycloak Invalid parameter: redirect_uri

If you are using the Authorization Code Flow then the response_type query param must be equal to code. See https://www.keycloak.org/docs/3.3/server_admin/topics/sso-protocols/oidc.html

Getting reference to the top-most view/window in iOS application

If you are adding a loading view (an activity indicator view for instance), make sure you have an object of UIWindow class. If you show an action sheet just before you show your loading view, the keyWindow will be the UIActionSheet and not UIWindow. And since the action sheet will go away, the loading view will go away with it. Or that's what was causing me problems.

UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
if (![NSStringFromClass([keyWindow class]) isEqualToString:@"UIWindow"]) {
    // find uiwindow in windows
    NSArray *windows = [UIApplication sharedApplication].windows;
    for (UIWindow *window in windows) {
        if ([NSStringFromClass([window class]) isEqualToString:@"UIWindow"]) {
            keyWindow = window;
            break;
        }
    }
}

Bootstrap change carousel height

This worked for me.

.carousel-item {
  height: 500px;
}

.item, img{
    position: absolute;
    object-fit:cover;
    height: 100% !important;
    width:  100% !important;
    /*min-height: 500px;*/
}

RecyclerView - Get view at particular position

Keep in mind that you have to wait until adapter will added to list, then you can try to getting view by position

final int i = 0;
recyclerView.setAdapter(adapter);
recyclerView.post(new Runnable() {
    @Override
    public void run() {
        View view = recyclerView.getLayoutManager().findViewByPosition(i);
    }
});

What is use of c_str function In c++

Oh must add my own pick here, you will use this when you encode/decode some string obj you transfer between two programs.

Lets say you use base64encode some array in python, and then you want to decode that into c++. Once you have the string you decode from base64decode in c++. In order to get it back to array of float, all you need to do here is

float arr[1024];
memcpy(arr, ur_string.c_str(), sizeof(float) * 1024);

This is pretty common use I suppose.

Get Windows version in a batch file

If you are looking to simply show windows version in a batch file such as Windows 10 etc.

you can simply use the ver command just type ver and the windows version will be displayed

how to remove "," from a string in javascript

If U want to delete more than one characters, say comma and dots you can write

<script type="text/javascript">
  var mystring = "It,is,a,test.string,of.mine" 
  mystring = mystring.replace(/[,.]/g , ''); 
  alert( mystring);
</script>

How to have Android Service communicate with Activity

As mentioned by Madhur, you can use a bus for communication.

In case of using a Bus you have some options:

Otto event Bus library (deprecated in favor of RxJava)

http://square.github.io/otto/

Green Robot’s EventBus

http://greenrobot.org/eventbus/

NYBus (RxBus, implemented using RxJava. very similar to the EventBus)

https://github.com/MindorksOpenSource/NYBus

Default port for SQL Server

If you have access to the server then you can use

select local_tcp_port from sys.dm_exec_connections where local_tcp_port is not null

For full details see port number of SQL Server

Get week of year in JavaScript like in PHP

This adds "getWeek" method to Date.prototype which returns number of week from the beginning of the year. The argument defines which day of the week to consider the first. If no argument passed, first day is assumed Sunday.

/**
 * Get week number in the year.
 * @param  {Integer} [weekStart=0]  First day of the week. 0-based. 0 for Sunday, 6 for Saturday.
 * @return {Integer}                0-based number of week.
 */
Date.prototype.getWeek = function(weekStart) {
    var januaryFirst = new Date(this.getFullYear(), 0, 1);
    if(weekStart !== undefined && (typeof weekStart !== 'number' || weekStart % 1 !== 0 || weekStart < 0 || weekStart > 6)) {
      throw new Error('Wrong argument. Must be an integer between 0 and 6.');
    }
    weekStart = weekStart || 0;
    return Math.floor((((this - januaryFirst) / 86400000) + januaryFirst.getDay() - weekStart) / 7);
};

XAMPP Port 80 in use by "Unable to open process" with PID 4

I had the following error message Port 80 in use by "Unable to open process" with PID 4! Apache WILL NOT start without the configured ports free! You need to uninstall/disable/reconfigure the blocking application or reconfigure Apache and the Control Panel to listen on a different port Starting Check-Timer Control Panel Ready

opened the httpd.conf and changed the listen port from 80 to 1234 in both places

Listen 12.34.56.78:1234

Listen 1234

Then go to Config for the xampp control panel and go to service and port setting and changed the port from 80 to 1234

That worked.

Reading from memory stream to string

string result = Encoding.UTF8.GetString((stream as MemoryStream).ToArray());

Node.js on multi-core machines

[This post is up-to-date as of 2012-09-02 (newer than above).]

Node.js absolutely does scale on multi-core machines.

Yes, Node.js is one-thread-per-process. This is a very deliberate design decision and eliminates the need to deal with locking semantics. If you don't agree with this, you probably don't yet realize just how insanely hard it is to debug multi-threaded code. For a deeper explanation of the Node.js process model and why it works this way (and why it will NEVER support multiple threads), read my other post.

So how do I take advantage of my 16 core box?

Two ways:

  • For big heavy compute tasks like image encoding, Node.js can fire up child processes or send messages to additional worker processes. In this design, you'd have one thread managing the flow of events and N processes doing heavy compute tasks and chewing up the other 15 CPUs.
  • For scaling throughput on a webservice, you should run multiple Node.js servers on one box, one per core and split request traffic between them. This provides excellent CPU-affinity and will scale throughput nearly linearly with core count.

Scaling throughput on a webservice

Since v6.0.X Node.js has included the cluster module straight out of the box, which makes it easy to set up multiple node workers that can listen on a single port. Note that this is NOT the same as the older learnboost "cluster" module available through npm.

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
} else {
  http.Server(function(req, res) { ... }).listen(8000);
}

Workers will compete to accept new connections, and the least loaded process is most likely to win. It works pretty well and can scale up throughput quite well on a multi-core box.

If you have enough load to care about multiple cores, then you are going to want to do a few more things too:

  1. Run your Node.js service behind a web-proxy like Nginx or Apache - something that can do connection throttling (unless you want overload conditions to bring the box down completely), rewrite URLs, serve static content, and proxy other sub-services.

  2. Periodically recycle your worker processes. For a long-running process, even a small memory leak will eventually add up.

  3. Setup log collection / monitoring


PS: There's a discussion between Aaron and Christopher in the comments of another post (as of this writing, its the top post). A few comments on that:

  • A shared socket model is very convenient for allowing multiple processes to listen on a single port and compete to accept new connections. Conceptually, you could think of preforked Apache doing this with the significant caveat that each process will only accept a single connection and then die. The efficiency loss for Apache is in the overhead of forking new processes and has nothing to do with the socket operations.
  • For Node.js, having N workers compete on a single socket is an extremely reasonable solution. The alternative is to set up an on-box front-end like Nginx and have that proxy traffic to the individual workers, alternating between workers for assigning new connections. The two solutions have very similar performance characteristics. And since, as I mentioned above, you will likely want to have Nginx (or an alternative) fronting your node service anyways, the choice here is really between:

Shared Ports: nginx (port 80) --> Node_workers x N (sharing port 3000 w/ Cluster)

vs

Individual Ports: nginx (port 80) --> {Node_worker (port 3000), Node_worker (port 3001), Node_worker (port 3002), Node_worker (port 3003) ...}

There are arguably some benefits to the individual ports setup (potential to have less coupling between processes, have more sophisticated load-balancing decisions, etc.), but it is definitely more work to set up and the built-in cluster module is a low-complexity alternative that works for most people.

VBScript: Using WScript.Shell to Execute a Command Line Program That Accesses Active Directory

The issue turned out to be certificate-related. The WCF service called by the console app uses an X509 cert for authentication, which is installed on the servers that this script is hosted and run from.

On other servers, where the same services are consumed, the certificates were configured as follows:

winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "NETWORK SERVICE"

As they ran within the context of IIS. However, when the script was being run as it would in production, it's under the context of the user themselves. So, the script needed to be modified to the following:

winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "USERS"

Once that change was made, all was well. Thanks to everyone who offered assistance.

Use string in switch case in java

Java (before version 7) does not support String in switch/case. But you can achieve the desired result by using an enum.

private enum Fruit {
    apple, carrot, mango, orange;
}

String value; // assume input
Fruit fruit = Fruit.valueOf(value); // surround with try/catch

switch(fruit) {
    case apple:
        method1;
        break;
    case carrot:
        method2;
        break;
    // etc...
}

Variable might not have been initialized error

You declared them, but you didn't initialize them with a value. Add something like this:

int a = 0;

Python datetime - setting fixed hour and minute after using strptime to get day,month,year

If you have date as a datetime.datetime (or a datetime.date) instance and want to combine it via a time from a datetime.time instance, then you can use the classmethod datetime.datetime.combine:

import datetime
dt = datetime.datetime(2020, 7, 1)
t = datetime.time(12, 34)
combined = datetime.datetime.combine(dt.date(), t)

Plotting in a non-blocking way with Matplotlib

I spent a long time looking for solutions, and found this answer.

It looks like, in order to get what you (and I) want, you need the combination of plt.ion(), plt.show() (not with block=False) and, most importantly, plt.pause(.001) (or whatever time you want). The pause is needed because the GUI events happen while the main code is sleeping, including drawing. It's possible that this is implemented by picking up time from a sleeping thread, so maybe IDEs mess with that—I don't know.

Here's an implementation that works for me on python 3.5:

import numpy as np
from matplotlib import pyplot as plt

def main():
    plt.axis([-50,50,0,10000])
    plt.ion()
    plt.show()

    x = np.arange(-50, 51)
    for pow in range(1,5):   # plot x^1, x^2, ..., x^4
        y = [Xi**pow for Xi in x]
        plt.plot(x, y)
        plt.draw()
        plt.pause(0.001)
        input("Press [enter] to continue.")

if __name__ == '__main__':
    main()

Angular 2.0 and Modal Dialog

I use ngx-bootstrap for my project.

You can find the demo here

The github is here

How to use:

  1. Install ngx-bootstrap

  2. Import to your module

// RECOMMENDED (doesn't work with system.js)
import { ModalModule } from 'ngx-bootstrap/modal';
// or
import { ModalModule } from 'ngx-bootstrap';

@NgModule({
  imports: [ModalModule.forRoot(),...]
})
export class AppModule(){}
  1. Simple static modal
<button type="button" class="btn btn-primary" (click)="staticModal.show()">Static modal</button>
<div class="modal fade" bsModal #staticModal="bs-modal" [config]="{backdrop: 'static'}"
tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
   <div class="modal-content">
      <div class="modal-header">
         <h4 class="modal-title pull-left">Static modal</h4>
         <button type="button" class="close pull-right" aria-label="Close" (click)="staticModal.hide()">
         <span aria-hidden="true">&times;</span>
         </button>
      </div>
      <div class="modal-body">
         This is static modal, backdrop click will not close it.
         Click <b>&times;</b> to close modal.
      </div>
   </div>
</div>
</div>

Add item to array in VBScript

There are a few ways, not including a custom COM or ActiveX object

  1. ReDim Preserve
  2. Dictionary object, which can have string keys and search for them
  3. ArrayList .Net Framework Class, which has many methods including: sort (forward, reverse, custom), insert, remove, binarysearch, equals, toArray, and toString

With the code below, I found Redim Preserve is fastest below 54000, Dictionary is fastest from 54000 to 690000, and Array List is fastest above 690000. I tend to use ArrayList for pushing because of the sorting and array conversion.

user326639 provided FastArray, which is pretty much the fastest.

Dictionaries are useful for searching for the value and returning the index (i.e. field names), or for grouping and aggregation (histograms, group and add, group and concatenate strings, group and push sub-arrays). When grouping on keys, set CompareMode for case in/sensitivity, and check the "exists" property before "add"-ing.

Redim wouldn't save much time for one array, but it's useful for a dictionary of arrays.

'pushtest.vbs
imax = 10000
value = "Testvalue"
s = imax & " of """ & value & """" 

t0 = timer 'ArrayList Method
Set o = CreateObject("System.Collections.ArrayList")
For i = 0 To imax
  o.Add value
Next
s = s & "[AList " & FormatNumber(timer - t0, 3, -1) & "]"
Set o = Nothing

t0 = timer 'ReDim Preserve Method
a = array()
For i = 0 To imax
  ReDim Preserve a(UBound(a) + 1)
  a(UBound(a)) = value
Next
s = s & "[ReDim " & FormatNumber(timer - t0, 3, -1) & "]"
Set a = Nothing

t0 = timer 'Dictionary Method
Set o = CreateObject("Scripting.Dictionary")
For i = 0 To imax
  o.Add i, value
Next
s = s & "[Dictionary " & FormatNumber(timer - t0, 3, -1) & "]"
Set o = Nothing

t0 = timer 'Standard array
Redim a(imax)
For i = 0 To imax
  a(i) = value
Next
s = s & "[Array " & FormatNumber(timer - t0, 3, -1) & "]" & vbCRLF
Set a = Nothing

t0 = timer 'Fast array
a = array()
For i = 0 To imax
 ub = UBound(a)
 If i>ub Then ReDim Preserve a(Int((ub+10)*1.1))
 a(i) = value
Next
ReDim Preserve a(i-1)
s = s & "[FastArr " & FormatNumber(timer - t0, 3, -1) & "]"
Set a = Nothing

MsgBox s

'  10000 of "Testvalue" [ArrayList 0.156][Redim 0.016][Dictionary 0.031][Array 0.016][FastArr 0.016]
'  54000 of "Testvalue" [ArrayList 0.734][Redim 0.672][Dictionary 0.203][Array 0.063][FastArr 0.109]
' 240000 of "Testvalue" [ArrayList 3.172][Redim 5.891][Dictionary 1.453][Array 0.203][FastArr 0.484]
' 690000 of "Testvalue" [ArrayList 9.078][Redim 44.785][Dictionary 8.750][Array 0.609][FastArr 1.406]
'1000000 of "Testvalue" [ArrayList 13.191][Redim 92.863][Dictionary 18.047][Array 0.859][FastArr 2.031]

How can I view all historical changes to a file in SVN

The oddly named "blame" command does this. If you use Tortoise, it gives you a "from revision" dialog, then a file listing with a line by line indicator of Revision number and author next to it.

If you right click on the revision info, you can bring up a "Show log" dialog that gives full checkin information, along with other files that were part of the checkin.

Actionbar notification count icon (badge) like Google has

Just to add. If someone wants to implement a filled circle bubble, heres the code (name it bage_circle.xml):

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="ring"
    android:useLevel="false"
    android:thickness="9dp"
    android:innerRadius="0dp"
    >

    <solid
        android:color="#F00"
        />
    <stroke
        android:width="1dip"
        android:color="#FFF" />

    <padding
        android:top="2dp"
        android:bottom="2dp"/>

</shape>

You may have to adjust the thickness according to your need.

enter image description here

EDIT: Here's the layout for button (name it badge_layout.xml):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <com.joanzapata.iconify.widget.IconButton
        android:layout_width="44dp"
        android:layout_height="44dp"
        android:textSize="24sp"
        android:textColor="@color/white"
        android:background="@drawable/action_bar_icon_bg"
        android:id="@+id/badge_icon_button"/>

    <TextView
        android:id="@+id/badge_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/badge_icon_button"
        android:layout_alignRight="@id/badge_icon_button"
        android:layout_alignEnd="@id/badge_icon_button"
        android:text="10"
        android:paddingEnd="8dp"
        android:paddingRight="8dp"
        android:paddingLeft="8dp"
        android:gravity="center"
        android:textColor="#FFF"
        android:textSize="11sp"
        android:background="@drawable/badge_circle"/>
</RelativeLayout>

In Menu create item:

<item
        android:id="@+id/menu_messages"
        android:showAsAction="always"
        android:actionLayout="@layout/badge_layout"/>

In onCreateOptionsMenu get reference to the Menu item:

    itemMessages = menu.findItem(R.id.menu_messages);

    badgeLayout = (RelativeLayout) itemMessages.getActionView();
    itemMessagesBadgeTextView = (TextView) badgeLayout.findViewById(R.id.badge_textView);
    itemMessagesBadgeTextView.setVisibility(View.GONE); // initially hidden

    iconButtonMessages = (IconButton) badgeLayout.findViewById(R.id.badge_icon_button);
    iconButtonMessages.setText("{fa-envelope}");
    iconButtonMessages.setTextColor(getResources().getColor(R.color.action_bar_icon_color_disabled));

    iconButtonMessages.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (HJSession.getSession().getSessionId() != null) {

                Intent intent = new Intent(getThis(), HJActivityMessagesContexts.class);
                startActivityForResult(intent, HJRequestCodes.kHJRequestCodeActivityMessages.ordinal());
            } else {
                showLoginActivity();
            }
        }
    });

After receiving notification for messages, set the count:

itemMessagesBadgeTextView.setText("" + count);
itemMessagesBadgeTextView.setVisibility(View.VISIBLE);
iconButtonMessages.setTextColor(getResources().getColor(R.color.white));

This code uses Iconify-fontawesome.

compile 'com.joanzapata.iconify:android-iconify-fontawesome:2.1.+'

Scrollbar without fixed height/Dynamic height with scrollbar

Use this:

style="height: 150px; max-height: 300px; overflow: auto;" 

fixe a height, it will be the default height and then a scroll bar come to access to the entire height

How can I remove the gloss on a select element in Safari on Mac?

i have used this and solved my

-webkit-appearance:none;

Count number of occurrences for each unique value

You should change the query to:

SELECT time_col, COUNT(time_col) As Count
FROM time_table
WHERE activity_col = 3
GROUP BY time_col

This vl works correctly.

How to get a resource id with a known resource name?

If I understood right, this is what you want

int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName());

Where "this" is an Activity, written just to clarify.

In case you want a String in strings.xml or an identifier of a UI element, substitute "drawable"

int resourceId = this.getResources().getIdentifier("nameOfResource", "id", this.getPackageName());

I warn you, this way of obtaining identifiers is really slow, use only where needed.

Link to official documentation: Resources.getIdentifier(String name, String defType, String defPackage)

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

If your file has only one main function that you want to call/expose, then you can also just start the file with:

Param($Param1)

You can then call it e.g. as follows:

.\MyFunctions.ps1 -Param1 'value1'

This makes it much more convenient if you want to easily call just that function without having to import the function.

Calculate percentage saved between two numbers?

100% - discounted price / full price

How to write LaTeX in IPython Notebook?

You can choose a cell to be markdown, then write latex code which gets interpreted by mathjax, as one of the responders say above.

Alternatively, Latex section of the iPython notebook tutorial explains this well.

You can either do:

from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0 
\end{eqnarray}""")

or do this:

%%latex
\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}

More info found in this link

How to change working directory in Jupyter Notebook?

Jupyter under the WinPython environment has a batch file in the scripts folder called:

make_working_directory_be_not_winpython.bat

You need to edit the following line in it:

echo WINPYWORKDIR = %%HOMEDRIVE%%%%HOMEPATH%%\Documents\WinPython%%WINPYVER%%\Notebooks>>"%winpython_ini%"

replacing the Documents\WinPython%%WINPYVER%%\Notebooks part with your folder address.

Notice that the %%HOMEDRIVE%%%%HOMEPATH%%\ part will identify the root and user folders (i.e. C:\Users\your_name\) which will allow you to point different WinPython installations on separate computers to the same cloud storage folder (e.g. OneDrive), accessing and working with the same files from different machines. I find that very useful.

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

Suppress the @JoinColumn(name="categoria") on the ID field of the Categoria class and I think it will work.

Observable.of is not a function

You could also import all operators this way:

import {Observable} from 'rxjs/Rx';

how to display none through code behind

I believe this should work:

login_div.Attributes.Add("style","display:none");

How to initialize weights in PyTorch?

If you see a deprecation warning (@Fábio Perez)...

def init_weights(m):
    if type(m) == nn.Linear:
        torch.nn.init.xavier_uniform_(m.weight)
        m.bias.data.fill_(0.01)

net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
net.apply(init_weights)

What is the purpose of using -pedantic in GCC/G++ compiler?

I use it all the time in my coding.

The -ansi flag is equivalent to -std=c89. As noted, it turns off some extensions of GCC. Adding -pedantic turns off more extensions and generates more warnings. For example, if you have a string literal longer than 509 characters, then -pedantic warns about that because it exceeds the minimum limit required by the C89 standard. That is, every C89 compiler must accept strings of length 509; they are permitted to accept longer, but if you are being pedantic, it is not portable to use longer strings, even though a compiler is permitted to accept longer strings and, without the pedantic warnings, GCC will accept them too.

Sending data back to the Main Activity in Android

All these answers are explaining the scenario of your second activity needs to be finish after sending the data.

But in case if you don't want to finish the second activity and want to send the data back in to first then for that you can use BroadCastReceiver.

In Second Activity -

Intent intent = new Intent("data");
intent.putExtra("some_data", true);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

In First Activity-

private BroadcastReceiver tempReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // do some action
    }
};

Register the receiver in onCreate()-

 LocalBroadcastManager.getInstance(this).registerReceiver(tempReceiver,new IntentFilter("data"));

Unregister it in onDestroy()

How to use a parameter in ExecStart command line?

Although systemd indeed does not provide way to pass command-line arguments for unit files, there are possibilities to write instances: http://0pointer.de/blog/projects/instances.html

For example: /lib/systemd/system/[email protected] looks something like this:

[Unit]
Description=Serial Getty on %I
BindTo=dev-%i.device
After=dev-%i.device systemd-user-sessions.service

[Service]
ExecStart=-/sbin/agetty -s %I 115200,38400,9600
Restart=always
RestartSec=0

So, you may start it like:

$ systemctl start [email protected]
$ systemctl start [email protected]

For systemd it will different instances:

$ systemctl status [email protected]
[email protected] - Getty on ttyUSB0
      Loaded: loaded (/lib/systemd/system/[email protected]; static)
      Active: active (running) since Mon, 26 Sep 2011 04:20:44 +0200; 2s ago
    Main PID: 5443 (agetty)
      CGroup: name=systemd:/system/[email protected]/ttyUSB0
          + 5443 /sbin/agetty -s ttyUSB0 115200,38400,9600

It also mean great possibility enable and disable it separately.

Off course it lack much power of command line parsing, but in common way it is used as some sort of config files selection. For example you may look at Fedora [email protected]: http://pkgs.fedoraproject.org/cgit/openvpn.git/tree/[email protected]

How to call one shell script from another shell script?

Depends on. Briefly... If you want load variables on current console and execute you may use source myshellfile.sh on your code. Example:

!#/bin/bash
set -x
echo "This is an example of run another INTO this session."
source my_lib_of_variables_and_functions.sh
echo "The function internal_function() is defined into my lib."
returned_value=internal_function()
echo $this_is_an_internal_variable

set +x

If you just want to execute a file and the only thing intersting for you is the result, you can do:

!#/bin/bash
set -x
./executing_only.sh
sh i_can_execute_this_way_too.sh
bash or_this_way.sh
set +x

I hope helps you. Thanks.

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

import os
os.environ["PATH"] += os.pathsep + "/Macintosh HD?/anaconda3?/lib?/?python3.7?/site-packages?/sphinx?/templates?/graphviz"

This solved the PATH issue on MAC for me!

Any way of using frames in HTML5?

You'll have to resort to XHTML or HTML 4.01 for this. Although iframe is still there in HTML5, its use is not recommended for embedding content meant for the user.

And be sure to tell your teacher that frames haven't been state-of-the-art since the late nineties. They have no place in any kind of education at all, except possibly for historical reasons.

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

Change your model file name, start with upper case letter like this: Logon_model.php

This happens when we migrate our project from windows server to LINUX server because linux is case sensitive while windows is not.

So, on windows even if don't write file name with upper case then also it will work fine but not on linux.

"Cannot update paths and switch to branch at the same time"

If you got white space in your branch then you will get this error.

Grep for beginning and end of line?

It looks like you were on the right track... The ^ character matches beginning-of-line, and $ matches end-of-line. Jonathan's pattern will work for you... just wanted to give you the explanation behind it

Reading a huge .csv file

Although Martijin's answer is prob best. Here is a more intuitive way to process large csv files for beginners. This allows you to process groups of rows, or chunks, at a time.

import pandas as pd
chunksize = 10 ** 8
for chunk in pd.read_csv(filename, chunksize=chunksize):
    process(chunk)

JavaScript ternary operator example with functions

I know question is already answered.

But let me add one point here. This is not only case of true or false. See below:

var val="Do";

Var c= (val == "Do" || val == "Done")
          ? 7
          : 0

Here if val is Do or Done then c will be 7 else it will be zero. In this case c will be 7.

This is actually another perspective of this operator.

compareTo with primitives -> Integer / int

For performance, it usually best to make the code as simple and clear as possible and this will often perform well (as the JIT will optimise this code best). In your case, the simplest examples are also likely to be the fastest.


I would do either

int cmp = a > b ? +1 : a < b ? -1 : 0;

or a longer version

int cmp;
if (a > b)
   cmp = +1;
else if (a < b)
   cmp = -1;
else
   cmp = 0;

or

int cmp = Integer.compare(a, b); // in Java 7
int cmp = Double.compare(a, b); // before Java 7

It's best not to create an object if you don't need to.

Performance wise, the first is best.

If you know for sure that you won't get an overflow you can use

int cmp = a - b; // if you know there wont be an overflow.

you won't get faster than this.

Get href attribute on jQuery

Use $(this) for get the desire element.

function openAll()
{
     $("tr.b_row").each(function(){
        var a_href = $(this).find('.cpt h2 a').attr('href');
        alert ("Href is: "+a_href);
     });
}

What is the size of an enum in C?

While the previous answers are correct, some compilers have options to break the standard and use the smallest type that will contain all values.

Example with GCC (documentation in the GCC Manual):

enum ord {
    FIRST = 1,
    SECOND,
    THIRD
} __attribute__ ((__packed__));
STATIC_ASSERT( sizeof(enum ord) == 1 )

How to sort Map values by key in Java?

Assuming TreeMap is not good for you (and assuming you can't use generics):

List sortedKeys=new ArrayList(yourMap.keySet());
Collections.sort(sortedKeys);
// Do what you need with sortedKeys.

Convert HH:MM:SS string to seconds only in javascript

This is the most clear, easy to understand solution:

_x000D_
_x000D_
function convertDurationtoSeconds(duration){
    const [hours, minutes, seconds] = duration.split(':');
    return Number(hours) * 60 * 60 + Number(minutes) * 60 + Number(seconds);
};

const input = '01:30:45';
const output = convertDurationtoSeconds(input);
console.log(`${input} is ${output} in seconds`);
_x000D_
_x000D_
_x000D_

how to make a specific text on TextView BOLD

In case you want to use the string from XML, you can do something like this:

strings.xml (the "CDATA" part is important, otherwise it won't work)

<string name="test">
     <![CDATA[
 <b>bold!</b> normal
    ]]>
</string>

layout file

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_gravity="center" />

</FrameLayout>

code

textView.text = HtmlCompat.fromHtml(getString(R.string.test), HtmlCompat.FROM_HTML_MODE_LEGACY)

Get webpage contents with Python?

If you ask me. try this one

import urllib2
resp = urllib2.urlopen('http://hiscore.runescape.com/index_lite.ws?player=zezima')

and read the normal way ie

page = resp.read()

Good luck though

Can I assume (bool)true == (int)1 for any C++ compiler?

Yes. The casts are redundant. In your expression:

true == 1

Integral promotion applies and the bool value will be promoted to an int and this promotion must yield 1.

Reference: 4.7 [conv.integral] / 4: If the source type is bool... true is converted to one.

How do I prompt for Yes/No/Cancel input in a Linux shell script?

I suggest you use dialog...

Linux Apprentice: Improve Bash Shell Scripts Using Dialog

The dialog command enables the use of window boxes in shell scripts to make their use more interactive.

it's simple and easy to use, there's also a gnome version called gdialog that takes the exact same parameters, but shows it GUI style on X.

Initializing entire 2D array with one value

Use vector array instead:

vector<vector<int>> array(ROW, vector<int>(COLUMN, 1));

How to permanently set $PATH on Linux/Unix?

You can also set permanently, editing one of these files:

/etc/profile (for all users)

~/.bash_profile (for current user)

~/.bash_login (for current user)

~/.profile (for current user)

You can also use /etc/environment to set a permanent PATH environment variable, but it does not support variable expansion.

Extracted from: http://www.sysadmit.com/2016/06/linux-anadir-ruta-al-path.html

creating a random number using MYSQL

As RAND produces a number 0 <= v < 1.0 (see documentation) you need to use ROUND to ensure that you can get the upper bound (500 in this case) and the lower bound (100 in this case)

So to produce the range you need:

SELECT name, address, ROUND(100.0 + 400.0 * RAND()) AS random_number
FROM users

jQuery Ajax calls and the Html.AntiForgeryToken()

You can do this also:

$("a.markAsDone").click(function (event) {
    event.preventDefault();

    $.ajax({
        type: "post",
        dataType: "html",
        url: $(this).attr("rel"),
        data: $('<form>@Html.AntiForgeryToken()</form>').serialize(),
        success: function (response) {
        // ....
        }
    });
});

This is using Razor, but if you're using WebForms syntax you can just as well use <%= %> tags

Vba macro to copy row from table if value in table meets condition

Try it like this:

Sub testIt()
Dim r As Long, endRow as Long, pasteRowIndex As Long

endRow = 10 ' of course it's best to retrieve the last used row number via a function
pasteRowIndex = 1

For r = 1 To endRow 'Loop through sheet1 and search for your criteria

    If Cells(r, Columns("B").Column).Value = "YourCriteria" Then 'Found

            'Copy the current row
            Rows(r).Select 
            Selection.Copy

            'Switch to the sheet where you want to paste it & paste
            Sheets("Sheet2").Select
            Rows(pasteRowIndex).Select
            ActiveSheet.Paste

            'Next time you find a match, it will be pasted in a new row
            pasteRowIndex = pasteRowIndex + 1


           'Switch back to your table & continue to search for your criteria
            Sheets("Sheet1").Select  
    End If
Next r
End Sub

In Bash, how can I check if a string begins with some value?

Since # has a meaning in Bash, I got to the following solution.

In addition I like better to pack strings with "" to overcome spaces, etc.

A="#sdfs"
if [[ "$A" == "#"* ]];then
    echo "Skip comment line"
fi

Use of "global" keyword in Python

The keyword global is only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution.

def bob():
    me = "locally defined"    # Defined only in local context
    print(me)

bob()
print(me)     # Asking for a global variable

The above will give you:

locally defined
Traceback (most recent call last):
  File "file.py", line 9, in <module>
    print(me)
NameError: name 'me' is not defined

While if you use the global statement, the variable will become available "outside" the scope of the function, effectively becoming a global variable.

def bob():
    global me
    me = "locally defined"   # Defined locally but declared as global
    print(me)

bob()
print(me)     # Asking for a global variable

So the above code will give you:

locally defined
locally defined

In addition, due to the nature of python, you could also use global to declare functions, classes or other objects in a local context. Although I would advise against it since it causes nightmares if something goes wrong or needs debugging.

how to modify an existing check constraint?

No. If such a feature existed it would be listed in this syntax illustration. (Although it's possible there is an undocumented SQL feature, or maybe there is some package that I'm not aware of.)

Using Javascript in CSS

IE supports CSS expressions:

width:expression(document.body.clientWidth > 955 ? "955px": "100%" );

but they are not standard and are not portable across browsers. Avoid them if possible. They are deprecated since IE8.

Unprotect workbook without password

No longer works for spreadsheets Protected with Excel 2013 or later -- they improved the pw hash. So now need to unzip .xlsx and hack the internals.

When to use React "componentDidUpdate" method?

componentDidUpdate(prevProps){ 

    if (this.state.authToken==null&&prevProps.authToken==null) {
      AccountKit.getCurrentAccessToken()
      .then(token => {
        if (token) {
          AccountKit.getCurrentAccount().then(account => {
            this.setState({
              authToken: token,
              loggedAccount: account
            });
          });
        } else {
          console.log("No user account logged");
        }
      })
      .catch(e => console.log("Failed to get current access token", e));

    }
}

Sass Variable in CSS calc() function

Here is a really simple solution using SASS/SCSS and a math formula style:

/* frame circle */
.container {
    position: relative;
    border-radius: 50%;
    background-color: white;
    overflow: hidden;
    width: 400px;
    height: 400px; }

/* circle sectors */
.menu-frame-sector {
    position: absolute;
    width: 50%;
    height: 50%;
    z-index: 10000;
    transform-origin: 100% 100%;
  }

$sector_count: 8;
$sector_width: 360deg / $sector_count;

.sec0 {
    transform: rotate(0 * $sector_width) skew($sector_width);
    background-color: red; }
.sec1 {
    transform: rotate(1 * $sector_width) skew($sector_width);
    background-color: blue; }
.sec2 {
    transform: rotate(2 * $sector_width) skew($sector_width);
    background-color: red; }
.sec3 {
    transform: rotate(3 * $sector_width) skew($sector_width);
    background-color: blue; }
.sec4 {
    transform: rotate(4 * $sector_width) skew($sector_width);
    background-color: red; }
.sec5 {
    transform: rotate(5 * $sector_width) skew($sector_width);
    background-color: blue; }
.sec6 {
    transform: rotate(6 * $sector_width) skew($sector_width);
    background-color: red; }
.sec7 {
    transform: rotate(7 * $sector_width) skew($sector_width);
    background-color: blue; }

To conclude, I strongly suggest you to understand transform-origin, rotate() and skew():

https://tympanus.net/codrops/2013/08/09/building-a-circular-navigation-with-css-transforms/

Put a Delay in Javascript

I just had an issue where I needed to solve this properly.

Via Ajax, a script gets X (0-10) messages. What I wanted to do: Add one message to the DOM every 10 Seconds.

the code I ended up with:

$.each(messages, function(idx, el){
  window.setTimeout(function(){
    doSomething(el);
  },Math.floor(idx+1)*10000);
});

Basically, think of the timeouts as a "timeline" of your script.

This is what we WANT to code:

DoSomething();
WaitAndDoNothing(5000);
DoSomethingOther();
WaitAndDoNothing(5000);
DoEvenMore();

This is HOW WE NEED TO TELL IT TO THE JAVASCRIPT:

At Runtime 0    : DoSomething();
At Runtime 5000 : DoSomethingOther();
At Runtime 10000: DoEvenMore();

Hope this helps.

How to set Status Bar Style in Swift 3

Swift 4.0 Please use this code in "didFinishLaunchingWithOptions launchOptions:" Appdelegate class

UIApplication.shared.statusBarStyle = .lightContent
let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
if statusBar.responds(to: #selector(setter: UIView.backgroundColor)){
  statusBar.backgroundColor = UIColor.black
}

Calling Non-Static Method In Static Method In Java

The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.

Why is enum class preferred over plain enum?

It's worth noting, on top of these other answers, that C++20 solves one of the problems that enum class has: verbosity. Imagining a hypothetical enum class, Color.

void foo(Color c)
  switch (c) {
    case Color::Red: ...;
    case Color::Green: ...;
    case Color::Blue: ...;
    // etc
  }
}

This is verbose compared to the plain enum variation, where the names are in the global scope and therefore don't need to be prefixed with Color::.

However, in C++20 we can use using enum to introduce all of the names in an enum to the current scope, solving the problem.

void foo(Color c)
  using enum Color;
  switch (c) {
    case Red: ...;
    case Green: ...;
    case Blue: ...;
    // etc
  }
}

So now, there is no reason not to use enum class.

Return multiple values from a function in swift

Return a tuple:

func getTime() -> (Int, Int, Int) {
    ...
    return ( hour, minute, second)
}

Then it's invoked as:

let (hour, minute, second) = getTime()

or:

let time = getTime()
println("hour: \(time.0)")

How to use Elasticsearch with MongoDB?

Here how to do this on mongodb 3.0. I used this nice blog

  1. Install mongodb.
  2. Create data directories:
$ mkdir RANDOM_PATH/node1
$ mkdir RANDOM_PATH/node2> 
$ mkdir RANDOM_PATH/node3
  1. Start Mongod instances
$ mongod --replSet test --port 27021 --dbpath node1
$ mongod --replSet test --port 27022 --dbpath node2
$ mongod --replSet test --port 27023 --dbpath node3
  1. Configure the Replica Set:
$ mongo
config = {_id: 'test', members: [ {_id: 0, host: 'localhost:27021'}, {_id: 1, host: 'localhost:27022'}]};    
rs.initiate(config);
  1. Installing Elasticsearch:
a. Download and unzip the [latest Elasticsearch][2] distribution

b. Run bin/elasticsearch to start the es server.

c. Run curl -XGET http://localhost:9200/ to confirm it is working.
  1. Installing and configuring the MongoDB River:

$ bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb

$ bin/plugin --install elasticsearch/elasticsearch-mapper-attachments

  1. Create the “River” and the Index:

curl -XPUT 'http://localhost:8080/_river/mongodb/_meta' -d '{ "type": "mongodb", "mongodb": { "db": "mydb", "collection": "foo" }, "index": { "name": "name", "type": "random" } }'

  1. Test on browser:

    http://localhost:9200/_search?q=home

CentOS: Enabling GD Support in PHP Installation

With CentOS 6.5+ and PHP 5.5:

yum install php55u-gd
service httpd restart

If you get an error like: cannot map zero-fill pages: Cannot allocate memory in Unknown on line 0, it could be because you don't have a swap file. I suggest you take a look at the tutorial mentioned in this answer: https://stackoverflow.com/a/20275282/828366

Tutorial: https://www.digitalocean.com/community/articles/how-to-add-swap-on-centos-6

Can I convert long to int?

A possible way is to use the modulo operator to only let the values stay in the int32 range, and then cast it to int.

var intValue= (int)(longValue % Int32.MaxValue);

How to mute an html5 video player using jQuery

$("video").prop('muted', true); //mute

AND

$("video").prop('muted', false); //unmute

See all events here

(side note: use attr if in jQuery < 1.6)

Android Text over image

You could possibly

  • make a new class inherited from the Class ImageView and
  • override the Method onDraw. Call super.onDraw() in that method first and
  • then draw some Text you want to display.

if you do it that way, you can use this as a single Layout Component which makes it easier to layout together with other components.

Apply style to only first level of td tags

I guess you could try

table tr td { color: red; }
table tr td table tr td { color: black; }

Or

body table tr td { color: red; }

where 'body' is a selector for your table's parent

But classes are most likely the right way to go here.

Why use @PostConstruct?

The main problem is that:

in a constructor, the injection of the dependencies has not yet occurred*

*obviously excluding Constructor Injection


Real-world example:

public class Foo {

    @Inject
    Logger LOG;

    @PostConstruct
    public void fooInit(){
        LOG.info("This will be printed; LOG has already been injected");
    }

    public Foo() {
        LOG.info("This will NOT be printed, LOG is still null");
        // NullPointerException will be thrown here
    }
}

IMPORTANT: @PostConstruct and @PreDestroy have been completely removed in Java 11.

To keep using them, you'll need to add the javax.annotation-api JAR to your dependencies.

Maven

<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</dependency>

Gradle

// https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api
compile group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2'

specifying goal in pom.xml

The error message which you specified is nothing but you are not specifying goal for maven build.

you can specify any goal in your run configuration for maven build like clear, compile, install, package.

please following below step to resolve it.

  1. right click on your project.
  2. click 'Run as' and select 'Maven Build'
  3. edit Configuration window will open. write any goal but your problem specific write 'package' in Goal text box.
  4. click on 'Run'

How to open Console window in Eclipse?

The only reliable way to open it is Window -> Show View -> Other -> Search "console". There was a handful suggestions in this post and none of them works! Apparently Eclipse likes to change their logic every other second.

Also, resetting the view is the most horrible suggestion, because that way you will lose everything you have ever done to change the layout, so it will probably not work for the most of the readers.

Append a dictionary to a dictionary

Assuming that you do not want to change orig, you can either do a copy and update like the other answers, or you can create a new dictionary in one step by passing all items from both dictionaries into the dict constructor:

from itertools import chain
dest = dict(chain(orig.items(), extra.items()))

Or without itertools:

dest = dict(list(orig.items()) + list(extra.items()))

Note that you only need to pass the result of items() into list() on Python 3, on 2.x dict.items() already returns a list so you can just do dict(orig.items() + extra.items()).

As a more general use case, say you have a larger list of dicts that you want to combine into a single dict, you could do something like this:

from itertools import chain
dest = dict(chain.from_iterable(map(dict.items, list_of_dicts)))

Error in spring application context schema

Sometimes the spring config xml file works not well on next eclipse open up.

It shows error in the xml file caused by schema definition, no matter reopen eclipse or clean up project are both not working.

But try this!

Right click on the spring config xml file, and select validate.

After a while, the error disappears and eclipse tells you there is no error on this file.

What a joke...

Disable button in jQuery

For Jquery UI buttons this works :

$("#buttonId").button( "option", "disabled", true | false );

Set a button background image iPhone programmatically

Swift

Set the button image like this:

let myImage = UIImage(named: "myImageName")
myButton.setImage(myImage , forState: UIControlState.Normal)

where myImageName is the name of your image in your asset catalog.

In CSS how do you change font size of h1 and h2

 h1 { font-size: 150%; }
 h2 { font-size: 120%; }

Tune as needed.

How to resolve Nodejs: Error: ENOENT: no such file or directory

I solved this error by simply creating a blank file at that location for which I got the error. If you are getting the error for a directory, You can try by creating empty directory also. All the best.

Get individual query parameters from Uri

For isolated projects, where dependencies must be kept to a minimum, I found myself using this implementation:

var arguments = uri.Query
  .Substring(1) // Remove '?'
  .Split('&')
  .Select(q => q.Split('='))
  .ToDictionary(q => q.FirstOrDefault(), q => q.Skip(1).FirstOrDefault());

Do note, however, that I do not handle encoded strings of any kind, as I was using this in a controlled setting, where encoding issues would be a coding error on the server side that should be fixed.

Listening for variable changes in JavaScript

Utils = {
    eventRegister_globalVariable : function(variableName,handlers){
        eventRegister_JsonVariable(this,variableName,handlers);
    },
    eventRegister_jsonVariable : function(jsonObj,variableName,handlers){
        if(jsonObj.eventRegisteredVariable === undefined) {
            jsonObj.eventRegisteredVariable={};//this Object is used for trigger event in javascript variable value changes ku
        }
        Object.defineProperty(jsonObj, variableName , {
                    get: function() { 
                        return jsonObj.eventRegisteredVariable[variableName] },
                    set: function(value) {
                        jsonObj.eventRegisteredVariable[variableName] = value; handlers(jsonObj.eventRegisteredVariable[variableName]);}
                    });
            }

The first day of the current month in php using date_modify as DateTime object

Currently I'm using this solution:

$firstDay = new \DateTime('first day of this month');
$lastDay = new \DateTime('last day of this month');

The only issue I came upon is that strange time is being set. I needed correct range for our search interface and I ended up with this:

$firstDay = new \DateTime('first day of this month 00:00:00');
$lastDay = new \DateTime('first day of next month 00:00:00');

Compile to stand alone exe for C# app in Visual Studio 2010

Press the start button in visual studio. Then go to the location where your solution is stored and open the folder of your main project then the bin folder. If your application was running in debug mode then go to the debug folder. If running in release mode then go to the release folder. You should find your exe there.

Name attribute in @Entity and @Table

@Entity(name = "someThing") => this name will be used to name the Entity
@Table(name = "someThing")  => this name will be used to name a table in DB

So, in the first case your table and entity will have the same name, that will allow you to access your table with the same name as the entity while writing HQL or JPQL.

And in second case while writing queries you have to use the name given in @Entity and the name given in @Table will be used to name the table in the DB.

So in HQL your someThing will refer to otherThing in the DB.

Representing null in JSON

There is only one way to represent null; that is with null.

console.log(null === null);   // true
console.log(null === true);   // false
console.log(null === false);  // false
console.log(null === 'null'); // false
console.log(null === "null"); // false
console.log(null === "");     // false
console.log(null === []);     // false
console.log(null === 0);      // false

That is to say; if any of the clients that consume your JSON representation use the === operator; it could be a problem for them.

no value

If you want to convey that you have an object whose attribute myCount has no value:

{ "myCount": null }

no attribute / missing attribute

What if you to convey that you have an object with no attributes:

{}

Client code will try to access myCount and get undefined; it's not there.

empty collection

What if you to convey that you have an object with an attribute myCount that is an empty list:

{ "myCount": [] }

How to serialize Object to JSON?

You make the http request

HttpResponse response = httpclient.execute(httpget);           
HttpEntity entity = response.getEntity();

inputStream = entity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

You read the Buffer

String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
Log.d("Result", sb.toString());
result = sb.toString();

Create a JSONObject and pass the result string to the constructor:

JSONObject json = new JSONObject(result);

Parse the json results to your desired variables:

String usuario= json.getString("usuario");
int idperon = json.getInt("idperson");
String nombre = json.getString("nombre");

Do not forget to import:

import org.json.JSONObject;

Creating a JSON dynamically with each input value using jquery

same from above example - if you are just looking for json (not an array of object) just use

function getJsonDetails() {
      item = {}
      item ["token1"] = token1val;
      item ["token2"] = token1val;
      return item;
}
console.log(JSON.stringify(getJsonDetails()))

this output ll print as (a valid json)

{ 
   "token1":"samplevalue1",
   "token2":"samplevalue2"
}

Change mysql user password using command line

Before MySQL 5.7.6 this works from the command line:

mysql -e "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('$w0rdf1sh');"

I don't have a mysql install to test on but I think in your case it would be

mysql -e "UPDATE mysql.user SET Password=PASSWORD('$w0rdf1sh') WHERE User='tate256';"

Declare global variables in Visual Studio 2010 and VB.NET

A global variable could be accessible in all your forms in your project if you use the keyword public shared if it is in a class. It will also work if you use the keyword "public" if it is under a Module, but it is not the best practice for many reasons.

(... Yes, I somewhat repeating what "Cody Gray" and "RBarryYoung" said.)

One of the problems is when you have two threads that call the same global variable at the same time. You will have some surprises. You might have unexpected reactions if you don't know their limitations. Take a look at the post Global Variables in Visual Basic .NET and download the sample project!

Moving from position A to position B slowly with animation

You can animate it after the fadeIn completes using the callback as shown below:

$("#Friends").fadeIn('slow',function(){
  $(this).animate({'top': '-=30px'},'slow');
});

Bootstrap 3 - jumbotron background image effect

After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!

Regex pattern for checking if a string starts with a certain substring?

You could use:

^(mailto|ftp|joe)

But to be honest, StartsWith is perfectly fine to here. You could rewrite it as follows:

string[] prefixes = { "http", "mailto", "joe" };
string s = "joe:bloggs";
bool result = prefixes.Any(prefix => s.StartsWith(prefix));

You could also look at the System.Uri class if you are parsing URIs.

How to use "svn export" command to get a single file from the repository?

Guessing from your directory name, you are trying to access the repository on the local filesystem. You still need to use URL syntax to access it:

svn export file:///e:/repositories/process/test.txt c:\test.txt

Get parent of current directory from Python script

import os
import sys
from os.path import dirname, abspath

d = dirname(dirname(abspath(__file__)))
print(d)
path1 = os.path.dirname(os.path.realpath(sys.argv[0]))
print(path1)
path = os.path.split(os.path.realpath(__file__))[0]
print(path)

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

Many modern browsers now support ES6 modules. As long as you import your scripts (including the entrypoint to your application) using <script type="module" src="..."> it will work.

Take a look at caniuse.com for more details: https://caniuse.com/#feat=es6-module

Better way to sort array in descending order

You may specify a comparer(IComparer implementation) as a parameter in Array.Sort, the order of sorting actually depends on comparer. The default comparer is used in ascending sorting

Removing duplicate characters from a string

from collections import OrderedDict
def remove_duplicates(value):
        m=list(OrderedDict.fromkeys(value))
        s=''
        for i in m:
            s+=i
        return s
print(remove_duplicates("11223445566666ababzzz@@@123#*#*"))

How to know a Pod's own IP address from inside a container in the Pod?

kubectl get pods -o wide

Give you a list of pods with name, status, ip, node...

C# Threading - How to start and stop a thread

Use a static AutoResetEvent in your spawned threads to call back to the main thread using the Set() method. This guy has a fairly good demo in SO on how to use it.

AutoResetEvent clarification

Running CMake on Windows

The default generator for Windows seems to be set to NMAKE. Try to use:

cmake -G "MinGW Makefiles"

Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.

Python 3.6 install win32api?

Information provided by @Gord

As of September 2019 pywin32 is now available from PyPI and installs the latest version (currently version 224). This is done via the pip command

pip install pywin32

If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx is the version you require, e.g. 224

pip install pywin32==xxx

This differs to the pip command below as that one uses pypiwin32 which currently installs an older (namely 223)

Browsing the docs I see no reason for these commands to work for all python3.x versions, I am unsure on python2.7 and below so you would have to try them and if they do not work then the solutions below will work.


Probably now undesirable solutions but certainly still valid as of September 2019

There is no version of specific version ofwin32api. You have to get the pywin32module which currently cannot be installed via pip. It is only available from this link at the moment.

https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/

The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python version :)


EDIT

Since I posted my answer there are other alternatives to downloading the win32api module.

It is now available to download through pip using this command;

pip install pypiwin32

Also it can be installed from this GitHub repository as provided in comments by @Heath

Spring Security redirect to previous page after successful login

I've custom OAuth2 authorization and request.getHeader("Referer") is not available at poit of decision. But security request already saved in ExceptionTranslationFilter.sendStartAuthentication:

protected void sendStartAuthentication(HttpServletRequest request,...
    ...
    requestCache.saveRequest(request, response);

So, all what we need is share requestCache as Spring bean:

@Bean
public RequestCache requestCache() {
   return new HttpSessionRequestCache();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
   http.authorizeRequests()
   ... 
   .requestCache().requestCache(requestCache()).and()
   ...
}     

and use it wheen authorization is finished:

@Autowired
private RequestCache requestCache;

public void authenticate(HttpServletRequest req, HttpServletResponse resp){
    ....
    SavedRequest savedRequest = requestCache.getRequest(req, resp);
    resp.sendRedirect(savedRequest != null && "GET".equals(savedRequest.getMethod()) ?  
    savedRequest.getRedirectUrl() : "defaultURL");
}