Programs & Examples On #Set based

How can I simulate an array variable in MySQL?

Dont know about the arrays, but there is a way to store comma-separated lists in normal VARCHAR column.

And when you need to find something in that list you can use the FIND_IN_SET() function.

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

You can motivate the solution by thinking about it in terms of symmetries (groups, in math language). No matter the order of the set of numbers, the answer should be the same. If you're going to use k functions to help determine the missing elements, you should be thinking about what functions have that property: symmetric. The function s_1(x) = x_1 + x_2 + ... + x_n is an example of a symmetric function, but there are others of higher degree. In particular, consider the elementary symmetric functions. The elementary symmetric function of degree 2 is s_2(x) = x_1 x_2 + x_1 x_3 + ... + x_1 x_n + x_2 x_3 + ... + x_(n-1) x_n, the sum of all products of two elements. Similarly for the elementary symmetric functions of degree 3 and higher. They are obviously symmetric. Furthermore, it turns out they are the building blocks for all symmetric functions.

You can build the elementary symmetric functions as you go by noting that s_2(x,x_(n+1)) = s_2(x) + s_1(x)(x_(n+1)). Further thought should convince you that s_3(x,x_(n+1)) = s_3(x) + s_2(x)(x_(n+1)) and so on, so they can be computed in one pass.

How do we tell which items were missing from the array? Think about the polynomial (z-x_1)(z-x_2)...(z-x_n). It evaluates to 0 if you put in any of the numbers x_i. Expanding the polynomial, you get z^n-s_1(x)z^(n-1)+ ... + (-1)^n s_n. The elementary symmetric functions appear here too, which is really no surprise, since the polynomial should stay the same if we apply any permutation to the roots.

So we can build the polynomial and try to factor it to figure out which numbers are not in the set, as others have mentioned.

Finally, if we are concerned about overflowing memory with large numbers (the nth symmetric polynomial will be of the order 100!), we can do these calculations mod p where p is a prime bigger than 100. In that case we evaluate the polynomial mod p and find that it again evaluates to 0 when the input is a number in the set, and it evaluates to a non-zero value when the input is a number not in the set. However, as others have pointed out, to get the values out of the polynomial in time that depends on k, not N, we have to factor the polynomial mod p.

How to get xdebug var_dump to show full object/array

I know this is a super old post, but I figured this may still be helpful.

If you're comfortable with reading json format you could replace your var_dump with:

return json_encode($myvar);

I've been using this to help troubleshoot a service I've been building that has some deeply nested arrays. This will return every level of your array without truncating anything or requiring you to change your php.ini file.

Also, because the json_encoded data is a string it means you can write it to the error log easily

error_log(json_encode($myvar));

It probably isn't the best choice for every situation, but it's a choice!

javascript scroll event for iPhone/iPad?

For iOS you need to use the touchmove event as well as the scroll event like this:

document.addEventListener("touchmove", ScrollStart, false);
document.addEventListener("scroll", Scroll, false);

function ScrollStart() {
    //start of scroll event for iOS
}

function Scroll() {
    //end of scroll event for iOS
    //and
    //start/end of scroll event for other browsers
}

How to add leading zeros for for-loop in shell?

Use printf command to have 0 padding:

printf "%02d\n" $num

Your for loop will be like this:

for (( num=1; num<=5; num++ )); do printf "%02d\n" $num; done
01
02
03
04
05

Memory errors and list limits?

First off, see How Big can a Python Array Get? and Numpy, problem with long arrays

Second, the only real limit comes from the amount of memory you have and how your system stores memory references. There is no per-list limit, so Python will go until it runs out of memory. Two possibilities:

  1. If you are running on an older OS or one that forces processes to use a limited amount of memory, you may need to increase the amount of memory the Python process has access to.
  2. Break the list apart using chunking. For example, do the first 1000 elements of the list, pickle and save them to disk, and then do the next 1000. To work with them, unpickle one chunk at a time so that you don't run out of memory. This is essentially the same technique that databases use to work with more data than will fit in RAM.

Bootstrap: align input with button

Just the heads up, there seems to be special CSS class for this called form-horizontal

input-append has another side effect, that it drops font-size to zero

How can I retrieve Id of inserted entity using Entity framework?

You can get ID only after saving, instead you can create a new Guid and assign before saving.

How to remove the default arrow icon from a dropdown list (select element)?

Try this it works for me,

_x000D_
_x000D_
<style>_x000D_
    select{_x000D_
        border: 0 !important;  /*Removes border*/_x000D_
        -webkit-appearance: none;_x000D_
        -moz-appearance: none;_x000D_
        appearance: none;_x000D_
        text-overflow:'';_x000D_
        text-indent: 0.01px; /* Removes default arrow from firefox*/_x000D_
        text-overflow: "";  /*Removes default arrow from firefox*/_x000D_
    }_x000D_
    select::-ms-expand {_x000D_
        display: none;_x000D_
    }_x000D_
    .select-wrapper_x000D_
    {_x000D_
        padding-left:0px;_x000D_
        overflow:hidden;_x000D_
    }_x000D_
</style>_x000D_
    _x000D_
<div class="select-wrapper">_x000D_
     <select> ... </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can not hide but using overflow hidden you can actually make it disappear.

How to count objects in PowerShell?

As short as @jumbo's answer is :-) you can do it even more tersely. This just returns the Count property of the array returned by the antecedent sub-expression:

@(Get-Alias).Count

A couple points to note:

  1. You can put an arbitrarily complex expression in place of Get-Alias, for example:

    @(Get-Process | ? { $_.ProcessName -eq "svchost" }).Count
    
  2. The initial at-sign (@) is necessary for a robust solution. As long as the answer is two or greater you will get an equivalent answer with or without the @, but when the answer is zero or one you will get no output unless you have the @ sign! (It forces the Count property to exist by forcing the output to be an array.)

2012.01.30 Update

The above is true for PowerShell V2. One of the new features of PowerShell V3 is that you do have a Count property even for singletons, so the at-sign becomes unimportant for this scenario.

How to determine if .NET Core is installed

It's possible that .NET Core is installed but not added to the PATH variable for your operating system or user profile. Running the dotnet commands may not work. As an alternative, you can check that the .NET Core install folders exist.

It's installed to a standard folder if you didn't change it during the instillation

  • dotnet executable C:\program files\dotnet\dotnet.exe

  • .NET SDK C:\program files\dotnet\sdk\{version}\

  • .NET Runtime C:\program files\dotnet\shared\{runtime-type}\{version}\

For more details check How to check that .NET Core is already installed page at .NET documentation

How do I create an .exe for a Java program?

Launch4j perhaps? Can't say I've used it myself, but it sounds like what you're after.

How to call servlet through a JSP page

there isn't method to call Servlet. You should make mapping in web.xml and then trigger this mapping.

Example: web.xml:

  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>test.HelloServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>

This mapping means that every call to http://yoursite/yourwebapp/hello trigger this servlet For example this jsp:

<jsp:forward page="/hello"/> 

How to call same method for a list of objects?

Taking @Ants Aasmas answer one step further, you can create a wrapper that takes any method call and forwards it to all elements of a given list:

class AllOf:
    def __init__(self, elements):
        self.elements = elements
    def __getattr__(self, attr):
        def on_all(*args, **kwargs):
            for obj in self.elements:
                getattr(obj, attr)(*args, **kwargs)
        return on_all

That class can then be used like this:

class Foo:
    def __init__(self, val="quux!"):
        self.val = val
    def foo(self):
        print "foo: " + self.val

a = [ Foo("foo"), Foo("bar"), Foo()]
AllOf(a).foo()

Which produces the following output:

foo: foo
foo: bar
foo: quux!

With some work and ingenuity it could probably be enhanced to handle attributes as well (returning a list of attribute values).

In Angular, how to pass JSON object/array into directive?

If you want to follow all the "best practices," there's a few things I'd recommend, some of which are touched on in other answers and comments to this question.


First, while it doesn't have too much of an affect on the specific question you asked, you did mention efficiency, and the best way to handle shared data in your application is to factor it out into a service.

I would personally recommend embracing AngularJS's promise system, which will make your asynchronous services more composable compared to raw callbacks. Luckily, Angular's $http service already uses them under the hood. Here's a service that will return a promise that resolves to the data from the JSON file; calling the service more than once will not cause a second HTTP request.

app.factory('locations', function($http) {
  var promise = null;

  return function() {
    if (promise) {
      // If we've already asked for this data once,
      // return the promise that already exists.
      return promise;
    } else {
      promise = $http.get('locations/locations.json');
      return promise;
    }
  };
});

As far as getting the data into your directive, it's important to remember that directives are designed to abstract generic DOM manipulation; you should not inject them with application-specific services. In this case, it would be tempting to simply inject the locations service into the directive, but this couples the directive to that service.

A brief aside on code modularity: a directive’s functions should almost never be responsible for getting or formatting their own data. There’s nothing to stop you from using the $http service from within a directive, but this is almost always the wrong thing to do. Writing a controller to use $http is the right way to do it. A directive already touches a DOM element, which is a very complex object and is difficult to stub out for testing. Adding network I/O to the mix makes your code that much more difficult to understand and that much more difficult to test. In addition, network I/O locks in the way that your directive will get its data – maybe in some other place you’ll want to have this directive receive data from a socket or take in preloaded data. Your directive should either take data in as an attribute through scope.$eval and/or have a controller to handle acquiring and storing the data.

- The 80/20 Guide to Writing AngularJS Directives

In this specific case, you should place the appropriate data on your controller's scope and share it with the directive via an attribute.

app.controller('SomeController', function($scope, locations) {
  locations().success(function(data) {
    $scope.locations = data;
  });
});
<ul class="list">
   <li ng-repeat="location in locations">
      <a href="#">{{location.id}}. {{location.name}}</a>
   </li>
</ul>
<map locations='locations'></map>
app.directive('map', function() {
  return {
    restrict: 'E',
    replace: true,
    template: '<div></div>',
    scope: {
      // creates a scope variable in your directive
      // called `locations` bound to whatever was passed
      // in via the `locations` attribute in the DOM
      locations: '=locations'
    },
    link: function(scope, element, attrs) {
      scope.$watch('locations', function(locations) {
        angular.forEach(locations, function(location, key) {
          // do something
        });
      });
    }
  };
});

In this way, the map directive can be used with any set of location data--the directive is not hard-coded to use a specific set of data, and simply linking the directive by including it in the DOM will not fire off random HTTP requests.

Javascript onclick hide div

just add onclick handler for anchor tag

onclick="this.parentNode.style.display = 'none'"

or change onclick handler for img tag

onclick="this.parentNode.parentNode.style.display = 'none'"

Why do I get PLS-00302: component must be declared when it exists?

You can get that error if you have an object with the same name as the schema. For example:

create sequence s2;

begin
  s2.a;
end;
/

ORA-06550: line 2, column 6:
PLS-00302: component 'A' must be declared
ORA-06550: line 2, column 3:
PL/SQL: Statement ignored

When you refer to S2.MY_FUNC2 the object name is being resolved so it doesn't try to evaluate S2 as a schema name. When you just call it as MY_FUNC2 there is no confusion, so it works.

The documentation explains name resolution. The first piece of the qualified object name - S2 here - is evaluated as an object on the current schema before it is evaluated as a different schema.

It might not be a sequence; other objects can cause the same error. You can check for the existence of objects with the same name by querying the data dictionary.

select owner, object_type, object_name
from all_objects
where object_name = 'S2';

How do I properly escape quotes inside HTML attributes?

Per HTML syntax, and even HTML5, the following are all valid options:

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

Note that if you are using XML syntax the quotes (single or double) are required.

Here's a jsfiddle showing all of the above working.

Why is Thread.Sleep so harmful

The problems with calling Thread.Sleep are explained quite succinctly here:

Thread.Sleep has its use: simulating lengthy operations while testing/debugging on an MTA thread. In .NET there's no other reason to use it.

Thread.Sleep(n) means block the current thread for at least the number of timeslices (or thread quantums) that can occur within n milliseconds. The length of a timeslice is different on different versions/types of Windows and different processors and generally ranges from 15 to 30 milliseconds. This means the thread is almost guaranteed to block for more than n milliseconds. The likelihood that your thread will re-awaken exactly after n milliseconds is about as impossible as impossible can be. So, Thread.Sleep is pointless for timing.

Threads are a limited resource, they take approximately 200,000 cycles to create and about 100,000 cycles to destroy. By default they reserve 1 megabyte of virtual memory for its stack and use 2,000-8,000 cycles for each context switch. This makes any waiting thread a huge waste.

The preferred solution: WaitHandles

The most-made-mistake is using Thread.Sleep with a while-construct (demo and answer, nice blog-entry)

EDIT:
I would like to enhance my answer:

We have 2 different use-cases:

  1. We are waiting because we know a specific timespan when we should continue (use Thread.Sleep, System.Threading.Timer or alikes)

  2. We are waiting because some condition changes some time ... keyword(s) is/are some time! if the condition-check is in our code-domain, we should use WaitHandles - otherwise the external component should provide some kind of hooks ... if it doesn't its design is bad!

My answer mainly covers use-case 2

React-Native: Application has not been registered error

In my case i have got a different solution in case any one need

yarn remove react-native-material-dropdown

Install new packages react-native-material-dropdown-v2

yarn add react-native-material-dropdown-v2

Replace react-native-material-dropdown with react-native-material-dropdown-v2 in your code

e.g. import { Dropdown } from 'react-native-material-dropdown' to import { Dropdown } from 'react-native-material-dropdown-v2'

another thing ==========

  1. Open node_modules and then search for react-native-material-textfield open the file and go to src folder
  2. Under src you will see affix, helper, label folder - under each folder, there is an index.js
  3. open the index.js of the mentioned folders one by one (all 3 folders) and search for the text style: Animated.Text.propTypes.style, and replace it by style: Text.propTypes
  4. And import text form react-native like this import { Animated , Text} from 'react-native';

How to update SQLAlchemy row entry?

user.no_of_logins += 1
session.commit()

Viewing local storage contents on IE

Since localStorage is a global object, you can add a watch in the dev tools. Just enter the dev tools, goto "watch", click on "Click to add..." and type in "localStorage".

Adding a parameter to the URL with JavaScript

A basic implementation which you'll need to adapt would look something like this:

function insertParam(key, value) {
    key = encodeURIComponent(key);
    value = encodeURIComponent(value);

    // kvp looks like ['key1=value1', 'key2=value2', ...]
    var kvp = document.location.search.substr(1).split('&');
    let i=0;

    for(; i<kvp.length; i++){
        if (kvp[i].startsWith(key + '=')) {
            let pair = kvp[i].split('=');
            pair[1] = value;
            kvp[i] = pair.join('=');
            break;
        }
    }

    if(i >= kvp.length){
        kvp[kvp.length] = [key,value].join('=');
    }

    // can return this or...
    let params = kvp.join('&');

    // reload page with new params
    document.location.search = params;
}

This is approximately twice as fast as a regex or search based solution, but that depends completely on the length of the querystring and the index of any match


the slow regex method I benchmarked against for completions sake (approx +150% slower)

function insertParam2(key,value)
{
    key = encodeURIComponent(key); value = encodeURIComponent(value);

    var s = document.location.search;
    var kvp = key+"="+value;

    var r = new RegExp("(&|\\?)"+key+"=[^\&]*");

    s = s.replace(r,"$1"+kvp);

    if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;};

    //again, do what you will here
    document.location.search = s;
}

Android custom dropdown/popup menu

The Kotlin Way

fun showPopupMenu(view: View) {
    PopupMenu(view.context, view).apply {
                menuInflater.inflate(R.menu.popup_men, menu)
                setOnMenuItemClickListener { item ->
                    Toast.makeText(view.context, "You Clicked : " + item.title, Toast.LENGTH_SHORT).show()
                    true
                }
            }.show()
}

UPDATE: In the above code, the apply function returns this which is not required, so we can use run which don't return anything and to make it even simpler we can also remove the curly braces of showPopupMenu method.

Even Simpler:

fun showPopupMenu(view: View) = PopupMenu(view.context, view).run {
            menuInflater.inflate(R.menu.popup_men, menu)
            setOnMenuItemClickListener { item ->
                Toast.makeText(view.context, "You Clicked : ${item.title}", Toast.LENGTH_SHORT).show()
                true
            }
            show()
        }

Port 80 is being used by SYSTEM (PID 4), what is that?

This can be very easily fixed by following these five steps:

  1. Open services
  2. Right click on World Wide Web Publishing Service
  3. Click STOP

To prevent this issue in future :

  1. Go to Properties
  2. Change Startup type to Manual

Viola u are good to go !

installing apache: no VCRUNTIME140.dll

I was gone through same problem & I resolved it by following steps.

  1. Uninstall earlier version of wamp server, which you are trying to install.
  2. Install which ever file supports to your configuration (64, 86) from en this link
  3. Restart your computer.
  4. Install wampserver now.

Why is it that "No HTTP resource was found that matches the request URI" here?

WebApiConfig.Register(GlobalConfiguration.Configuration); should be on top.

Testing the type of a DOM element in JavaScript

roenving is correct BUT you need to change the test to:

if(element.nodeType == 1) {
//code
}

because nodeType of 3 is actually a text node and nodeType of 1 is an HTML element. See http://www.w3schools.com/Dom/dom_nodetype.asp

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

I had same issue while using yeoman's angular-fullstack generated project and removing the IP parameter worked for me.

I replaced this code

server.listen(config.port, config.ip, function () {
  console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});

with

server.listen(config.port, function () {
  console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});

git - pulling from specific branch

if you want to pull from a specific branch all you have to do is

git pull 'remote_name' 'branch_name'

NOTE: Make sure you commit your code first.

How to create global variables accessible in all views using Express / Node.JS?

With the differents answers, I implemented this code to use an external file JSON loaded in "app.locals"

Parameters

{
    "web": {
        "title" : "Le titre de ma Page",
        "cssFile" : "20200608_1018.css"
    }
}

Application

var express     = require('express');
var appli       = express();
var serveur     = require('http').Server(appli);

var myParams    = require('./include/my_params.json');
var myFonctions = require('./include/my_fonctions.js');

appli.locals = myParams;

EJS Page

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title><%= web.title %></title>
    <link rel="stylesheet" type="text/css" href="/css/<%= web.cssFile %>">
</head>

</body>
</html>

Hoping it will help

How can I change the image displayed in a UIImageView programmatically?

My problem was that I tried to change the image in an other thread. I did like this:

- (void)changeImage {
    backgroundImage.image = [UIImage imageNamed:@"img.png"];
}

Call with:

[self performSelectorOnMainThread : @selector(changeImage) withObject:nil waitUntilDone:NO];

How to align this span to the right of the div?

The solution using flexbox without justify-content: space-between.

<div class="title">
  <span>Cumulative performance</span>
  <span>20/02/2011</span>
</div>

.title {
  display: flex;
}

span:first-of-type {
  flex: 1;
}

When we use flex:1 on the first <span>, it takes up the entire remaining space and moves the second <span> to the right. The Fiddle with this solution: https://jsfiddle.net/2k1vryn7/

Here https://jsfiddle.net/7wvx2uLp/3/ you can see the difference between two flexbox approaches: flexbox with justify-content: space-between and flexbox with flex:1 on the first <span>.

What is the meaning of the prefix N in T-SQL statements and when should I use it?

1. Performance:

Assume your where clause is like this:

WHERE NAME='JON'

If the NAME column is of any type other than nvarchar or nchar, then you should not specify the N prefix. However, if the NAME column is of type nvarchar or nchar, then if you do not specify the N prefix, then 'JON' is treated as non-unicode. This means the data type of NAME column and string 'JON' are different and so SQL Server implicitly converts one operand’s type to the other. If the SQL Server converts the literal’s type to the column’s type then there is no issue, but if it does the other way then performance will get hurt because the column's index (if available) wont be used.

2. Character set:

If the column is of type nvarchar or nchar, then always use the prefix N while specifying the character string in the WHERE criteria/UPDATE/INSERT clause. If you do not do this and one of the characters in your string is unicode (like international characters - example - a) then it will fail or suffer data corruption.

The localhost page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500

Such kind of error normally happens when you try using functions like php_info() wrongly.

<?php 
     php_info(); // 500 error
     phpinfo(); // Works correctly
?>

A close look at your code will be better.

Omitting the second expression when using the if-else shorthand

Using null is fine for one of the branches of a ternary expression. And a ternary expression is fine as a statement in Javascript.

As a matter of style, though, if you have in mind invoking a procedure, it's clearer to write this using if..else:

if (x==2) doSomething;
else doSomethingElse

or, in your case,

if (x==2) doSomething;

.war vs .ear file

WAR (web archive) files contain servlet class files, JSPs (Java servlet pages), HTML and graphical files, and other supporting files.

EAR (enterprise archive) files contain the WAR files along with the JAR files containing code.

There may be other things in those files but their basically meant for what they sound like they mean: WAR for web-type stuff, EAR for enterprise-type stuff (WARs, code, connectors et al).

Whitespaces in java

If you want to consider a regular expression based way of doing it

if(text.split("\\s").length > 1){
    //text contains whitespace
}

How to add constraints programmatically using Swift

Would like to add some theoretical concept to Imanou Petit’s answer, so that one can understand how auto layout works.

To understand auto layout consider your view as rubber's object which is shrinked initially.

To place an object on screen we need 4 mandatory things :

  • X coordinate of object (horizontal position).

  • Y coordinate of object (vertical position )

  • Object’s Width

  • Object’s Height.

1 X coordinate: There are multiple ways of giving x coordinates to a view.

Such as Leading constraint, Trailing constraint , Horizontally centre etc.

2 Y coordinate: There are multiple ways of giving y coordinates to a view :

Such as Top constraint, Bottom constraint , Vertical centre etc.

3 Object's width: There are two ways of giving width constrain to a view :

a. Add fixed width constraint (consider this constraint as iron rod of fixed width and you have hooked your rubber’s object horizontally with it so rubber’s object don’t shrink or expand)

b. Do not add any width constraint but add x coordinate constraint to both end of view trailing and leading, these two constraints will expand/shrink your rubber’s object by pulling/pushing it from both end, leading and trailing.

4 Object's height: Similar to width, there are two ways of giving height constraint to a view as well :

a. Add fixed height constraint (consider this constraints as iron rod of fixed height and you have hooked your rubber’s object vertically with it so rubber’s object don’t shrink or expand)

b. Do not add any height constraint but add x coordinate constraint to both end of view top and bottom, these two constraints will expand/shrink your rubber’s object pulling/pushing it from both end, top and bottom.

What does %s mean in a python format string?

%s indicates a conversion type of string when using python's string formatting capabilities. More specifically, %s converts a specified value to a string using the str() function. Compare this with the %r conversion type that uses the repr() function for value conversion.

Take a look at the docs for string formatting.

What is the difference between dynamic programming and greedy approach?

Difference between greedy method and dynamic programming are given below :

  1. Greedy method never reconsiders its choices whereas Dynamic programming may consider the previous state.

  2. Greedy algorithm is less efficient whereas Dynamic programming is more efficient.

  3. Greedy algorithm have a local choice of the sub-problems whereas Dynamic programming would solve the all sub-problems and then select one that would lead to an optimal solution.

  4. Greedy algorithm take decision in one time whereas Dynamic programming take decision at every stage.

Background Image for Select (dropdown) does not work in Chrome

What Arne said - you can't reliably style select boxes and have them look anything like consistent across browsers.

Uniform: https://github.com/pixelmatrix/uniform is a javascript solution which gives you good graphic control over your form elements - it's still Javascript, but it's about as nice as javascript gets for solving this problem.

Reading a file character by character in C

Expanding upon the above code from @dreamlax

char *readFile(char *fileName) {
    FILE *file = fopen(fileName, "r");
    char *code;
    size_t n = 0;
    int c;

    if (file == NULL) return NULL; //could not open file
    fseek(file, 0, SEEK_END);
    long f_size = ftell(file);
    fseek(file, 0, SEEK_SET);
    code = malloc(f_size);

    while ((c = fgetc(file)) != EOF) {
        code[n++] = (char)c;
    }

    code[n] = '\0';        

    return code;
}

This gives you the length of the file, then proceeds to read it character by character.

How to use target in location.href

The problem is that some versions of explorer don't support the window.open javascript function

Say what? Can you provide a reference for that statement? With respect, I think you must be mistaken. This works on IE6 and IE9, for instance.

Most modern browsers won't let your code use window.open except in direct response to a user event, in order to keep spam pop-ups and such at bay; perhaps that's what you're thinking of. As long as you only use window.open when responding to a user event, you should be fine using window.open — with all versions of IE.

There is no way to use location to open a new window. Just window.open or, of course, the user clicking a link with target="_blank".

Fix footer to bottom of page

My solution:

html, body {
  min-height: 100%
}

body {
  padding-bottom: 88px;
}

footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 88px;
}

REST vs JSON-RPC?

I have explored the issue in some detail and decided that pure REST is way too limiting, and RPC is best, even though most of my apps are CRUD apps. If you stick to REST, you eventually are going to be scratching your head wondering how you can easily add another needed method to your API for some special purpose. In many cases, the only way to do that with REST is to create another controller for it, which may unduly complicate your program.

If you decide on RPC, the only difference is that you are explicitly specifying the verb as part of the URI, which is clear, consistent, less buggy, and really no trouble. Especially if you create an app that goes way beyond simple CRUD, RPC is the only way to go. I have another issue with RESTful purists: HTTP POST, GET, PUT, DELETE have definite meanings in HTTP which have been subverted by REST into meaning other things, simply because they fit most of the time - but not all of the time.

In programming, I have long ago found that trying to use one thing to mean two things is going to come around sometime and bite you. I like to have the ability to use POST for just about every action, because it provides the freedom to send and receive data as your method needs to do. You can't fit the whole world into CRUD.

How to stop IIS asking authentication for default website on localhost

What worked for me is ,,,

Click Start>control panel>Administrative Tools>Internet Information Services

Expand the left tree, right-click your WebSite>Properties

Click on Directory Security, then in "Anonymous access and authentication control" click on Edit

Enable Anonymous access>browse> enter the credentials of the admin (like Administrator) (check names),> Click OK

Apply the settings and it should work fine.

Using multiple delimiters in awk

Good news! awk field separator can be a regular expression. You just need to use -F"<separator1>|<separator2>|...":

awk -F"/|=" -vOFS='\t' '{print $3, $5, $NF}' file

Returns:

tc0001  tomcat7.1  demo.example.com
tc0001  tomcat7.2  quest.example.com
tc0001  tomcat7.5  www.example.com

Here:

  • -F"/|=" sets the input field separator to either / or =. Then, it sets the output field separator to a tab.

  • -vOFS='\t' is using the -v flag for setting a variable. OFS is the default variable for the Output Field Separator and it is set to the tab character. The flag is necessary because there is no built-in for the OFS like -F.

  • {print $3, $5, $NF} prints the 3rd, 5th and last fields based on the input field separator.


See another example:

$ cat file
hello#how_are_you
i#am_very#well_thank#you

This file has two fields separators, # and _. If we want to print the second field regardless of the separator being one or the other, let's make both be separators!

$ awk -F"#|_" '{print $2}' file
how
am

Where the files are numbered as follows:

hello#how_are_you           i#am_very#well_thank#you
^^^^^ ^^^ ^^^ ^^^           ^ ^^ ^^^^ ^^^^ ^^^^^ ^^^
  1    2   3   4            1  2   3    4    5    6

Get yesterday's date using Date

Calendar cal = Calendar.getInstance();
   DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
   System.out.println("Today's date is "+dateFormat.format(cal.getTime()));

   cal.add(Calendar.DATE, -1);
   System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime())); 

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

i have same problem, i open several dialog my problem was what the content should be removed to prevent the form data stay with same data, then the dialog is created these paramters

var dialog = $("#dummy-1");

    dialog.html('<div style="position:absolute; top:15px; left:0px; right:0px; bottom:0px; text-align:center;"><img align="middle" src="cargando.gif"></div>');
    dialog.html(mensaje);
    dialog.dialog(
    {
        title:'Ventana de Confirmacion',
        width:400, 
        height:200, 
        modal:true,
        resizable: false,
        draggable:false,
        position: { my: "center center", at: "center center", of: window },
        buttons:
        [
            {
                text: "Eliminar",
                click: function() {
                    functionCall(dialog,var1,var2);
                }
            },
            {
                text: "Cerrar",
                click: function() {
                    dialog.dialog("close");
                }
            }
        ],
        close: function(event, ui)
        {
            dialog.dialog("close").dialog("destroy").remove();
        }
    });

and the dialog is passed as a parameter to the function to do action:

    function functionCall(dialogFormulario,var1,var2)
{
    //same action 
        dialogFormulario.dialog("close");

}

Here it is necessary only to use .dialog("close") and no .dialog("destroy") because the dialog will call its function close: and the element will not exist

comparing strings in vb

If String.Compare(string1,string2,True) Then

    'perform operation

EndIf

how to format date in Component of angular 5

You can find more information about the date pipe here, such as formats.

If you want to use it in your component, you can simply do

pipe = new DatePipe('en-US'); // Use your own locale

Now, you can simply use its transform method, which will be

const now = Date.now();
const myFormattedDate = this.pipe.transform(now, 'short');

What is the difference between require and require-dev sections in composer.json?

  1. According to composer's manual:

    require-dev (root-only)

    Lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both install or update support the --no-dev option that prevents dev dependencies from being installed.

    So running composer install will also download the development dependencies.

  2. The reason is actually quite simple. When contributing to a specific library you may want to run test suites or other develop tools (e.g. symfony). But if you install this library to a project, those development dependencies may not be required: not every project requires a test runner.

What is the difference between children and childNodes in JavaScript?

Good answers so far, I want to only add that you could check the type of a node using nodeType:

yourElement.nodeType

This will give you an integer: (taken from here)

| Value |             Constant             |                          Description                          |  |
|-------|----------------------------------|---------------------------------------------------------------|--|
|    1  | Node.ELEMENT_NODE                | An Element node such as <p> or <div>.                         |  |
|    2  | Node.ATTRIBUTE_NODE              | An Attribute of an Element. The element attributes            |  |
|       |                                  | are no longer implementing the Node interface in              |  |
|       |                                  | DOM4 specification.                                           |  |
|    3  | Node.TEXT_NODE                   | The actual Text of Element or Attr.                           |  |
|    4  | Node.CDATA_SECTION_NODE          | A CDATASection.                                               |  |
|    5  | Node.ENTITY_REFERENCE_NODE       | An XML Entity Reference node. Removed in DOM4 specification.  |  |
|    6  | Node.ENTITY_NODE                 | An XML <!ENTITY ...> node. Removed in DOM4 specification.     |  |
|    7  | Node.PROCESSING_INSTRUCTION_NODE | A ProcessingInstruction of an XML document                    |  |
|       |                                  | such as <?xml-stylesheet ... ?> declaration.                  |  |
|    8  | Node.COMMENT_NODE                | A Comment node.                                               |  |
|    9  | Node.DOCUMENT_NODE               | A Document node.                                              |  |
|   10  | Node.DOCUMENT_TYPE_NODE          | A DocumentType node e.g. <!DOCTYPE html> for HTML5 documents. |  |
|   11  | Node.DOCUMENT_FRAGMENT_NODE      | A DocumentFragment node.                                      |  |
|   12  | Node.NOTATION_NODE               | An XML <!NOTATION ...> node. Removed in DOM4 specification.   |  |

Note that according to Mozilla:

The following constants have been deprecated and should not be used anymore: Node.ATTRIBUTE_NODE, Node.ENTITY_REFERENCE_NODE, Node.ENTITY_NODE, Node.NOTATION_NODE

How to replace local branch with remote branch entirely in Git?

  1. Make sure you've checked out the branch you're replacing (from Zoltán's comment).
  2. Assuming that master is the local branch you're replacing, and that "origin/master" is the remote branch you want to reset to:

    git reset --hard origin/master
    

This updates your local HEAD branch to be the same revision as origin/master, and --hard will sync this change into the index and workspace as well.

jwt check if token expired

This is for react-native, but login will work for all types.

isTokenExpired = async () => {
    try {
        const LoginTokenValue = await AsyncStorage.getItem('LoginTokenValue');
        if (JSON.parse(LoginTokenValue).RememberMe) {
            const { exp } = JwtDecode(LoginTokenValue);
            if (exp < (new Date().getTime() + 1) / 1000) {
                this.handleSetTimeout();
                return false;
            } else {
                //Navigate inside the application
                return true;
            }
        } else {
            //Navigate to the login page
        }
    } catch (err) {
        console.log('Spalsh -> isTokenExpired -> err', err);
        //Navigate to the login page
        return false;
    }
}

CSS: Hover one element, effect for multiple elements?

This worked for me in Firefox and Chrome and IE8...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html>
    <head>
        <style type="text/css">
        div.section:hover div.image, div.section:hover div.layer {
            border: solid 1px red;
        }
        </style>
    </head>
    <body>
        <div class="section">
            <div class="image"><img src="myImage.jpg" /></div>
            <div class="layer">Lorem Ipsum</div>
        </div>
    </body>
</html>

... you may want to test this with IE6 as well (I'm not sure if it'll work there).

Get user profile picture by Id

From the Graph API documentation.

  • /OBJECT_ID/picture returns a redirect to the object's picture (in this case the users)
  • /OBJECT_ID/?fields=picture returns the picture's URL

Examples:

<img src="https://graph.facebook.com/4/picture"/> uses a HTTP 301 redirect to Zuck's profile picture

https://graph.facebook.com/4?fields=picture returns the URL itself

Plotting a python dict in order of key values

Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict

In your case, sort the dict by key before plotting,

import matplotlib.pylab as plt

lists = sorted(d.items()) # sorted by key, return a list of tuples

x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.plot(x, y)
plt.show()

Here is the result. enter image description here

jQuery autohide element after 5 seconds

Please note you may need to display div text again after it has disappeared. So you will need to also empty and then re-show the element at some point.

You can do this with 1 line of code:

$('#element_id').empty().show().html(message).delay(3000).fadeOut(300);

If you're using jQuery you don't need setTimeout, at least not to autohide an element.

Java getHours(), getMinutes() and getSeconds()

Java 8

    System.out.println(LocalDateTime.now().getHour());       // 7
    System.out.println(LocalDateTime.now().getMinute());     // 45
    System.out.println(LocalDateTime.now().getSecond());     // 32

Calendar

System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));  // 7 
System.out.println(Calendar.getInstance().get(Calendar.MINUTE));       // 45
System.out.println(Calendar.getInstance().get(Calendar.SECOND));       // 32

Joda Time

    System.out.println(new DateTime().getHourOfDay());      // 7
    System.out.println(new DateTime().getMinuteOfHour());   // 45
    System.out.println(new DateTime().getSecondOfMinute()); // 32

Formatted

Java 8

    // 07:48:55.056
    System.out.println(ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME));
    // 7:48:55
    System.out.println(LocalTime.now().getHour() + ":" + LocalTime.now().getMinute() + ":" + LocalTime.now().getSecond());

    // 07:48:55
    System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));

    // 074855
    System.out.println(new SimpleDateFormat("HHmmss").format(Calendar.getInstance().getTime()));

    // 07:48:55 
    System.out.println(new Date().toString().substring(11, 20));

Find all files in a folder

A lot of these answers won't actually work, having tried them myself. Give this a go:

string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo d = new DirectoryInfo(filepath);

foreach (var file in d.GetFiles("*.txt"))
{
      Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name);
}

It will move all .txt files on the desktop to the folder TextFiles.

Indent starting from the second line of a paragraph with CSS

Is it literally just the second line you want to indent, or is it from the second line (ie. a hanging indent)?

If it is the latter, something along the lines of this JSFiddle would be appropriate.

_x000D_
_x000D_
    div {_x000D_
        padding-left: 1.5em;_x000D_
        text-indent:-1.5em;_x000D_
    }_x000D_
    _x000D_
    span {_x000D_
        padding-left: 1.5em;_x000D_
        text-indent:-1.5em;_x000D_
    }
_x000D_
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</div>_x000D_
_x000D_
<span>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</span>
_x000D_
_x000D_
_x000D_

This example shows how using the same CSS syntax in a DIV or SPAN produce different effects.

How to make an input type=button act like a hyperlink and redirect using a get request?

Do not do it. I might want to run my car on monkey blood. I have my reasons, but sometimes it's better to stick with using things the way they were designed even if it doesn't "absolutely perfectly" match the exact look you are driving for.

To back up my argument I submit the following.

  • See how this image lacks the status bar at the bottom. This link is using the onclick="location.href" model. (This is a real-life production example from my predecessor) This can make users hesitant to click on the link, since they have no idea where it is taking them, for starters.

Image

You are also making Search engine optimization more difficult IMO as well as making the debugging and reading of your code/HTML more complex. A submit button should submit a form. Why should you(the development community) try to create a non-standard UI?

Eclipse projects not showing up after placing project files in workspace/projects

I had the same problem over and over again the solution that a have found works for now

  1. Close Eclipse.
  2. go to workspace.metadata.plugins
  3. remove org.eclipse.core.resources
  4. Start Eclipse
  5. Do File->Import
  6. General->Existing Projects into Workspace and import all the project from the workspace

Can't use Swift classes inside Objective-C

There is two condition,

  • Use your swift file in objective c file.
  • Use your objective c file in swift file.

So, For that purpose, you have to follow this steps:

  • Add your swift file in an objective-c project or vice-versa.
  • Create header(.h) file.
  • Go to Build Settings and perform below steps with search,

    1. search for this text "brid" and set a path of your header file.
    2. "Defines Module": YES.
    3. "Always Embed Swift Standard Libraries" : YES.
    4. "Install Objective-C Compatibility Header" : YES.

After that, clean and rebuild your project.

Use your swift file in objective c file.

In that case,First write "@objc" before your class in swift file.

After that ,In your objective c file, write this,

  #import "YourProjectName-Swift.h"

Use your objective c file in swift file.

In that case, In your header file, write this,

  #import "YourObjective-c_FileName.h"

I hope this will help you.

How to create Custom Ratings bar in Android

You can create custom material rating bar by defining drawable xml using material icon of your choice and then applying custom drawable to rating bar using progressDrawable attribute.

For infomration about customizing rating bar see http://www.zoftino.com/android-ratingbar-and-custom-ratingbar-example

Below drawable xml uses thumbs up icon for rating bar.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <bitmap
            android:src="@drawable/thumb_up"
            android:tint="?attr/colorControlNormal" />
    </item>
    <item android:id="@android:id/secondaryProgress">
        <bitmap
            android:src="@drawable/thumb_up"
            android:tint="?attr/colorControlActivated" />
    </item>
    <item android:id="@android:id/progress">
        <bitmap
            android:src="@drawable/thumb_up"
            android:tint="?attr/colorControlActivated" />
    </item>
</layer-list>

Detect encoding and make everything UTF-8

It's simple: when you get something that's not UTF-8, you must encode that into UTF-8.

So, when you're fetching a certain feed that's ISO 8859-1 parse it through utf8_encode.

However, if you're fetching an UTF-8 feed, you don't need to do anything.

Regular Expressions and negating a whole character group

Use negative lookahead:

^(?!.*ab).*$

UPDATE: In the comments below, I stated that this approach is slower than the one given in Peter's answer. I've run some tests since then, and found that it's really slightly faster. However, the reason to prefer this technique over the other is not speed, but simplicity.

The other technique, described here as a tempered greedy token, is suitable for more complex problems, like matching delimited text where the delimiters consist of multiple characters (like HTML, as Luke commented below). For the problem described in the question, it's overkill.

For anyone who's interested, I tested with a large chunk of Lorem Ipsum text, counting the number of lines that don't contain the word "quo". These are the regexes I used:

(?m)^(?!.*\bquo\b).+$

(?m)^(?:(?!\bquo\b).)+$

Whether I search for matches in the whole text, or break it up into lines and match them individually, the anchored lookahead consistently outperforms the floating one.

Which is better, return value or out parameter?

There is no real difference. Out parameters are in C# to allow method return more then one value, that's all.

However There are some slight differences , but non of them are really important:

Using out parameter will enforce you to use two lines like:

int n;
GetValue(n);

while using return value will let you do it in one line:

int n = GetValue();

Another difference (correct only for value types and only if C# doesn't inline the function) is that using return value will necessarily make a copy of the value when the function return, while using OUT parameter will not necessarily do so.

How to do a LIKE query with linq?

You can use contains:

string[] example = { "sample1", "sample2" };
var result = (from c in example where c.Contains("2") select c);
// returns only sample2

PHP CSV string to array

I have used following function to parse csv string to associative array

public function csvToArray($file) {
    $rows = array();
    $headers = array();
    if (file_exists($file) && is_readable($file)) {
        $handle = fopen($file, 'r');
        while (!feof($handle)) {
            $row = fgetcsv($handle, 10240, ',', '"');
            if (empty($headers))
                $headers = $row;
            else if (is_array($row)) {
                array_splice($row, count($headers));
                $rows[] = array_combine($headers, $row);
            }
        }
        fclose($handle);
    } else {
        throw new Exception($file . ' doesn`t exist or is not readable.');
    }
    return $rows;
}

if your csv file name is mycsv.csv then you call this function as:

$dataArray = csvToArray(mycsv.csv);

you can get this script also in http://www.scriptville.in/parse-csv-data-to-array/

Get SELECT's value and text in jQuery

$('select').val()  // Get's the value

$('select option:selected').val() ; // Get's the value

$('select').find('option:selected').val() ; // Get's the value

$('select option:selected').text()  // Gets you the text of the selected option

Check FIDDLE

How to use pull to refresh in Swift?

A solution with storyboard and Swift:

  1. Open your .storyboard file, select a TableViewController in your storyboard and "Enable" the Table View Controller: Refreshing feature in the Utilities.

    Inspector

  2. Open the associated UITableViewController class and add the following Swift 5 line into the viewDidLoad method.

    self.refreshControl?.addTarget(self, action: #selector(refresh), for: UIControl.Event.valueChanged)
    
  3. Add the following method above the viewDidLoad method

    func refresh(sender:AnyObject)
    {
        // Updating your data here...
    
        self.tableView.reloadData()
        self.refreshControl?.endRefreshing()
    }
    

How can I push a specific commit to a remote, and not previous commits?

You could also, in another directory:

  • git clone [your repository]
  • Overwrite the .git directory in your original repository with the .git directory of the repository you just cloned right now.
  • git add and git commit your original

Passing two command parameters using a WPF binding

Use Tuple in Converter, and in OnExecute, cast the parameter object back to Tuple.

public class YourConverter : IMultiValueConverter 
{      
    public object Convert(object[] values, ...)     
    {   
        Tuple<string, string> tuple = new Tuple<string, string>(
            (string)values[0], (string)values[1]);
        return (object)tuple;
    }      
} 

// ...

public void OnExecute(object parameter) 
{
    var param = (Tuple<string, string>) parameter;
}

How to use LINQ to select object with minimum or maximum property value

NOTE: I include this answer for completeness since the OP didn't mention what the data source is and we shouldn't make any assumptions.

This query gives the correct answer, but could be slower since it might have to sort all the items in People, depending on what data structure People is:

var oldest = People.OrderBy(p => p.DateOfBirth ?? DateTime.MaxValue).First();

UPDATE: Actually I shouldn't call this solution "naive", but the user does need to know what he is querying against. This solution's "slowness" depends on the underlying data. If this is a array or List<T>, then LINQ to Objects has no choice but to sort the entire collection first before selecting the first item. In this case it will be slower than the other solution suggested. However, if this is a LINQ to SQL table and DateOfBirth is an indexed column, then SQL Server will use the index instead of sorting all the rows. Other custom IEnumerable<T> implementations could also make use of indexes (see i4o: Indexed LINQ, or the object database db4o) and make this solution faster than Aggregate() or MaxBy()/MinBy() which need to iterate the whole collection once. In fact, LINQ to Objects could have (in theory) made special cases in OrderBy() for sorted collections like SortedList<T>, but it doesn't, as far as I know.

Move all files except one

move all files(not include except file) to except_file
find -maxdepth 1 -mindepth 1 -not -name except_file -print0 |xargs -0 mv -t ./except_file
for example(cache is current except file)
find -maxdepth 1 -mindepth 1 -not -name cache -print0 |xargs -0 mv -t ./cache

What type of hash does WordPress use?

include_once('../../../wp-config.php');

global $wpdb;

$password = wp_hash_password("your password");

Count the cells with same color in google spreadsheet

Easy solution if you don't want to code manually using Google Sheets Power Tools:

  1. Install Power Tools through the Add-ons panel (Add-ons -> Get add-ons)
  2. From the Power Tools sidebar click on the S button and within that menu click on the "Sum by Color" menu item
  3. Select the "Pattern cell" with the color markup you want to search for
  4. Select the "Source range" for the cells you want to count
  5. Use function should be set to "COUNTA"
  6. Press "Insert function" and you're done :)

PDOException “could not find driver”

Incorrect installation of PHP was being called

I was experiencing the same problem. And I hope this would help someone who is having a similar issue as me.

Scenario

OS = Windows 10  
Platform = XAMPP  
PHP Version = 7 (Multiple Version seem to have been installed in the PC)  

I created phpinfo.php file in the public folder and run the phpinfo() to look for the location of my php.ini file.

PHP.ini Location = c:\xampp\php\php.ini

Problem
Calling c:\xampp\htdocs> php -v returned PHP 7.2.3 but phpinfo.php showed PHP 7.2.2.

Solution
Instead of calling

php artisan migrate:install   

which gave me this error, I used

c:\xampp\php\php artisan migrate:install

and it worked.

Dynamic creation of table with DOM

You need to create new TextNodes as well as td nodes for each column, not reuse them among all of the columns as your code is doing.

Edit: Revise your code like so:

for (var i = 1; i < 4; i++)
{
   tr[i] = document.createElement('tr');   
      var td1 = document.createElement('td');
      var td2 = document.createElement('td');
      td1.appendChild(document.createTextNode('Text1'));
      td2.appendChild(document.createTextNode('Text2'));
      tr[i].appendChild(td1);
      tr[i].appendChild(td2);
  table.appendChild(tr[i]);
}

How can I install a .ipa file to my iPhone simulator

You can't. If it was downloaded via the iTunes store it was built for a different processor and won't work in the simulator.

How to get data by SqlDataReader.GetValue by column name

thisReader.GetString(int columnIndex)

JavaScript single line 'if' statement - best syntax, this alternative?

I've seen many answers with many votes advocating using the ternary operator. The ternary is great if a) you do have an alternative option and b) you are returning a fairly simple value from a simple condition. But...

The original question didn't have an alternative, and the ternary operator with only a single (real) branch forces you to return a confected answer.

lemons ? "foo gave me a bar" : "who knows what you'll get back"

I think the most common variation is lemons ? 'foo...' : '', and, as you'll know from reading the myriad of articles for any language on true, false, truthy, falsey, null, nil, blank, empty (with our without ?) , you are entering a minefield (albeit a well documented minefield.)

As soon as any part of the ternary gets complicated you are better off with a more explicit form of conditional.

A long way to say that I am voting for if (lemons) "foo".

how to fix stream_socket_enable_crypto(): SSL operation failed with code 1

To resolve this problem you first need to check the SSL certificates of the host your are connecting to. For example using ssllabs or other ssl tools. In my case the intermediate certificate was wrong.

If the certificate is ok, make sure the openSSL on your server is up to date. Run openssl -v to check your version. Maybe your version is to old to work with the certificate.

In very rare cases you might want to disable ssl security features like verify_peer, verify_peer_name or allow_self_signed. Please be very careful with this and never use this in production. This is only an option for temporary testing.

How to change color of SVG image using CSS (jQuery SVG image replacement)?

You can use data-image for that. using data-image(data-URI) you can access SVG like inline.

Here is rollover effect using pure CSS and SVG.

I know it messy but you can do this way.

_x000D_
_x000D_
 .action-btn {_x000D_
    background-size: 20px 20px;_x000D_
    background-position: center center;_x000D_
    background-repeat: no-repeat;_x000D_
    border-width: 1px;_x000D_
    border-style: solid;_x000D_
    border-radius: 30px;_x000D_
    height: 40px;_x000D_
    width: 60px;_x000D_
    display: inline-block;_x000D_
 }_x000D_
_x000D_
.delete {_x000D_
     background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg version='1.1' id='Capa_1' fill='#FB404B' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='482.428px' height='482.429px' viewBox='0 0 482.428 482.429' style='enable-background:new 0 0 482.428 482.429;' xml:space='preserve'%3e%3cg%3e%3cg%3e%3cpath d='M381.163,57.799h-75.094C302.323,25.316,274.686,0,241.214,0c-33.471,0-61.104,25.315-64.85,57.799h-75.098 c-30.39,0-55.111,24.728-55.111,55.117v2.828c0,23.223,14.46,43.1,34.83,51.199v260.369c0,30.39,24.724,55.117,55.112,55.117 h210.236c30.389,0,55.111-24.729,55.111-55.117V166.944c20.369-8.1,34.83-27.977,34.83-51.199v-2.828 C436.274,82.527,411.551,57.799,381.163,57.799z M241.214,26.139c19.037,0,34.927,13.645,38.443,31.66h-76.879 C206.293,39.783,222.184,26.139,241.214,26.139z M375.305,427.312c0,15.978-13,28.979-28.973,28.979H136.096 c-15.973,0-28.973-13.002-28.973-28.979V170.861h268.182V427.312z M410.135,115.744c0,15.978-13,28.979-28.973,28.979H101.266 c-15.973,0-28.973-13.001-28.973-28.979v-2.828c0-15.978,13-28.979,28.973-28.979h279.897c15.973,0,28.973,13.001,28.973,28.979 V115.744z'/%3e%3cpath d='M171.144,422.863c7.218,0,13.069-5.853,13.069-13.068V262.641c0-7.216-5.852-13.07-13.069-13.07 c-7.217,0-13.069,5.854-13.069,13.07v147.154C158.074,417.012,163.926,422.863,171.144,422.863z'/%3e%3cpath d='M241.214,422.863c7.218,0,13.07-5.853,13.07-13.068V262.641c0-7.216-5.854-13.07-13.07-13.07 c-7.217,0-13.069,5.854-13.069,13.07v147.154C228.145,417.012,233.996,422.863,241.214,422.863z'/%3e%3cpath d='M311.284,422.863c7.217,0,13.068-5.853,13.068-13.068V262.641c0-7.216-5.852-13.07-13.068-13.07 c-7.219,0-13.07,5.854-13.07,13.07v147.154C298.213,417.012,304.067,422.863,311.284,422.863z'/%3e%3c/g%3e%3c/g%3e%3c/svg%3e ");_x000D_
     border-color:#FB404B;_x000D_
     _x000D_
 }_x000D_
 _x000D_
 .delete:hover {_x000D_
     background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg version='1.1' id='Capa_1' fill='#fff' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='482.428px' height='482.429px' viewBox='0 0 482.428 482.429' style='enable-background:new 0 0 482.428 482.429;' xml:space='preserve'%3e%3cg%3e%3cg%3e%3cpath d='M381.163,57.799h-75.094C302.323,25.316,274.686,0,241.214,0c-33.471,0-61.104,25.315-64.85,57.799h-75.098 c-30.39,0-55.111,24.728-55.111,55.117v2.828c0,23.223,14.46,43.1,34.83,51.199v260.369c0,30.39,24.724,55.117,55.112,55.117 h210.236c30.389,0,55.111-24.729,55.111-55.117V166.944c20.369-8.1,34.83-27.977,34.83-51.199v-2.828 C436.274,82.527,411.551,57.799,381.163,57.799z M241.214,26.139c19.037,0,34.927,13.645,38.443,31.66h-76.879 C206.293,39.783,222.184,26.139,241.214,26.139z M375.305,427.312c0,15.978-13,28.979-28.973,28.979H136.096 c-15.973,0-28.973-13.002-28.973-28.979V170.861h268.182V427.312z M410.135,115.744c0,15.978-13,28.979-28.973,28.979H101.266 c-15.973,0-28.973-13.001-28.973-28.979v-2.828c0-15.978,13-28.979,28.973-28.979h279.897c15.973,0,28.973,13.001,28.973,28.979 V115.744z'/%3e%3cpath d='M171.144,422.863c7.218,0,13.069-5.853,13.069-13.068V262.641c0-7.216-5.852-13.07-13.069-13.07 c-7.217,0-13.069,5.854-13.069,13.07v147.154C158.074,417.012,163.926,422.863,171.144,422.863z'/%3e%3cpath d='M241.214,422.863c7.218,0,13.07-5.853,13.07-13.068V262.641c0-7.216-5.854-13.07-13.07-13.07 c-7.217,0-13.069,5.854-13.069,13.07v147.154C228.145,417.012,233.996,422.863,241.214,422.863z'/%3e%3cpath d='M311.284,422.863c7.217,0,13.068-5.853,13.068-13.068V262.641c0-7.216-5.852-13.07-13.068-13.07 c-7.219,0-13.07,5.854-13.07,13.07v147.154C298.213,417.012,304.067,422.863,311.284,422.863z'/%3e%3c/g%3e%3c/g%3e%3c/svg%3e ");        _x000D_
     background-color: #FB404B;_x000D_
    }
_x000D_
<a class="action-btn delete">&nbsp;</a>
_x000D_
_x000D_
_x000D_

You can convert your svg to data url here

  1. https://codepen.io/elliz/full/ygvgay
  2. https://websemantics.uk/tools/svg-to-background-image-conversion/

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

Here are a few ways to create a list with N of continuous natural numbers starting from 1.

1 range:

def numbers(n): 
    return range(1, n+1);

2 List Comprehensions:

def numbers(n):
    return [i for i in range(1, n+1)]

You may want to look into the method xrange and the concepts of generators, those are fun in python. Good luck with your Learning!

How to set min-font-size in CSS

CSS has a clamp() function that holds the value between the upper and lower bound. The clamp() function enables the selection of the middle value in the range of values between the defined minimum and maximum values.

It simply takes three dimensions:

  1. Minimum value.
  2. List item
  3. Preferred value Maximum allowed value.

try with the code below, and check the window resize, which will change the font size you see in the console. i set maximum value 150px and minimum value 100px.

_x000D_
_x000D_
$(window).resize(function(){_x000D_
    console.log($('#element').css('font-size'));_x000D_
});_x000D_
console.log($('#element').css('font-size'));
_x000D_
h1{_x000D_
    font-size: 10vw; /* Browsers that do not support "MIN () - MAX ()" and "Clamp ()" functions will take this value.*/_x000D_
    font-size: max(100px, min(10vw, 150px)); /* Browsers that do not support the "clamp ()" function will take this value. */_x000D_
    font-size: clamp(100px, 10vw, 150px);_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<center>_x000D_
  <h1 id="element">THIS IS TEXT</h1>_x000D_
</center>
_x000D_
_x000D_
_x000D_

jquery to change style attribute of a div class

Try with

$('.handle').css({'left': '300px'});

Instead of

$('.handle').css({'style':'left: 300px'})

How do I select the parent form based on which submit button is clicked?

To get the form that the submit is inside why not just

this.form

Easiest & quickest path to the result.

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

I feel the performance characteristics change from one DBMS to another. It's all on how they choose to implement it. Since I have worked extensively on Oracle, I'll tell from that perspective.

COUNT(*) - Fetches entire row into result set before passing on to the count function, count function will aggregate 1 if the row is not null

COUNT(1) - Will not fetch any row, instead count is called with a constant value of 1 for each row in the table when the WHERE matches.

COUNT(PK) - The PK in Oracle is indexed. This means Oracle has to read only the index. Normally one row in the index B+ tree is many times smaller than the actual row. So considering the disk IOPS rate, Oracle can fetch many times more rows from Index with a single block transfer as compared to entire row. This leads to higher throughput of the query.

From this you can see the first count is the slowest and the last count is the fastest in Oracle.

Checking for duplicate strings in JavaScript array

_x000D_
_x000D_
function hasDuplicates(arr) {
    var counts = [];

    for (var i = 0; i <= arr.length; i++) {
        if (counts[arr[i]] === undefined) {
            counts[arr[i]] = 1;
        } else {
            return true;
        }
    }
    return false;
}

// [...]

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

if (hasDuplicates(arr)) {
  alert('Error: you have duplicates values !')
}
_x000D_
_x000D_
_x000D_

Simple Javascript (if you don't know ES6)

function hasDuplicates(arr) {
    var counts = [];

    for (var i = 0; i <= arr.length; i++) {
        if (counts[arr[i]] === undefined) {
            counts[arr[i]] = 1;
        } else {
            return true;
        }
    }
    return false;
}

// [...]

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

if (hasDuplicates(arr)) {
  alert('Error: you have duplicates values !')
}

Removing header column from pandas dataframe

How to get rid of a header(first row) and an index(first column).

To write to CSV file:

df = pandas.DataFrame(your_array)
df.to_csv('your_array.csv', header=False, index=False)

To read from CSV file:

df = pandas.read_csv('your_array.csv')
a = df.values

If you want to read a CSV file that doesn't contain a header, pass additional parameter header:

df = pandas.read_csv('your_array.csv', header=None)

How to add elements to a list in R (loop)

The following adds elements to a list in a loop.

l<-c()
i=1

while(i<100) {

    b<-i
    l<-c(l,b)
    i=i+1
}

Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central?

The following command helped me (executing on bash before running mvn)

export MAVEN_OPTS=-Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2

Read response body in JAX-RS client from a post request

Acording with the documentation, the method getEntity in Jax rs 2.0 return a InputStream. If you need to convert to InputStream to String with JSON format, you need to cast the two formats. For example in my case, I implemented the next method:

    private String processResponse(Response response) {
    if (response.getEntity() != null) {
        try {
            InputStream salida = (InputStream) response.getEntity();
            StringWriter writer = new StringWriter();
            IOUtils.copy(salida, writer, "UTF-8");
            return writer.toString();
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    }
    return null;
}

why I implemented this method. Because a read in differets blogs that many developers they have the same problem whit the version in jaxrs using the next methods

String output = response.readEntity(String.class)

and

String output = response.getEntity(String.class)

The first works using jersey-client from com.sun.jersey library and the second found using the jersey-client from org.glassfish.jersey.core.

This is the error that was being presented to me: org.glassfish.jersey.client.internal.HttpUrlConnector$2 cannot be cast to java.lang.String

I use the following maven dependency:

<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.28</version>

What I do not know is why the readEntity method does not work.I hope you can use the solution.

Carlos Cepeda

adding text to an existing text element in javascript via DOM

_x000D_
_x000D_
var t = document.getElementById("p").textContent;
var y = document.createTextNode("This just got added");

t.appendChild(y);
_x000D_
<p id="p">This is some text</p>
_x000D_
_x000D_
_x000D_

What is an application binary interface (ABI)?

The ABI needs to be consistent between caller and callee to be certain that the call succeeds. Stack use, register use, end-of-routine stack pop. All these are the most important parts of the ABI.

Change selected value of kendo ui dropdownlist

Since this is one of the top search results for questions related to this I felt it was worth mentioning how you can make this work with Kendo().DropDownListFor() as well.

Everything is the same as with OnaBai's post except for how you select the item based off of its text and your selector.

To do that you would swap out dataItem.symbol for dataItem.[DataTextFieldName]. Whatever model field you used for .DataTextField() is what you will be comparing against.

@(Html.Kendo().DropDownListFor(model => model.Status.StatusId)
    .Name("Status.StatusId")
    .DataTextField("StatusName")
    .DataValueField("StatusId")
    .BindTo(...)
)

//So that your ViewModel gets bound properly on the post, naming is a bit 
//different and as such you need to replace the periods with underscores
var ddl = $('#Status_StatusId').data('kendoDropDownList');    

ddl.select(function(dataItem) {
    return dataItem.StatusName === "Active";
});

Powershell send-mailmessage - email to multiple recipients

here is a full (gmail) and simple solution... just use normal ; delimiter.. best for passing in as params.

$to = "[email protected];[email protected]"
$user = "[email protected]"    
$pass = ConvertTo-SecureString -String "pass" -AsPlainText -Force

$cred = New-Object System.Management.Automation.PSCredential $user, $pass
$mailParam = @{
    To = $to.Split(';')
    From = "IT Alerts <[email protected]>"
    Subject = "test"
    Body = "test"
    SmtpServer = "smtp.gmail.com"
    Port = 587
    Credential = $cred
}

Send-MailMessage @mailParam -UseSsl

How do I find the value of $CATALINA_HOME?

Just as a addition. You can find the Catalina Paths in

->RUN->RUN CONFIGURATIONS->APACHE TOMCAT->ARGUMENTS

In the VM Arguments the Paths are listed and changeable

Java 8 - Difference between Optional.flatMap and Optional.map

Okay. You only need to use 'flatMap' when you're facing nested Optionals. Here's the example.

public class Person {

    private Optional<Car> optionalCar;

    public Optional<Car> getOptionalCar() {
        return optionalCar;
    }
}

public class Car {

    private Optional<Insurance> optionalInsurance;

    public Optional<Insurance> getOptionalInsurance() {
        return optionalInsurance;
    }
}

public class Insurance {

    private String name;

    public String getName() {
        return name;
    }

}

public class Test {

    // map cannot deal with nested Optionals
    public Optional<String> getCarInsuranceName(Person person) {
        return person.getOptionalCar()
                .map(Car::getOptionalInsurance) // ? leads to a Optional<Optional<Insurance>
                .map(Insurance::getName);       // ?
    }

}

Like Stream, Optional#map will return a value wrapped by a Optional. That's why we get a nested Optional -- Optional<Optional<Insurance>. And at ?, we want to map it as an Insurance instance, that's how the tragedy happened. The root is nested Optionals. If we can get the core value regardless the shells, we'll get it done. That's what flatMap does.

public Optional<String> getCarInsuranceName(Person person) {
    return person.getOptionalCar()
                 .flatMap(Car::getOptionalInsurance)
                 .map(Insurance::getName);
}

In the end, I stronly recommed the Java 8 In Action to you if you'd like to study Java8 Systematicly.

How I can delete in VIM all text from current line to end of file?

Just add another way , in normal mode , type ctrl+v then G, select the rest, then D, I don't think it is effective , you should do like @Ed Guiness, head -n 20 > filename in linux.

Adding a css class to select using @Html.DropDownList()

Simply Try this

@Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID,  new { @class="dropdown" })

But if you want a default value or no option value then you must have to try this one, because String.Empty will select that no value for you which will work as a -select- as default option

@Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID, String.Empty, new { @class="dropdown" })

CodeIgniter Active Record - Get number of returned rows

$this->db->select('count(id) as rows');
$this->db->from('table_name');
$this->db->where('active',1);
$query = $this->db->get();
foreach($query->result() as $r)
{
   return $r->rows;
}

How change default SVN username and password to commit changes?

For Windows (7), the same folder is located at,

%APPDATA%\Subversion\auth

Type in the above in the Run(Win key + R) dialog box and hit Enter,

To check the existing username open the below file as a text file,

%APPDATA%\Subversion\auth\svn.simple\xxxxxxxxxx

XAMPP on Windows - Apache not starting

For me, the problem was I had two installations of Apache Tomcat

The following steps solved my problem:

  1. Open up services.msc in command prompt
  2. Select the Apache Tomcat service, right click and select properties
  3. Check the path to the executable of the service
  4. Follow the instructions in https://stackoverflow.com/questions/7190480/modifying-the-path-to-executable-of-a-windows-service to change the path to "\tomcat\bin\tomcat7.exe" //RS//Tomcat7
  5. Restart XAMPP Control Panel

Javascript: The prettiest way to compare one value against multiple values

What i use to do, is put those multiple values in an array like

var options = [foo, bar];

and then, use indexOf()

if(options.indexOf(foobar) > -1){
   //do something
}

for prettiness:

if([foo, bar].indexOf(foobar) +1){
   //you can't get any more pretty than this :)
}

and for the older browsers:
( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/IndexOf )

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}

How to remove word wrap from textarea?

Textareas shouldn't wrap by default, but you can set wrap="soft" to explicitly disable wrap:

<textarea name="nowrap" cols="30" rows="3" wrap="soft"></textarea>

EDIT: The "wrap" attribute is not officially supported. I got it from the german SELFHTML page (an english source is here) that says IE 4.0 and Netscape 2.0 support it. I also tested it in FF 3.0.7 where it works as supposed. Things have changed here, SELFHTML is now a wiki and the english source link is dead.

EDIT2: If you want to be sure every browser supports it, you can use CSS to change wrap behaviour:

Using Cascading Style Sheets (CSS), you can achieve the same effect with white-space: nowrap; overflow: auto;. Thus, the wrap attribute can be regarded as outdated.

From here (seems to be an excellent page with information about textarea).

EDIT3: I'm not sure when it changed (according to the comments, must've been around 2014), but wrap is now an official HTML5 attribute, see w3schools. Changed the answer to match this.

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

Yep, confirmed that simply using hh instead of HH fixed my issue.

Changed from this:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm aa");

To this:

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");

You can still use HH to store the time if you don't want to bother storing and dealing with the AM/PM. Then when you retrieve it, use hh.

Properly embedding Youtube video into bootstrap 3.0 page

There is a Bootstrap3 native solution: http://getbootstrap.com/components/#responsive-embed

since Bootstrap 3.2.0!

If you are using Bootstrap < v3.2.0 so look into "responsive-embed.less" file of v3.2.0 - possibly you can use/copy this code in your case (it works for me in v3.1.1).

How to calculate the IP range when the IP address and the netmask is given?

I would recommend the use of IPNetwork Library https://github.com/lduchosal/ipnetwork. As of version 2, it supports IPv4 and IPv6 as well.

IPv4

  IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/25");

  Console.WriteLine("Network : {0}", ipnetwork.Network);
  Console.WriteLine("Netmask : {0}", ipnetwork.Netmask);
  Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast);
  Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable);
  Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable);
  Console.WriteLine("Usable : {0}", ipnetwork.Usable);
  Console.WriteLine("Cidr : {0}", ipnetwork.Cidr);

Output

  Network : 192.168.0.0
  Netmask : 255.255.255.128
  Broadcast : 192.168.0.127
  FirstUsable : 192.168.0.1
  LastUsable : 192.168.0.126
  Usable : 126
  Cidr : 25

Have fun !

Why does viewWillAppear not get called when an app comes back from the background?

viewWillAppear:animated:, one of the most confusing methods in the iOS SDKs in my opinion, is never be invoked in such a situation, i.e., application switching. That method is only invoked according to the relationship between the view controller's view and the application's window, i.e., the message is sent to a view controller only if its view appears on the application's window, not on the screen.

When your application goes background, obviously the topmost views of the application window are no longer visible to the user. In your application window's perspective, however, they are still the topmost views and therefore they did not disappear from the window. Rather, those views disappeared because the application window disappeared. They did not disappeared because they disappeared from the window.

Therefore, when the user switches back to your application, they obviously seem to appear on the screen, because the window appears again. But from the window's perspective, they haven't disappeared at all. Therefore the view controllers never get the viewWillAppear:animated message.

Git: How to return from 'detached HEAD' state

If you remember which branch was checked out before (e.g. master) you could simply

git checkout master

to get out of detached HEAD state.

Generally speaking: git checkout <branchname> will get you out of that.

If you don't remember the last branch name, try

git checkout -

This also tries to check out your last checked out branch.

Equivalent of jQuery .hide() to set visibility: hidden

You could make your own plugins.

jQuery.fn.visible = function() {
    return this.css('visibility', 'visible');
};

jQuery.fn.invisible = function() {
    return this.css('visibility', 'hidden');
};

jQuery.fn.visibilityToggle = function() {
    return this.css('visibility', function(i, visibility) {
        return (visibility == 'visible') ? 'hidden' : 'visible';
    });
};

If you want to overload the original jQuery toggle(), which I don't recommend...

!(function($) {
    var toggle = $.fn.toggle;
    $.fn.toggle = function() {
        var args = $.makeArray(arguments),
            lastArg = args.pop();

        if (lastArg == 'visibility') {
            return this.visibilityToggle();
        }

        return toggle.apply(this, arguments);
    };
})(jQuery);

jsFiddle.

Get name of currently executing test in JUnit 4

I'd suggest you decouple the test method name from your test data set. I would model a DataLoaderFactory class which loads/caches the sets of test data from your resources, and then in your test case cam call some interface method which returns a set of test data for the test case. Having the test data tied to the test method name assumes the test data can only be used once, where in most case i'd suggest that the same test data in uses in multiple tests to verify various aspects of your business logic.

Fully custom validation error message with Rails

Just do it the normal way:

validates_presence_of :email, :message => "Email is required."

But display it like this instead

<% if @user.errors.any? %>
  <% @user.errors.messages.each do |message| %>
    <div class="message"><%= message.last.last.html_safe %></div>
  <% end %>
<% end %>

Returns

"Email is required."

The localization method is definitely the "proper" way to do this, but if you're doing a little, non-global project and want to just get going fast - this is definitely easier than file hopping.

I like it for the ability to put the field name somewhere other than the beginning of the string:

validates_uniqueness_of :email, :message => "There is already an account with that email."

Find non-ASCII characters in varchar columns using SQL Server

This script searches for non-ascii characters in one column. It generates a string of all valid characters, here code point 32 to 127. Then it searches for rows that don't match the list:

declare @str varchar(128)
declare @i int
set @str = ''
set @i = 32
while @i <= 127
    begin
    set @str = @str + '|' + char(@i)
    set @i = @i + 1
    end

select  col1
from    YourTable
where   col1 like '%[^' + @str + ']%' escape '|'

how to use LIKE with column name

ORACLE DATABASE example:

select * 
from table1 t1, table2 t2
WHERE t1.a like ('%' || t2.b || '%')

In Postgresql, force unique on combination of two columns

CREATE TABLE someTable (
    id serial PRIMARY KEY,
    col1 int NOT NULL,
    col2 int NOT NULL,
    UNIQUE (col1, col2)
)

autoincrement is not postgresql. You want a serial.

If col1 and col2 make a unique and can't be null then they make a good primary key:

CREATE TABLE someTable (
    col1 int NOT NULL,
    col2 int NOT NULL,
    PRIMARY KEY (col1, col2)
)

Java generics - ArrayList initialization

You have strange expectations. If you gave the chain of arguments that led you to them, we might spot the flaw in them. As it is, I can only give a short primer on generics, hoping to touch on the points you might have misunderstood.

ArrayList<? extends Object> is an ArrayList whose type parameter is known to be Object or a subtype thereof. (Yes, extends in type bounds has a meaning other than direct subclass). Since only reference types can be type parameters, this is actually equivalent to ArrayList<?>.

That is, you can put an ArrayList<String> into a variable declared with ArrayList<?>. That's why a1.add(3) is a compile time error. a1's declared type permits a1 to be an ArrayList<String>, to which no Integer can be added.

Clearly, an ArrayList<?> is not very useful, as you can only insert null into it. That might be why the Java Spec forbids it:

It is a compile-time error if any of the type arguments used in a class instance creation expression are wildcard type arguments

ArrayList<ArrayList<?>> in contrast is a functional data type. You can add all kinds of ArrayLists into it, and retrieve them. And since ArrayList<?> only contains but is not a wildcard type, the above rule does not apply.

Changing cursor to waiting in javascript/jquery

If it saves too fast, try this:

<style media="screen" type="text/css">
    .autosave {display: inline; padding: 0 10px; color:green; font-weight: 400; font-style: italic;}
</style>

<input type="button" value="Save" onclick="save();" />&nbsp;
<span class="autosave" style="display: none;">Saved Successfully</span>


$('span.autosave').fadeIn("80");
$('span.autosave').delay("400");
$('span.autosave').fadeOut("80");

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

Disabling automatic and then re-enabling has solved this for me in Xcode 8 GM seed. This can be done in the project settings, info tab for each target that needs to be signed.

How to dismiss a Twitter Bootstrap popover by clicking outside?

Try this, this will hide by clicking outside.

$('body').on('click', function (e) {
    $('[data-toggle="popover"]').each(function () {
    //the 'is' for buttons that trigger popups
    //the 'has' for icons within a button that triggers a popup
    if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
    $(this).popover('hide');
    }
    });
});

"could not find stored procedure"

I had:

USE [wrong_place]

GO

before

DECLARE..

Getting the textarea value of a ckeditor textarea with javascript

Simply execute

CKEDITOR.instances[elementId].getData();

with element id = id of element assigned the editor.

How to iterate a table rows with JQuery and access some cell values?

$("tr.item").each(function() {
  $this = $(this);
  var value = $this.find("span.value").html();
  var quantity = $this.find("input.quantity").val();
});

How to set up fixed width for <td>?

None of this work for me, and have many cols on datatable to make % or sm class equals to 12 elements layout on bootstrap.

I was working with datatables Angular 5 and Bootstrap 4, and have many cols in table. The solution for me was in the TH to add a DIV element with a specific width. For example for the cols "Person Name" and "Event date" I need a specific width, then put a div in the col header, the entire col width then resizes to the width specified from the div on the TH:

<table datatable [dtOptions]="dtOptions" *ngIf="listData" class="table table-hover table-sm table-bordered text-center display" width="100%">
    <thead class="thead-dark">
        <tr>
            <th scope="col">ID </th>
            <th scope="col">Value</th>
            <th scope="col"><div style="width: 600px;">Person Name</div></th>
            <th scope="col"><div style="width: 800px;">Event date</div></th> ...

How can I get the intersection, union, and subset of arrays in Ruby?

If Multiset extends from the Array class

x = [1, 1, 2, 4, 7]
y = [1, 2, 2, 2]
z = [1, 1, 3, 7]

UNION

x.union(y)           # => [1, 2, 4, 7]      (ONLY IN RUBY 2.6)
x.union(y, z)        # => [1, 2, 4, 7, 3]   (ONLY IN RUBY 2.6)
x | y                # => [1, 2, 4, 7]

DIFFERENCE

x.difference(y)      # => [4, 7] (ONLY IN RUBY 2.6)
x.difference(y, z)   # => [4] (ONLY IN RUBY 2.6)
x - y                # => [4, 7]

INTERSECTION

x & y                # => [1, 2]

For more info about the new methods in Ruby 2.6, you can check this blog post about its new features

What is the difference between origin and upstream on GitHub?

In a nutshell answer.

  • origin: the fork
  • upstream: the forked

InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

If you are still recieving the InvalidKeyException when running my AES encryption program with 256 bit keys, but not with 128 bit keys, it is because you have not installed the new policy JAR files correctly, and has nothing to do with BouncyCastle (which is also restrained by those policy files). Try uninstalling, then re-installing java and then replaceing the old jar's with the new unlimited strength ones. Other than that, I'm out of ideas, best of luck.

You can see the policy files themselves if you open up the lib/security/local_policy.jar and US_export_policy.jar files in winzip and look at the conatined *.policy files in notepad and make sure they look like this:

default_local.policy:

    // Country-specific policy file for countries with no limits on crypto strength.
grant {
    // There is no restriction to any algorithms.
    permission javax.crypto.CryptoAllPermission; 
};

default_US_export.policy:

// Manufacturing policy file.
grant {
    // There is no restriction to any algorithms.
    permission javax.crypto.CryptoAllPermission; 
};

How to Identify Microsoft Edge browser via CSS?

/* Microsoft Edge Browser 12-18 (All versions before Chromium) - one-liner method */

_:-ms-lang(x), _:-webkit-full-screen, .selector { property:value; }

That works great!

// for instance:
_:-ms-lang(x), _:-webkit-full-screen, .headerClass 
{ 
  border: 1px solid brown;
}

https://jeffclayton.wordpress.com/2015/04/07/css-hacks-for-windows-10-and-spartan-browser-preview/

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

Your port 80 is being used by the system.

  1. In Windows “World Wide Publishing" Service is using this port and it's process is system which PID is 4 maximum time and stopping this service(“World Wide Publishing") will free the port 80 and you can connect Apache using this port. To stop the service go to the “Task manager –> Services tab”, right click the “World Wide Publishing Service” and stop.
  2. If you don't find there then Then go to "Run > services.msc" and again find there and right click the “World Wide Publishing Service” and stop.
  3. If you didn't find “World Wide Publishing Service” there then go to "Run>>resmon.exe>> Network Tab>>Listening Ports" and see which process is using port 80

enter image description here

And from "Overview>>CPU" just Right click on that process and click "End Process Tree". If that process is system that might be a critical issue.

Localhost not working in chrome and firefox

You need to disable Script Debugging In Visual Studio

Including an anchor tag in an ASP.NET MVC Html.ActionLink

I Did that and it works for redirecting to other view I think If you add the #sectionLink after It will work

<a class="btn yellow" href="/users/Create/@Model.Id" target="_blank">
                                        Add As User
                                    </a>

Storing image in database directly or as base64 data?

I contend that images (files) are NOT usually stored in a database base64 encoded. Instead, they are stored in their raw binary form in a binary (blob) column (or file).

Base64 is only used as a transport mechanism, not for storage. For example, you can embed a base64 encoded image into an XML document or an email message.

Base64 is also stream friendly. You can encode and decode on the fly (without knowing the total size of the data).

While base64 is fine for transport, do not store your images base64 encoded.

Base64 provides no checksum or anything of any value for storage.

Base64 encoding increases the storage requirement by 33% over a raw binary format. It also increases the amount of data that must be read from persistent storage, which is still generally the largest bottleneck in computing. It's generally faster to read less bytes and encode them on the fly. Only if your system is CPU bound instead of IO bound, and you're regularly outputting the image in base64, then consider storing in base64.

Inline images (base64 encoded images embedded in HTML) are a bottleneck themselves--you're sending 33% more data over the wire, and doing it serially (the web browser has to wait on the inline images before it can finish downloading the page HTML).

If you still wish to store images base64 encoded, please, whatever you do, make sure you don't store base64 encoded data in a UTF8 column then index it.

cout is not a member of std

I had a similar issue and it turned out that i had to add an extra entry in cmake to include the files.

Since i was also using the zmq library I had to add this to the included libraries as well.

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

Remove element should clear out such errors. The reason behind this is the inherited settings. Your application will inherit some settings from its parent's config file and machine's (server) config files.
You can either remove such duplicates with the remove tag before adding them or make these tags non-inheritable in the upper level config files.

EF Core add-migration Build Failed

I got the same error. There were no errors during the build proccess. I closed the Visual Studio and it worked.

Copy a file from one folder to another using vbscripting

Please find the below code:

If ComboBox21.Value = "Delimited file" Then
    'Const txtFldrPath As String = "C:\Users\513090.CTS\Desktop\MACRO"      'Change to folder path containing text files
    Dim myValue2 As String
    myValue2 = ComboBox22.Value
    Dim txtFldrPath As Variant
    txtFldrPath = InputBox("Give the file path")
    'Dim CurrentFile As String: CurrentFile = Dir(txtFldrPath & "\" & "LL.txt")
    Dim strLine() As String
    Dim LineIndex As Long
    Dim myValue As Variant
    On Error GoTo Errhandler
    myValue = InputBox("Give the DELIMITER")

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    While txtFldrPath <> vbNullString
        LineIndex = 0
        Close #1
        'Open txtFldrPath & "\" & CurrentFile For Input As #1
        Open txtFldrPath For Input As #1
        While Not EOF(1)
            LineIndex = LineIndex + 1
            ReDim Preserve strLine(1 To LineIndex)
            Line Input #1, strLine(LineIndex)
        Wend
        Close #1

        With ActiveWorkbook.Sheets(myValue2).Range("A1").Resize(LineIndex, 1)
            .Value = WorksheetFunction.Transpose(strLine)
            .TextToColumns Other:=True, OtherChar:=myValue
        End With

        'ActiveSheet.UsedRange.EntireColumn.AutoFit
        'ActiveSheet.Copy
        'ActiveWorkbook.SaveAs xlsFldrPath & "\" & Replace(CurrentFile, ".txt", ".xls"), xlNormal
        'ActiveWorkbook.Close False
       ' ActiveSheet.UsedRange.ClearContents

        CurrentFile = Dir
    Wend
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True

End If

Replace all 0 values to NA

#Sample data
set.seed(1)
dat <- data.frame(x = sample(0:2, 5, TRUE), y = sample(0:2, 5, TRUE))
#-----
  x y
1 0 2
2 1 2
3 1 1
4 2 1
5 0 0

#replace zeros with NA
dat[dat==0] <- NA
#-----
   x  y
1 NA  2
2  1  2
3  1  1
4  2  1
5 NA NA

How to select a value in dropdown javascript?

This may do it

document.forms['someform'].elements['someelement'].value

Jquery Setting Value of Input Field

Put your jQuery function in

$(document).ready(function(){

});

It's surely solved.

JavaScript Loading Screen while page loads

If in your site you have ajax calls loading some data, and this is the reason the page is loading slow, the best solution I found is with

$(document).ajaxStop(function(){
    alert("All AJAX requests completed");
});

https://jsfiddle.net/44t5a8zm/ - here you can add some ajax calls and test it.

json_encode/json_decode - returns stdClass instead of Array in PHP

tl;dr: JavaScript doesn't support associative arrays, therefore neither does JSON.

After all, it's JSON, not JSAAN. :)

So PHP has to convert your array into an object in order to encode into JSON.

Import an existing git project into GitLab?

I was able to fully export my project along with all commits, branches and tags to gitlab via following commands run locally on my computer:

To illustrate my example, I will be using https://github.com/raveren/kint as the source repository that I want to import into gitlab. I created an empty project named Kint (under namespace raveren) in gitlab beforehand and it told me the http git url of the newly created project there is http://gitlab.example.com/raveren/kint.git

The commands are OS agnostic.

In a new directory:

git clone --mirror https://github.com/raveren/kint
cd kint.git
git remote add gitlab http://gitlab.example.com/raveren/kint.git
git push gitlab --mirror

Now if you have a locally cloned repository that you want to keep using with the new remote, just run the following commands* there:

git remote remove origin
git remote add origin http://gitlab.example.com/raveren/kint.git
git fetch --all

*This assumes that you did not rename your remote master from origin, otherwise, change the first two lines to reflect it.

ImportError: No module named model_selection

do you have sklearn? if not, do the following:

sudo pip install sklearn

After installing sklearn

from sklearn.model_selection import train_test_split

works fine

How to rename HTML "browse" button of an input type=file?

Here is the best, simple, short and clean way to "rename" the text of an input with file type and without JQuery, with pure HTML and javascript:

<input id='browse' type='file' style='width:0px'>
<button id='browser' onclick='browse.click()'>
    *The text you want*
</button>

What is the difference between RTP or RTSP in a streaming server?

AFAIK, RTSP does not transmit streams at all, it is just an out-of-band control protocol with functions like PLAY and STOP.

Raw UDP or RTP over UDP are transmission protocols for streams just like raw TCP or HTTP over TCP.

To be able to stream a certain program over the given transmission protocol, an encapsulation method has to be defined for your container format. For example TS container can be transmitted over UDP but Matroska can not.

Pretty much everything can be transported through TCP though.

(The fact that which codec do you use also matters indirectly as it restricts the container formats you can use.)

Render basic HTML view?

If you're using express@~3.0.0 change the line below from your example:

app.use(express.staticProvider(__dirname + '/public'));

to something like this:

app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));

I made it as described on express api page and it works like charm. With that setup you don't have to write additional code so it becomes easy enough to use for your micro production or testing.

Full code listed below:

var express = require('express');
var app = express.createServer();

app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
    res.render('index.html');
});

app.listen(8080, '127.0.0.1')

How to highlight cell if value duplicate in same column for google spreadsheet?

While zolley's answer is perfectly right for the question, here's a more general solution for any range, plus explanation:

    =COUNTIF($A$1:$C$50, INDIRECT(ADDRESS(ROW(), COLUMN(), 4))) > 1

Please note that in this example I will be using the range A1:C50. The first parameter ($A$1:$C$50) should be replaced with the range on which you would like to highlight duplicates!


to highlight duplicates:

  1. Select the whole range on which the duplicate marking is wanted.
  2. On the menu: Format > Conditional formatting...
  3. Under Apply to range, select the range to which the rule should be applied.
  4. In Format cells if, select Custom formula is on the dropdown.
  5. In the textbox insert the given formula, adjusting the range to match step (3).

Why does it work?

COUNTIF(range, criterion), will compare every cell in range to the criterion, which is processed similarly to formulas. If no special operators are provided, it will compare every cell in the range with the given cell, and return the number of cells found to be matching the rule (in this case, the comparison). We are using a fixed range (with $ signs) so that we always view the full range.

The second block, INDIRECT(ADDRESS(ROW(), COLUMN(), 4)), will return current cell's content. If this was placed inside the cell, docs will have cried about circular dependency, but in this case, the formula is evaluated as if it was in the cell, without changing it.

ROW() and COLUMN() will return the row number and column number of the given cell respectively. If no parameter is provided, the current cell will be returned (this is 1-based, for example, B3 will return 3 for ROW(), and 2 for COLUMN()).

Then we use: ADDRESS(row, column, [absolute_relative_mode]) to translate the numeric row and column to a cell reference (like B3. Remember, while we are inside the cell's context, we don't know it's address OR content, and we need the content in order to compare with). The third parameter takes care for the formatting, and 4 returns the formatting INDIRECT() likes.

INDIRECT(), will take a cell reference and return its content. In this case, the current cell's content. Then back to the start, COUNTIF() will test every cell in the range against ours, and return the count.

The last step is making our formula return a boolean, by making it a logical expression: COUNTIF(...) > 1. The > 1 is used because we know there's at least one cell identical to ours. That's our cell, which is in the range, and thus will be compared to itself. So to indicate a duplicate, we need to find 2 or more cells matching ours.


Sources:

Hidden Features of C#?

Conditional string.Format:

Applies different formatting to a number depending on whether the number is positive, negative, or zero.

string s = string.Format("{0:positive;negative;zero}", i);

e.g.

string format = "000;-#;(0)";

string pos = 1.ToString(format);     // 001
string neg = (-1).ToString(format);  // -1
string zer = 0.ToString(format);     // (0)

Check if an element is a child of a parent

You can get your code to work by just swapping the two terms:

if ($(target).parents('div#hello').length) {

You had the child and parent round the wrong way.

A regex for version number parsing

Sometimes version numbers might contain alphanumeric minor information (e.g. 1.2.0b or 1.2.0-beta). In this case I am using this regex:

([0-9]{1,4}(\.[0-9a-z]{1,6}){1,5})

What Ruby IDE do you prefer?

RubyMine from JetBrains. (Also available as a plugin to IntelliJ IDEA)

how can I check if a file exists?

an existing folder will FAIL with FileExists

Function FileExists(strFileName)
' Check if a file exists - returns True or False

use instead or in addition:

Function FolderExists(strFolderPath)
' Check if a path exists

How to set a reminder in Android?

You can use AlarmManager in coop with notification mechanism Something like this:

Intent intent = new Intent(ctx, ReminderBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE);
// time of of next reminder. Unix time.
long timeMs =...
if (Build.VERSION.SDK_INT < 19) {
    am.set(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
} else {
    am.setExact(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
}

It starts alarm.

public class ReminderBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setSmallIcon(...)
                .setContentTitle(..)
                .setContentText(..);
        Intent intentToFire = new Intent(context, Activity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentToFire, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
        NotificationManagerCompat.from(this);.notify((int) System.currentTimeMillis(), builder.build());
    }
}

Undoing accidental git stash pop

From git stash --help

Recovering stashes that were cleared/dropped erroneously
   If you mistakenly drop or clear stashes, they cannot be recovered through the normal safety mechanisms. However, you can try the
   following incantation to get a list of stashes that are still in your repository, but not reachable any more:

       git fsck --unreachable |
       grep commit | cut -d\  -f3 |
       xargs git log --merges --no-walk --grep=WIP

This helped me better than the accepted answer with the same scenario.

What's the purpose of META-INF?

The META-INF folder is the home for the MANIFEST.MF file. This file contains meta data about the contents of the JAR. For example, there is an entry called Main-Class that specifies the name of the Java class with the static main() for executable JAR files.

How to position two elements side by side using CSS

You have two options, either float:left or display:inline-block.

Both methods have their caveats. It seems that display:inline-block is more common nowadays, as it avoids some of the issues of floating.

Read this article http://designshack.net/articles/css/whats-the-deal-with-display-inline-block/ or this one http://www.vanseodesign.com/css/inline-blocks/ for a more in detail discussion.

ASP.NET Button to redirect to another page

<button type ="button" onclick="location.href='@Url.Action("viewname","Controllername")'"> Button name</button>

for e.g ,

<button type="button" onclick="location.href='@Url.Action("register","Home")'">Register</button>

How to center text vertically with a large font-awesome icon?

I use icons next to text 99% of the time so I made the change globally:

.fa-2x {
  vertical-align: middle;
}

Add 3x, 4x, etc to the same definition as needed.

how to pass this element to javascript onclick function and add a class to that clicked element

Try like

<script>
function Data(string)
{      
  $('.filter').removeClass('active');
  $(this).parent('.filter').addClass('active') ;
} 
</script>

For the class selector you need to use . before the classname.And you need to add the class for the parent. Bec you are clicking on anchor tag not the filter.

null check in jsf expression language

Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"

If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"

Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"

How to render an array of objects in React?

https://facebook.github.io/react/docs/jsx-in-depth.html#javascript-expressions

You can pass any JavaScript expression as children, by enclosing it within {}. For example, these expressions are equivalent:

<MyComponent>foo</MyComponent>

<MyComponent>{'foo'}</MyComponent>

This is often useful for rendering a list of JSX expressions of arbitrary length. For example, this renders an HTML list:

function Item(props) {
  return <li>{props.message}</li>;
}

function TodoList() {
  const todos = ['finish doc', 'submit pr', 'nag dan to review'];
  return (
    <ul>
      {todos.map((message) => <Item key={message} message={message} />)}
    </ul>
  );
}

_x000D_
_x000D_
class First extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.state = {_x000D_
      data: [{name: 'bob'}, {name: 'chris'}],_x000D_
    };_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    return (_x000D_
      <ul>_x000D_
        {this.state.data.map(d => <li key={d.name}>{d.name}</li>)}_x000D_
      </ul>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <First />,_x000D_
  document.getElementById('root')_x000D_
);_x000D_
  
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

Get a list of checked checkboxes in a div using jQuery

I needed the count of all checkboxes which are checked. Instead of writing a loop i did this

$(".myCheckBoxClass:checked").length;

Compare it with the total number of checkboxes to see if they are equal. Hope it will help someone

Add Whatsapp function to website, like sms, tel

Rahul's answer gives me an error: You seem to be trying to send a WhatsApp message to a phone number that is not registered with WhatsApp..., even though I'm sending it to a registered WhatsApp number.

This, however works:

<li><a href="intent:0123456789#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end"><i class="fa fa-whatsapp"></i>+237 655 421 621</li>

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

As the error in code in conf file may vary (@Jacky Nguyen vs @H?NÐR? N???? answers),
the general solution answer would be to
a) correct the condition logic in conf file to make sense
(x)or b) install corrected/current phpmyadmin

As for a)

  1. open the file with error code
    For the terminal people: sudo nano /usr/share/phpmyadmin/libraries/sql.lib.php
    For the regular folks: sudo gedit /usr/share/phpmyadmin/libraries/sql.lib.php

  2. find the condition - basically search for $analyzed_sql_results['select_expr']

  3. now the logic should be to check whether this sub array is empty, or, whether it has just 1 element with a value "*

  4. so basically the block
    between && $analyzed_sql_results['select_from']
    and && count($analyzed_sql_results['select_tables']) == 1
    should look something like this

&& (
    empty($analyzed_sql_results['select_expr']) //the sub array is empty,
    || //or,
    (
        (count($analyzed_sql_results['select_expr']) == 1) //it has just 1 element
        && //and at the same time
        ($analyzed_sql_results['select_expr'][0] == '*') //the 1 element value is "*"
    )
)

This is a good example of why to indent and beautify your code, if it would be indeted correctly, I believe this would never happen, or at least, would be more easily found.

Maven: How to rename the war file for the project?

You can follow the below step to modify the .war file name if you are using maven project.

Open pom.xml file of your maven project and go to the tag <build></build>,

  1. In that give your desired name between this tag : <finalName></finalName>.

    ex. : <finalName>krutik</finalName>

    After deploying this .war you will be able to access url with:
    http://localhost:8080/krutik/

  2. If you want to access the url with slash '/' then you will have to specify then name as below:

    e.x. : <finalName>krutik#maheta</finalName>

    After deploying this .war you will be able to access url with:
    http://localhost:8080/krutik/maheta

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

I have finally figured out why this is happening !

In visual studio 2015, stdin, stderr, stdout are defined as follow :

#define stdin  (__acrt_iob_func(0))
#define stdout (__acrt_iob_func(1))
#define stderr (__acrt_iob_func(2))

But previously, they were defined as:

#define stdin  (&__iob_func()[0])
#define stdout (&__iob_func()[1])
#define stderr (&__iob_func()[2])

So now __iob_func is not defined anymore which leads to a link error when using a .lib file compiled with previous versions of visual studio.

To solve the issue, you can try defining __iob_func() yourself which should return an array containing {*stdin,*stdout,*stderr}.

Regarding the other link errors about stdio functions (in my case it was sprintf()), you can add legacy_stdio_definitions.lib to your linker options.

Why do I get a warning icon when I add a reference to an MEF plugin project?

I had these icons for a different reason. We have one big solution for all our projects (nearly 100). I made a subselection of the projects I was interested in and made a new solution. However the references where project references instead of references to the compiled dll's....

After some research I found this link on GitHub which explains this is new behaviour in VS2015.

On the GitHub page they explain a workaround for converting project references to binary references.

Launch a shell command with in a python script, wait for the termination and return to the script

use spawn

import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')

Detect when an image fails to load in Javascript

This:

<img onerror="this.src='/images/image.png'" src="...">

Best way to parse RSS/Atom feeds with PHP

If feed isn't well-formed XML, you're supposed to reject it, no exceptions. You're entitled to call feed creator a bozo.

Otherwise you're paving way to mess that HTML ended up in.

How to get a barplot with several variables side by side grouped by a factor

You can plot the means without resorting to external calculations and additional tables using stat_summary(...). In fact, stat_summary(...) was designed for exactly what you are doing.

library(ggplot2)
library(reshape2)            # for melt(...)
gg <- melt(df,id="gender")   # df is your original table
ggplot(gg, aes(x=variable, y=value, fill=factor(gender))) + 
  stat_summary(fun.y=mean, geom="bar",position=position_dodge(1)) + 
  scale_color_discrete("Gender")
  stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
               color="grey80",position=position_dodge(1), width=.2)

To add "error bars" you cna also use stat_summary(...) (here, I'm using the min and max value rather than sd because you have so little data).

ggplot(gg, aes(x=variable, y=value, fill=factor(gender))) + 
  stat_summary(fun.y=mean, geom="bar",position=position_dodge(1)) + 
  stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
               color="grey40",position=position_dodge(1), width=.2) +
  scale_fill_discrete("Gender")

How do I terminate a thread in C++11?

Tips of using OS-dependent function to terminate C++ thread:

  1. std::thread::native_handle() only can get the thread’s valid native handle type before calling join() or detach(). After that, native_handle() returns 0 - pthread_cancel() will coredump.

  2. To effectively call native thread termination function(e.g. pthread_cancel()), you need to save the native handle before calling std::thread::join() or std::thread::detach(). So that your native terminator always has a valid native handle to use.

More explanations please refer to: http://bo-yang.github.io/2017/11/19/cpp-kill-detached-thread .

How to create a static library with g++?

You can create a .a file using the ar utility, like so:

ar crf lib/libHeader.a header.o

lib is a directory that contains all your libraries. it is good practice to organise your code this way and separate the code and the object files. Having everything in one directory generally looks ugly. The above line creates libHeader.a in the directory lib. So, in your current directory, do:

mkdir lib

Then run the above ar command.

When linking all libraries, you can do it like so:

g++ test.o -L./lib -lHeader -o test  

The -L flag will get g++ to add the lib/ directory to the path. This way, g++ knows what directory to search when looking for libHeader. -llibHeader flags the specific library to link.

where test.o is created like so:

g++ -c test.cpp -o test.o 

background:none vs background:transparent what is the difference?

To complement the other answers: if you want to reset all background properties to their initial value (which includes background-color: transparent and background-image: none) without explicitly specifying any value such as transparent or none, you can do so by writing:

background: initial;

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

Simple is that

Like:

DECLARE @DUENO BIGINT
SET @DUENO=5

SELECT 'ND'+STUFF('000000',6-LEN(RTRIM(@DueNo))+1,LEN(RTRIM(@DueNo)),RTRIM(@DueNo)) DUENO

Python Loop: List Index Out of Range

When you call for i in a:, you are getting the actual elements, not the indexes. When we reach the last element, that is 3, b.append(a[i+1]-a[i]) looks for a[4], doesn't find one and then fails. Instead, try iterating over the indexes while stopping just short of the last one, like

for i in range(0, len(a)-1): Do something

Your current code won't work yet for the do something part though ;)

How do I force make/GCC to show me the commands?

Since GNU Make version 4.0, the --trace argument is a nice way to tell what and why a makefile do, outputing lines like:

makefile:8: target 'foo.o' does not exist

or

makefile:12: update target 'foo' due to: bar

The total number of locks exceeds the lock table size

First, you can use sql command show global variables like 'innodb_buffer%'; to check the buffer size.

Solution is find your my.cnf file and add,

_x000D_
_x000D_
[mysqld]_x000D_
innodb_buffer_pool_size=1G # depends on your data and machine
_x000D_
_x000D_
_x000D_

DO NOT forget to add [mysqld], otherwise, it won't work.

In my case, ubuntu 16.04, my.cnf is located under the folder /etc/mysql/.

How to add local .jar file dependency to build.gradle file?

According to the documentation, use a relative path for a local jar dependency as follows:

dependencies {
    implementation files('libs/something_local.jar')
}

Manipulate a url string by adding GET parameters

Basic method

$query = parse_url($url, PHP_URL_QUERY);

// Returns a string if the URL has parameters or NULL if not
if ($query) {
    $url .= '&category=1';
} else {
    $url .= '?category=1';
}

More advanced

$url = 'http://example.com/search?keyword=test&category=1&tags[]=fun&tags[]=great';

$url_parts = parse_url($url);
// If URL doesn't have a query string.
if (isset($url_parts['query'])) { // Avoid 'Undefined index: query'
    parse_str($url_parts['query'], $params);
} else {
    $params = array();
}

$params['category'] = 2;     // Overwrite if exists
$params['tags'][] = 'cool';  // Allows multiple values

// Note that this will url_encode all values
$url_parts['query'] = http_build_query($params);

// If you have pecl_http
echo http_build_url($url_parts);

// If not
echo $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'] . '?' . $url_parts['query'];

You should put this in a function at least, if not a class.

String "true" and "false" to boolean

You can use wannabe_bool gem. https://github.com/prodis/wannabe_bool

This gem implements a #to_b method for String, Integer, Symbol and NilClass classes.

params[:internal].to_b

How do I tell Gradle to use specific JDK version?

I added this line in my GRADLE_HOME/bin/gradle file - export JAVA_HOME=/path/to/java/version

How to know if an object has an attribute in Python

You can check whether object contains attribute by using hasattr builtin method.

For an instance if your object is a and you want to check for attribute stuff

>>> class a:
...     stuff = "something"
... 
>>> hasattr(a,'stuff')
True
>>> hasattr(a,'other_stuff')
False

The method signature itself is hasattr(object, name) -> bool which mean if object has attribute which is passed to second argument in hasattr than it gives boolean True or False according to the presence of name attribute in object.

How to downgrade Xcode to previous version?

When you log in to your developer account, you can find a link at the bottom of the download section for Xcode that says "Looking for an older version of Xcode?". In there you can find download links to older versions of Xcode and other developer tools

HTTPS using Jersey Client

If you are using Java 8, a shorter version for Jersey2 than the answer provided by Aleksandr.

SSLContext sslContext = null;
try {
  sslContext = SSLContext.getInstance("SSL");
  // Create a new X509TrustManager
  sslContext.init(null, getTrustManager(), null);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
  throw e;
}
final Client client = ClientBuilder.newBuilder().hostnameVerifier((s, session) -> true)
  .sslContext(sslContext).build();
return client;

private TrustManager[] getTrustManager() {
  return new TrustManager[] {
    new X509TrustManager() {
      @Override
      public X509Certificate[] getAcceptedIssuers() {
        return null;
      }
      @Override
      public void checkServerTrusted(X509Certificate[] chain, String authType)
      throws CertificateException {
      }
      @Override
      public void checkClientTrusted(X509Certificate[] chain, String authType)
      throws CertificateException {
      }
    }
  };
}

Add a row number to result set of a SQL query

So before MySQL 8.0 there is no ROW_NUMBER() function. Accpted answer rewritten to support older versions of MySQL:

SET @row_number = 0;
SELECT t.A, t.B, t.C, (@row_number:=@row_number + 1) AS number
FROM dbo.tableZ AS t ORDER BY t.A;

How to evaluate http response codes from bash/shell script?

Although the accepted response is a good answer, it overlooks failure scenarios. curl will return 000 if there is an error in the request or there is a connection failure.

url='http://localhost:8080/'
status=$(curl --head --location --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${url})
[[ $status == 500 ]] || [[ $status == 000 ]] && echo restarting ${url} # do start/restart logic

Note: this goes a little beyond the requested 500 status check to also confirm that curl can even connect to the server (i.e. returns 000).

Create a function from it:

failureCode() {
    local url=${1:-http://localhost:8080}
    local code=${2:-500}
    local status=$(curl --head --location --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${url})
    [[ $status == ${code} ]] || [[ $status == 000 ]]
}

Test getting a 500:

failureCode http://httpbin.org/status/500 && echo need to restart

Test getting error/connection failure (i.e. 000):

failureCode http://localhost:77777 && echo need to start

Test not getting a 500:

failureCode http://httpbin.org/status/400 || echo not a failure

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

File sutest

#!/bin/bash
echo "uid is ${UID}"
echo "user is ${USER}"
echo "username is ${USERNAME}"

run it: `./sutest' gives me

uid is 500
user is stephenp
username is stephenp

but using sudo: sudo ./sutest gives

uid is 0
user is root
username is stephenp

So you retain the original user name in $USERNAME when running as sudo. This leads to a solution similar to what others posted:

#!/bin/bash
sudo -u ${USERNAME} normal_command_1
root_command_1
root_command_2
sudo -u ${USERNAME} normal_command_2
# etc.

Just sudo to invoke your script in the first place, it will prompt for the password once.


I originally wrote this answer on Linux, which does have some differences with OS X

OS X (I'm testing this on Mountain Lion 10.8.3) has an environment variable SUDO_USER when you're running sudo, which can be used in place of USERNAME above, or to be more cross-platform the script could check to see if SUDO_USER is set and use it if so, or use USERNAME if that's set.

Changing the original script for OS X, it becomes...

#!/bin/bash
sudo -u ${SUDO_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${SUDO_USER} normal_command_2
# etc.

A first stab at making it cross-platform could be...

#!/bin/bash
#
# set "THE_USER" to SUDO_USER if that's set,
#  else set it to USERNAME if THAT is set,
#   else set it to the string "unknown"
# should probably then test to see if it's "unknown"
#
THE_USER=${SUDO_USER:-${USERNAME:-unknown}}

sudo -u ${THE_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${THE_USER} normal_command_2
# etc.

Dynamic tabs with user-click chosen components

update

Angular 5 StackBlitz example

update

ngComponentOutlet was added to 4.0.0-beta.3

update

There is a NgComponentOutlet work in progress that does something similar https://github.com/angular/angular/pull/11235

RC.7

Plunker example RC.7

// Helper component to add dynamic components
@Component({
  selector: 'dcl-wrapper',
  template: `<div #target></div>`
})
export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef;
  @Input() type: Type<Component>;
  cmpRef: ComponentRef<Component>;
  private isViewInitialized:boolean = false;

  constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler) {}

  updateComponent() {
    if(!this.isViewInitialized) {
      return;
    }
    if(this.cmpRef) {
      // when the `type` input changes we destroy a previously 
      // created component before creating the new one
      this.cmpRef.destroy();
    }

    let factory = this.componentFactoryResolver.resolveComponentFactory(this.type);
    this.cmpRef = this.target.createComponent(factory)
    // to access the created instance use
    // this.compRef.instance.someProperty = 'someValue';
    // this.compRef.instance.someOutput.subscribe(val => doSomething());
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();  
  }

  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }    
  }
}

Usage example

// Use dcl-wrapper component
@Component({
  selector: 'my-tabs',
  template: `
  <h2>Tabs</h2>
  <div *ngFor="let tab of tabs">
    <dcl-wrapper [type]="tab"></dcl-wrapper>
  </div>
`
})
export class Tabs {
  @Input() tabs;
}
@Component({
  selector: 'my-app',
  template: `
  <h2>Hello {{name}}</h2>
  <my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
  // The list of components to create tabs from
  types = [C3, C1, C2, C3, C3, C1, C1];
}
@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, DclWrapper, Tabs, C1, C2, C3],
  entryComponents: [C1, C2, C3],
  bootstrap: [ App ]
})
export class AppModule {}

See also angular.io DYNAMIC COMPONENT LOADER

older versions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

This changed again in Angular2 RC.5

I will update the example below but it's the last day before vacation.

This Plunker example demonstrates how to dynamically create components in RC.5

Update - use ViewContainerRef.createComponent()

Because DynamicComponentLoader is deprecated, the approach needs to be update again.

@Component({
  selector: 'dcl-wrapper',
  template: `<div #target></div>`
})
export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target;
  @Input() type;
  cmpRef:ComponentRef;
  private isViewInitialized:boolean = false;

  constructor(private resolver: ComponentResolver) {}

  updateComponent() {
    if(!this.isViewInitialized) {
      return;
    }
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }
   this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
      this.cmpRef = this.target.createComponent(factory)
      // to access the created instance use
      // this.compRef.instance.someProperty = 'someValue';
      // this.compRef.instance.someOutput.subscribe(val => doSomething());
    });
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();  
  }

  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }    
  }
}

Plunker example RC.4
Plunker example beta.17

Update - use loadNextToLocation

export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target;
  @Input() type;
  cmpRef:ComponentRef;
  private isViewInitialized:boolean = false;

  constructor(private dcl:DynamicComponentLoader) {}

  updateComponent() {
    // should be executed every time `type` changes but not before `ngAfterViewInit()` was called 
    // to have `target` initialized
    if(!this.isViewInitialized) {
      return;
    }
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }
    this.dcl.loadNextToLocation(this.type, this.target).then((cmpRef) => {
      this.cmpRef = cmpRef;
    });
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();  
  }

  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }    
  }
}

Plunker example beta.17

original

Not entirely sure from your question what your requirements are but I think this should do what you want.

The Tabs component gets an array of types passed and it creates "tabs" for each item in the array.

@Component({
  selector: 'dcl-wrapper',
  template: `<div #target></div>`
})
export class DclWrapper {
  constructor(private elRef:ElementRef, private dcl:DynamicComponentLoader) {}
  @Input() type;

  ngOnChanges() {
    if(this.cmpRef) {
      this.cmpRef.dispose();
    }
    this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
      this.cmpRef = cmpRef;
    });
  }
}

@Component({
  selector: 'c1',
  template: `<h2>c1</h2>`

})
export class C1 {
}

@Component({
  selector: 'c2',
  template: `<h2>c2</h2>`

})
export class C2 {
}

@Component({
  selector: 'c3',
  template: `<h2>c3</h2>`

})
export class C3 {
}

@Component({
  selector: 'my-tabs',
  directives: [DclWrapper],
  template: `
  <h2>Tabs</h2>
  <div *ngFor="let tab of tabs">
    <dcl-wrapper [type]="tab"></dcl-wrapper>
  </div>
`
})
export class Tabs {
  @Input() tabs;
}


@Component({
  selector: 'my-app',
  directives: [Tabs]
  template: `
  <h2>Hello {{name}}</h2>
  <my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
  types = [C3, C1, C2, C3, C3, C1, C1];
}

Plunker example beta.15 (not based on your Plunker)

There is also a way to pass data along that can be passed to the dynamically created component like (someData would need to be passed like type)

    this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
  cmpRef.instance.someProperty = someData;
  this.cmpRef = cmpRef;
});

There is also some support to use dependency injection with shared services.

For more details see https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

The dialog needs to be started only after the window states of the Activity are initialized This happens only after onresume.

So call

runOnUIthread(new Runnable(){

    showInfoMessageDialog("Please check your network connection","Network Alert");
});

in your OnResume function. Do not create dialogs in OnCreate
Edit:

use this

Handler h = new Handler();

h.postDelayed(new Runnable(){

        showInfoMessageDialog("Please check your network connection","Network Alert");
    },500);

in your Onresume instead of showonuithread

Parse Json string in C#

Instead of an arraylist or dictionary you can also use a dynamic. Most of the time I use EasyHttp for this, but sure there will by other projects that do the same. An example below:

var http = new HttpClient();
http.Request.Accept = HttpContentTypes.ApplicationJson;
var response = http.Get("url");
var body = response.DynamicBody;
Console.WriteLine("Name {0}", body.AppName.Description);
Console.WriteLine("Name {0}", body.AppName.Value);

On NuGet: EasyHttp

How do I revert my changes to a git submodule?

If there's changes in your submodules, then use

git submodule foreach --recursive git reset --hard

If your changes are remote submodule changes, then use

git submodule update --init

If these changes have been committed, then use

git reset --hard
git submodule update --init

Connecting to remote URL which requires authentication using Java

i did that this way you need to do this just copy paste it be happy

    HttpURLConnection urlConnection;
    String url;
 //   String data = json;
    String result = null;
    try {
        String username ="[email protected]";
        String password = "12345678";

        String auth =new String(username + ":" + password);
        byte[] data1 = auth.getBytes(UTF_8);
        String base64 = Base64.encodeToString(data1, Base64.NO_WRAP);
        //Connect
        urlConnection = (HttpURLConnection) ((new URL(urlBasePath).openConnection()));
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Authorization", "Basic "+base64);
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.setConnectTimeout(10000);
        urlConnection.connect();
        JSONObject obj = new JSONObject();

        obj.put("MobileNumber", "+97333746934");
        obj.put("EmailAddress", "[email protected]");
        obj.put("FirstName", "Danish");
        obj.put("LastName", "Hussain");
        obj.put("Country", "BH");
        obj.put("Language", "EN");
        String data = obj.toString();
        //Write
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(data);
        writer.close();
        outputStream.close();
        int responseCode=urlConnection.getResponseCode();
        if (responseCode == HttpsURLConnection.HTTP_OK) {
            //Read
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

        String line = null;
        StringBuilder sb = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }

        bufferedReader.close();
        result = sb.toString();

        }else {
        //    return new String("false : "+responseCode);
        new String("false : "+responseCode);
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }