Programs & Examples On #Fsockopen

PHP function used to open (Internet or Unix domain) sockets connections.

Socket transport "ssl" in PHP not enabled

Success!

After checking the log files and making sure the permissions on php_openssl.dll were correct, I googled the warning and found more things to try.

So I:

  • added C:\PHP\ext to the Windows path
  • added libeay32.dll and ssleay32.dll to C:\WINDOWS\system32\inetsrv
  • rebooted the server

I'm not sure which of these fixed my problem, but it's definately fixed now! :)

I found these things to try on this page: http://php.net/manual/en/install.windows.extensions.php

Thanks for your help!

php_network_getaddresses: getaddrinfo failed: Name or service not known

in simple word your site has been blocked to access network. may be you have automated some script and it caused your whole website to be blocked. the better way to resolve this is contact that site and tell your issue. if issue is genuine they may consider unblocking

How to check if a file exists from a url

I've just found this solution:

if(@getimagesize($remoteImageURL)){
    //image exists!
}else{
    //image does not exist.
}

Source: http://www.dreamincode.net/forums/topic/11197-checking-if-file-exists-on-remote-server/

selected value get from db into dropdown select box option using php mysql error

USING POD

<?php
$username = "root";
$password = "";
$db = "db_name";

$dns = "mysql:host=localhost;dbname=$db;charset=utf8mb4";
    $conn = new PDO($dns,$username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "select * from mine where username = ? ";

    $stmt1 = $conn->prepare($sql);
    $stmt1 -> execute(array($_POST['user']));
    $all = $stmt1->fetchAll(); ?>

    <div class="controls">
        <select  data-rel="chosen"  name="degree_id" id="selectError">

                 <?php foreach($all as $nt) { echo "<option value =$nt[id]>$nt[name]</option>";}?>
        </select>

    </div>

Can I have two JavaScript onclick events in one element?

You can attach a handler which would call as many others as you like:

<a href="#blah" id="myLink"/>

<script type="text/javascript">

function myOtherFunction() {
//do stuff...
}

document.getElementById( 'myLink' ).onclick = function() {
   //do stuff...
   myOtherFunction();
};

</script>

Using if elif fi in shell scripts

Change [ to [[, and ] to ]].

Application Installation Failed in Android Studio

Try disabling the Instant run in Settings.

Remove querystring from URL

If using backbone.js (which contains url anchor as route), url query string may appear:

  1. before url anchor:

    var url = 'http://example.com?a=1&b=3#routepath/subpath';
    
  2. after url anchor:

    var url = 'http://example.com#routepath/subpath?a=1&b=3';
    

Solution:

window.location.href.replace(window.location.search, '');
// run as: 'http://example.com#routepath/subpath?a=1&b=3'.replace('?a=1&b=3', '');

SVG gradient using CSS

Building on top of what Finesse wrote, here is a simpler way to target the svg and change it's gradient.

This is what you need to do:

  1. Assign classes to each color stop defined in the gradient element.
  2. Target the css and change the stop-color for each of those stops using plain classes.
  3. Win!

Some benefits of using classes instead of :nth-child is that it'll not be affected if you reorder your stops. Also, it makes the intent of each class clear - you'll be left wondering whether you needed a blue color on the first child or the second one.

I've tested it on all Chrome, Firefox and IE11:

_x000D_
_x000D_
.main-stop {_x000D_
  stop-color: red;_x000D_
}_x000D_
.alt-stop {_x000D_
  stop-color: green;_x000D_
}
_x000D_
<svg class="green" width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
  <linearGradient id="gradient">_x000D_
    <stop class="main-stop" offset="0%" />_x000D_
    <stop class="alt-stop" offset="100%" />_x000D_
  </linearGradient>_x000D_
  <rect width="100" height="50" fill="url(#gradient)" />_x000D_
</svg>
_x000D_
_x000D_
_x000D_

See an editable example here: https://jsbin.com/gabuvisuhe/edit?html,css,output

Cannot install signed apk to device manually, got error "App not installed"

File > Project Structure > Build Variants > Select release > Make sure 'Signing Config' is not empty > if it is select from the drop window the $signingConfigs.release

I did this with Android Studio 3.1.4 and it allowed me to create a release apk after following all the steps above of creating the release apk and release key and adding the info to the app gradle. Cheers!

How do I clear inner HTML

Take a look at this. a clean and simple solution using jQuery.

http://jsfiddle.net/ma2Yd/

    <h1 onmouseover="go('The dog is in its shed')" onmouseout="clear()">lalala</h1>
    <div id="goy"></div>


    <script type="text/javascript">

    $(function() {
       $("h1").on('mouseover', function() {
          $("#goy").text('The dog is in its shed');
       }).on('mouseout', function() {
          $("#goy").text("");
       });
   });

Windows command for file size only

Since you're using Windows XP, Windows PowerShell is an option.

(Get-Item filespec ).Length 

or as a function

function Get-FileLength { (Get-Item $args).Length }
Get-FileLength filespec

How do I use $scope.$watch and $scope.$apply in AngularJS?

There are $watchGroup and $watchCollection as well. Specifically, $watchGroup is really helpful if you want to call a function to update an object which has multiple properties in a view that is not dom object, for e.g. another view in canvas, WebGL or server request.

Here, the documentation link.

How can I get a JavaScript stack trace when I throw an exception?

I don't think there's anything built in that you can use however I did find lots of examples of people rolling their own.

Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration

When using VS2019, MVC5 - look under Migrations folder for file Configuration.cs Edit : AutomaticMigrationsEnabled = true

    -

ASP.NET Web API session or something?

You can use cookies if the data is small enough and does not present a security concern. The same HttpContext.Current based approach should work.

Request and response HTTP headers can also be used to pass information between service calls.

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

SQL Server : check if variable is Empty or NULL for WHERE clause

If you don't want to pass the parameter when you don't want to search, then you should make the parameter optional instead of assuming that '' and NULL are the same thing.

ALTER PROCEDURE [dbo].[psProducts] 
(
  @SearchType varchar(50) = NULL
)
AS
BEGIN
  SET NOCOUNT ON;

  SELECT P.[ProductId]
  ,P.[ProductName]
  ,P.[ProductPrice]
  ,P.[Type]
  FROM dbo.[Product] AS P
  WHERE p.[Type] = COALESCE(NULLIF(@SearchType, ''), p.[Type]);
END
GO

Now if you pass NULL, an empty string (''), or leave out the parameter, the where clause will essentially be ignored.

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

I had the same issue and the following seemed to have addressed the issue.

a) Updated to latest version 1.3.5 and re-enabled all the diagnosis settings.

I was still getting the messages

b) Added the vendor folder with the dependent libraries to the workspace

This seems to have solved the problem.

What are good ways to prevent SQL injection?

By using the SqlCommand and its child collection of parameters all the pain of checking for sql injection is taken away from you and will be handled by these classes.

Here is an example, taken from one of the articles above:

private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored  
    // in an xml column.  
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics. 
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

Is it possible to convert char[] to char* in C?

If you have char[] c then you can do char* d = &c[0] and access element c[1] by doing *(d+1), etc.

Redirect stderr to stdout in C shell

As paxdiablo said you can use >& to redirect both stdout and stderr. However if you want them separated you can use the following:

(command > stdoutfile) >& stderrfile

...as indicated the above will redirect stdout to stdoutfile and stderr to stderrfile.

Java Try and Catch IOException Problem

Your countLines(String filename) method throws IOException.

You can't use it in a member declaration. You'll need to perform the operation in a main(String[] args) method.

Your main(String[] args) method will get the IOException thrown to it by countLines and it will need to handle or declare it.

Try this to just throw the IOException from main

public class MyClass {
  private int lineCount;
  public static void main(String[] args) throws IOException {
    lineCount = LineCounter.countLines(sFileName);
  }
}

or this to handle it and wrap it in an unchecked IllegalArgumentException:

public class MyClass {
  private int lineCount;
  private String sFileName  = "myfile";
  public static void main(String[] args) throws IOException {
    try {
      lineCount = LineCounter.countLines(sFileName);
     } catch (IOException e) {
       throw new IllegalArgumentException("Unable to load " + sFileName, e);
     }
  }
}

react-router - pass props to handler component

The problem with the React Router is that it renders your components and so stops you passsing in props. The Navigation router, on the other hand, lets you render your own components. That means you don't have to jump through any hoops to pass in props as the following code and accompanying JsFiddle show.

var Comments = ({myProp}) => <div>{myProp}</div>;

var stateNavigator = new Navigation.StateNavigator([
  {key:'comments', route:''}
]);

stateNavigator.states.comments.navigated = function(data) {
  ReactDOM.render(
    <Comments myProp="value" />,
    document.getElementById('content')
  );
}

stateNavigator.start();

Is quitting an application frowned upon?

The Linux kernel has a feature called Out-of-memory killer (as mentioned above, the policies are configurable at the userspace level as well as the kernel is not an optimal one, but by no means unnecessary).

And it is heavily used by Android:

Some userspace apps are available to assist with these kill apps, for example:

import android packages cannot be resolved

May be you are using this checking :

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
}

To resolve this you need to import android.provider.DocumentsContract class.

To resolve this issue you'll need to set the build SDK version to 19 (4.4) or higher to have API level 19 symbols available while compiling.

First, use the SDK Manager to download API 19 if you don't have it yet. Then, configure your project to use API 19:

  • In Android Studio: File -> Project Structure -> General Settings -> Project SDK.
  • In Eclipse ADT: Project Properties -> Android -> Project Build Target

I found this answer from here

Thanks .

Is there an SQLite equivalent to MySQL's DESCRIBE [table]?

To see all tables:

.tables

To see a particular table:

.schema [tablename]

pros and cons between os.path.exists vs os.path.isdir

os.path.exists will also return True if there's a regular file with that name.

os.path.isdir will only return True if that path exists and is a directory, or a symbolic link to a directory.

What is the difference between json.dump() and json.dumps() in python?

One notable difference in Python 2 is that if you're using ensure_ascii=False, dump will properly write UTF-8 encoded data into the file (unless you used 8-bit strings with extended characters that are not UTF-8):

dumps on the other hand, with ensure_ascii=False can produce a str or unicode just depending on what types you used for strings:

Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance.

(emphasis mine). Note that it may still be a str instance as well.

Thus you cannot use its return value to save the structure into file without checking which format was returned and possibly playing with unicode.encode.

This of course is not valid concern in Python 3 any more, since there is no more this 8-bit/Unicode confusion.


As for load vs loads, load considers the whole file to be one JSON document, so you cannot use it to read multiple newline limited JSON documents from a single file.

Laravel Mail::send() sending to multiple to or bcc addresses

You can loop over recipientce like:

foreach (['[email protected]', '[email protected]'] as $recipient) {
    Mail::to($recipient)->send(new OrderShipped($order));
}

See documentation here

How to write an inline IF statement in JavaScript?

To add to this you can also use inline if condition with && and || operators. Like this

var a = 2;
var b = 0;

var c = (a > b || b == 0)? "do something" : "do something else";

How to Run Terminal as Administrator on Mac Pro

You can run a command as admin using

sudo <command>

You can also switch to root and every command will be run as root

sudo su

How can I listen for a click-and-hold in jQuery?

    var _timeoutId = 0;

    var _startHoldEvent = function(e) {
      _timeoutId = setInterval(function() {
         myFunction.call(e.target);
      }, 1000);
    };

    var _stopHoldEvent = function() {
      clearInterval(_timeoutId );
    };

    $('#myElement').on('mousedown', _startHoldEvent).on('mouseup mouseleave', _stopHoldEvent);

Jenkins Git Plugin: How to build specific tag?

Can't you tell Jenkins to build from a Ref name? If so then it's

refs/tags/tag-name

From all the questions I see about Jenkins and Hudson, I'd suggest switching to TeamCity. I haven't had to edit any configuration files to get TeamCity to work.

How can you create pop up messages in a batch script?

You can take advantage of CSCRIPT.EXE or WSCRIPT.EXE (which have been present in every version of Windows since, I believe, Windows 95) like this:

echo msgbox "Hey! Here is a message!" > %tmp%\tmp.vbs
cscript /nologo %tmp%\tmp.vbs
del %tmp%\tmp.vbs

or

echo msgbox "Hey! Here is a message!" > %tmp%\tmp.vbs
wscript %tmp%\tmp.vbs
del %tmp%\tmp.vbs

You could also choose the more customizeable PopUp command. This example gives you a 10 second window to click OK, before timing out:

echo set WshShell = WScript.CreateObject("WScript.Shell") > %tmp%\tmp.vbs
echo WScript.Quit (WshShell.Popup( "You have 10 seconds to Click 'OK'." ,10 ,"Click OK", 0)) >> %tmp%\tmp.vbs
cscript /nologo %tmp%\tmp.vbs
if %errorlevel%==1 (
  echo You Clicked OK
) else (
  echo The Message timed out.
)
del %tmp%\tmp.vbs

In their above context, both cscript and wscript will act the same. When called from a batch file, bot cscript and wscript will pause the batch file until they finish their script, then allow the file to continue.

When called manually from the command prompt, cscript will not return control to the command prompt until it is finished, while wscript will create a seprate thread for the execution of it's script, returning control to the command prompt even before it's script has finished.

Other methods discussed in this thread do not cause the execution of batch files to pause while waiting for the message to be clicked on. Your selection will be dictated by your needs.

Note: Using this method, multiple button and icon configurations are available to cover various yes/no/cancel/abort/retry queries to the user: https://technet.microsoft.com/en-us/library/ee156593.aspx

enter image description here

Printing Mongo query output to a file while in the mongo shell

If you invoke the shell with script-file, db address, and --quiet arguments, you can redirect the output (made with print() for example) to a file:

mongo localhost/mydatabase --quiet myScriptFile.js > output 

C++ - how to find the length of an integer

Closed formula for the longest int (I used int here, but works for any signed integral type):

1 + (int) ceil((8*sizeof(int)-1) * log10(2))

Explanation:

                  sizeof(int)                 // number bytes in int
                8*sizeof(int)                 // number of binary digits (bits)
                8*sizeof(int)-1               // discount one bit for the negatives
               (8*sizeof(int)-1) * log10(2)   // convert to decimal, because:
                                              // 1 bit == log10(2) decimal digits
    (int) ceil((8*sizeof(int)-1) * log10(2))  // round up to whole digits
1 + (int) ceil((8*sizeof(int)-1) * log10(2))  // make room for the minus sign

For an int type of 4 bytes, the result is 11. An example of 4 bytes int with 11 decimal digits is: "-2147483648".

If you want the number of decimal digits of some int value, you can use the following function:

unsigned base10_size(int value)
{
    if(value == 0) {
        return 1u;
    }

    unsigned ret;
    double dval;
    if(value > 0) {
        ret = 0;
        dval = value;
    } else {
        // Make room for the minus sign, and proceed as if positive.
        ret = 1;
        dval = -double(value);
    }

    ret += ceil(log10(dval+1.0));

    return ret;
}

I tested this function for the whole range of int in g++ 9.3.0 for x86-64.

How do I include inline JavaScript in Haml?

You can actually do what Chris Chalmers does in his answer, but you must make sure that HAML doesn't parse the JavaScript. This approach is actually useful when you need to use a different type than text/javascript, which is was I needed to do for MathJax.

You can use the plain filter to keep HAML from parsing the script and throwing an illegal nesting error:

%script{type: "text/x-mathjax-config"}
  :plain
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [["$","$"],["\\(","\\)"]]
      }
    });

How to set value in @Html.TextBoxFor in Razor syntax?

The problem is that you are using a lower case v.

You need to set it to Value and it should fix your issue:

@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", Value= "3" })

What is the best way to paginate results in SQL Server

Getting the total number of results and paginating are two different operations. For the sake of this example, let's assume that the query you're dealing with is

SELECT * FROM Orders WHERE OrderDate >= '1980-01-01' ORDER BY OrderDate

In this case, you would determine the total number of results using:

SELECT COUNT(*) FROM Orders WHERE OrderDate >= '1980-01-01'

...which may seem inefficient, but is actually pretty performant, assuming all indexes etc. are properly set up.

Next, to get actual results back in a paged fashion, the following query would be most efficient:

SELECT  *
FROM    ( SELECT    ROW_NUMBER() OVER ( ORDER BY OrderDate ) AS RowNum, *
          FROM      Orders
          WHERE     OrderDate >= '1980-01-01'
        ) AS RowConstrainedResult
WHERE   RowNum >= 1
    AND RowNum < 20
ORDER BY RowNum

This will return rows 1-19 of the original query. The cool thing here, especially for web apps, is that you don't have to keep any state, except the row numbers to be returned.

How do android screen coordinates work?

This picture will remove everyone's confusion hopefully which is collected from there.

Android screen coordinate

Resolving IP Address from hostname with PowerShell

The Test-Connection command seems to be a useful alternative, and it can either provide either a Win32_PingStatus object, or a boolean value.

Documentation: https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.management/test-connection

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

I had the same problem. Go to Project Properties -> Deployment Assemplbly and add jstl jar

Get Value of Row in Datatable c#

for (int i=0; i<dt_pattern.Rows.Count; i++)
{
    DataRow dr = dt_pattern.Rows[i];
}

In the loop, you can now reference row i+1 (assuming there is an i+1)

Class Not Found: Empty Test Suite in IntelliJ

This might also happen, if your test folder has been imported as a separate module (a small square is shown on the folder icon in the project view).
Remove the module by selecting the test folder in the project view and press DEL.
Then start your test.
If a popup dialog appears with an error message, that no module is selected, specify your root module from the dropdown.

PHP: Inserting Values from the Form into MySQL

There are two problems in your code.

  1. No action found in form.
  2. You have not executed the query mysqli_query()

dbConfig.php

<?php

$conn=mysqli_connect("localhost","root","password","testDB");

if(!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}

?>

index.php

 include('dbConfig.php');

<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="$1">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" type="text/css" href="style.css">

<title>test</title>


</head>
<body>

 <?php

  if(isset($_POST['save']))
{
    $sql = "INSERT INTO users (username, password, email)
    VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

    $result = mysqli_query($conn,$sql);
}

?>

<form action="index.php" method="post"> 
<label id="first"> First name:</label><br/>
<input type="text" name="username"><br/>

<label id="first">Password</label><br/>
<input type="password" name="password"><br/>

<label id="first">Email</label><br/>
<input type="text" name="email"><br/>

<button type="submit" name="save">save</button>

</form>

</body>
</html>

Android screen size HDPI, LDPI, MDPI

UPDATE: 30.07.2014

If you use Android Studio, make sure you have at least 144x144 resource and than use "FILE-NEW-IMAGE ASSET". Android Studio will make proper image files to all folders for you : )


As documentation says, adjust bitmaps as follows:

Almost every application should have alternative drawable resources for different screen densities, because almost every application has a launcher icon and that icon should look good on all screen densities. Likewise, if you include other bitmap drawables in your application (such as for menu icons or other graphics in your application), you should provide alternative versions or each one, for different densities.

Note: You only need to provide density-specific drawables for bitmap files (.png, .jpg, or .gif) and Nine-Path files (.9.png). If you use XML files to define shapes, colors, or other drawable resources, you should put one copy in the default drawable directory (drawable/).

To create alternative bitmap drawables for different densities, you should follow the 3:4:6:8 scaling ratio between the four generalized densities. For example, if you have a bitmap drawable that's 48x48 pixels for medium-density screen (the size for a launcher icon), all the different sizes should be:

36x36 for low-density (LDPI)

48x48 for medium-density (MDPI)

72x72 for high-density (HDPI)

96x96 for extra high-density (XHDPI)

144x144 for extra extra high-density (XXHDPI)

192x192 for extra extra extra high-density (XXXHDPI)

Getting SyntaxError for print with keyword argument end=' '

Are you sure you are using Python 3.x? The syntax isn't available in Python 2.x because print is still a statement.

print("foo" % bar, end=" ")

in Python 2.x is identical to

print ("foo" % bar, end=" ")

or

print "foo" % bar, end=" "

i.e. as a call to print with a tuple as argument.

That's obviously bad syntax (literals don't take keyword arguments). In Python 3.x print is an actual function, so it takes keyword arguments, too.

The correct idiom in Python 2.x for end=" " is:

print "foo" % bar,

(note the final comma, this makes it end the line with a space rather than a linebreak)

If you want more control over the output, consider using sys.stdout directly. This won't do any special magic with the output.

Of course in somewhat recent versions of Python 2.x (2.5 should have it, not sure about 2.4), you can use the __future__ module to enable it in your script file:

from __future__ import print_function

The same goes with unicode_literals and some other nice things (with_statement, for example). This won't work in really old versions (i.e. created before the feature was introduced) of Python 2.x, though.

I just assigned a variable, but echo $variable shows something else

Additional to putting the variable in quotation, one could also translate the output of the variable using tr and converting spaces to newlines.

$ echo $var | tr " " "\n"
foo
bar
baz

Although this is a little more convoluted, it does add more diversity with the output as you can substitute any character as the separator between array variables.

Detect if a jQuery UI dialog box is open

jQuery dialog has an isOpen property that can be used to check if a jQuery dialog is open or not.

You can see example at this link: http://www.codegateway.com/2012/02/detect-if-jquery-dialog-box-is-open.html

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

For a lot of projects, there is actually 0% difference between the different pythons in terms of speed. That is those that are dominated by engineering time and where all pythons have the same amount of library support.

Node.js global variables

Use a global namespace like global.MYAPI = {}:

global.MYAPI._ = require('underscore')

All other posters talk about the bad pattern involved. So leaving that discussion aside, the best way to have a variable defined globally (OP's question) is through namespaces.

Tip: Development Using Namespaces

Class file has wrong version 52.0, should be 50.0

In your IntelliJ idea find tools.jar replace it with tools.jar from yout JDK8

log4j: Log output of a specific class to a specific appender

An example:

log4j.rootLogger=ERROR, logfile

log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.datePattern='-'dd'.log'
log4j.appender.logfile.File=log/radius-prod.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n

log4j.logger.foo.bar.Baz=DEBUG, myappender
log4j.additivity.foo.bar.Baz=false

log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myappender.datePattern='-'dd'.log'
log4j.appender.myappender.File=log/access-ext-dmz-prod.log
log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n

How can I get a vertical scrollbar in my ListBox?

The problem with your solution is you're putting a scrollbar around a ListBox where you probably want to put it inside the ListBox.

If you want to force a scrollbar in your ListBox, use the ScrollBar.VerticalScrollBarVisibility attached property.

<ListBox 
    ItemsSource="{Binding}" 
    ScrollViewer.VerticalScrollBarVisibility="Visible">
</ListBox>

Setting this value to Auto will popup the scrollbar on an as needed basis.

How do I declare and use variables in PL/SQL like I do in T-SQL?

In Oracle PL/SQL, if you are running a query that may return multiple rows, you need a cursor to iterate over the results. The simplest way is with a for loop, e.g.:

declare
  myname varchar2(20) := 'tom';
begin
  for result_cursor in (select * from mytable where first_name = myname) loop
    dbms_output.put_line(result_cursor.first_name);
    dbms_output.put_line(result_cursor.other_field);
  end loop;
end;

If you have a query that returns exactly one row, then you can use the select...into... syntax, e.g.:

declare 
  myname varchar2(20);
begin
  select first_name into myname 
    from mytable 
    where person_id = 123;
end;

How to get request URL in Spring Boot RestController

If you don't want any dependency on Spring's HATEOAS or javax.* namespace, use ServletUriComponentsBuilder to get URI of current request:

import org.springframework.web.util.UriComponentsBuilder;

ServletUriComponentsBuilder.fromCurrentRequest();
ServletUriComponentsBuilder.fromCurrentRequestUri();

jQuery get the location of an element relative to window

function getWindowRelativeOffset(parentWindow, elem) {
        var offset = {
            left : 0,
            top : 0
        };
        // relative to the target field's document
        offset.left = elem.getBoundingClientRect().left;
        offset.top = elem.getBoundingClientRect().top;
        // now we will calculate according to the current document, this current
        // document might be same as the document of target field or it may be
        // parent of the document of the target field
        var childWindow = elem.document.frames.window;
        while (childWindow != parentWindow) {
            offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
            offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
            childWindow = childWindow.parent;
        }
        return offset;
    };

you can call it like this

getWindowRelativeOffset(top, inputElement);

I focus for IE only as per my requirement but similar can be done for other browsers

How to pass multiple values to single parameter in stored procedure

USE THIS

I have had this exact issue for almost 2 weeks, extremely frustrating but I FINALLY found this site and it was a clear walk-through of what to do.

http://blog.summitcloud.com/2010/01/multivalue-parameters-with-stored-procedures-in-ssrs-sql/

I hope this helps people because it was exactly what I was looking for

Using RegEx in SQL Server

You will have to build a CLR procedure that provides regex functionality, as this article illustrates.

Their example function uses VB.NET:

Imports System
Imports System.Data.Sql
Imports Microsoft.SqlServer.Server
Imports System.Data.SqlTypes
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Collections 'the IEnumerable interface is here  


Namespace SimpleTalk.Phil.Factor
    Public Class RegularExpressionFunctions
        'RegExIsMatch function
        <SqlFunction(IsDeterministic:=True, IsPrecise:=True)> _
        Public Shared Function RegExIsMatch( _
                                            ByVal pattern As SqlString, _
                                            ByVal input As SqlString, _
                                            ByVal Options As SqlInt32) As SqlBoolean
            If (input.IsNull OrElse pattern.IsNull) Then
                Return SqlBoolean.False
            End If
            Dim RegExOption As New System.Text.RegularExpressions.RegExOptions
            RegExOption = Options
            Return RegEx.IsMatch(input.Value, pattern.Value, RegExOption)
        End Function
    End Class      ' 
End Namespace

...and is installed in SQL Server using the following SQL (replacing '%'-delimted variables by their actual equivalents:

sp_configure 'clr enabled', 1
RECONFIGURE WITH OVERRIDE

IF EXISTS ( SELECT   1
            FROM     sys.objects
            WHERE    object_id = OBJECT_ID(N'dbo.RegExIsMatch') ) 
   DROP FUNCTION dbo.RegExIsMatch
go

IF EXISTS ( SELECT   1
            FROM     sys.assemblies asms
            WHERE    asms.name = N'RegExFunction ' ) 
   DROP ASSEMBLY [RegExFunction]

CREATE ASSEMBLY RegExFunction 
           FROM '%FILE%'
GO

CREATE FUNCTION RegExIsMatch
   (
    @Pattern NVARCHAR(4000),
    @Input NVARCHAR(MAX),
    @Options int
   )
RETURNS BIT
AS EXTERNAL NAME 
   RegExFunction.[SimpleTalk.Phil.Factor.RegularExpressionFunctions].RegExIsMatch
GO

--a few tests
---Is this card a valid credit card?
SELECT dbo.RegExIsMatch ('^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$','4241825283987487',1)
--is there a number in this string
SELECT dbo.RegExIsMatch( '\d','there is 1 thing I hate',1)
--Verifies number Returns 1
DECLARE @pattern VARCHAR(255)
SELECT @pattern ='[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]'
SELECT  dbo.RegExIsMatch (@pattern, '1298-673-4192',1),
        dbo.RegExIsMatch (@pattern,'A08Z-931-468A',1),
        dbo.RegExIsMatch (@pattern,'[A90-123-129X',1),
        dbo.RegExIsMatch (@pattern,'12345-KKA-1230',1),
        dbo.RegExIsMatch (@pattern,'0919-2893-1256',1)

Convert command line argument to string

You can create an std::string

#include <string>
#include <vector>
int main(int argc, char *argv[])
{
  // check if there is more than one argument and use the second one
  //  (the first argument is the executable)
  if (argc > 1)
  {
    std::string arg1(argv[1]);
    // do stuff with arg1
  }

  // Or, copy all arguments into a container of strings
  std::vector<std::string> allArgs(argv, argv + argc);
}

Linux command to translate DomainName to IP

Use this

$ dig +short stackoverflow.com

69.59.196.211

or this

$ host stackoverflow.com

stackoverflow.com has address 69.59.196.211
stackoverflow.com mail is handled by 30 alt2.aspmx.l.google.com.
stackoverflow.com mail is handled by 40 aspmx2.googlemail.com.
stackoverflow.com mail is handled by 50 aspmx3.googlemail.com.
stackoverflow.com mail is handled by 10 aspmx.l.google.com.
stackoverflow.com mail is handled by 20 alt1.aspmx.l.google.com.

C# Remove object from list of objects

First you have to find out the object in the list. Then you can remove from the list.

       var item = myList.Find(x=>x.ItemName == obj.ItemName);
       myList.Remove(item);

How can I sharpen an image in OpenCV?

To sharpen an image we can use the filter (as in many previous answers)

kernel = np.array([[-1, -1, -1],[-1, 8, -1],[-1, -1, 0]], np.float32) 

kernel /= denominator * kernel

It will be the most when the denominator is 1 and will decrease as increased (2.3..)

The most used one is when the denominator is 3.

Below is the implementation.

kernel = np.array([[-1, -1, -1],[-1, 8, -1],[-1, -1, 0]], np.float32) 

kernel = 1/3 * kernel

dst = cv2.filter2D(image, -1, kernel)

GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration

this resolved this issue by adding namespace to Global.asax.cs file.

using System.Web.Http;

this resolved the issue.

Best way to Format a Double value to 2 Decimal places

An alternative is to use String.format:

double[] arr = { 23.59004,
    35.7,
    3.0,
    9
};

for ( double dub : arr ) {
  System.out.println( String.format( "%.2f", dub ) );
}

output:

23.59
35.70
3.00
9.00

You could also use System.out.format (same method signature), or create a java.util.Formatter which works in the same way.

How to open a local disk file with JavaScript?

The xmlhttp request method is not valid for the files on local disk because the browser security does not allow us to do so.But we can override the browser security by creating a shortcut->right click->properties In target "... browser location path.exe" append --allow-file-access-from-files.This is tested on chrome,however care should be taken that all browser windows should be closed and the code should be run from the browser opened via this shortcut.

find all subsets that sum to a particular value

public class SumOfSubSet {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int a[] = {1,2};
        int sum=0;
        if(a.length<=0) {
            System.out.println(sum);
        }else {
        for(int i=0;i<a.length;i++) {
            sum=sum+a[i];
            for(int j=i+1;j<a.length;j++) {
                sum=sum+a[i]+a[j];
            }
        }
        System.out.println(sum);

        }


    }

}

Best way to list files in Java, sorted by Date Modified?

Collections.sort(listFiles, new Comparator<File>() {
        public int compare(File f1, File f2) {
            return Long.compare(f1.lastModified(), f2.lastModified());
        }
    });

where listFiles is the collection of all files in ArrayList

Creating a static class with no instances

You could use a classmethod or staticmethod

class Paul(object):
    elems = []

    @classmethod
    def addelem(cls, e):
        cls.elems.append(e)

    @staticmethod
    def addelem2(e):
        Paul.elems.append(e)

Paul.addelem(1)
Paul.addelem2(2)

print(Paul.elems)

classmethod has advantage that it would work with sub classes, if you really wanted that functionality.

module is certainly best though.

How to watch for a route change in AngularJS?

This is for the total beginner... like me:

HTML:

  <ul>
    <li>
      <a href="#"> Home </a>
    </li>
    <li>
      <a href="#Info"> Info </a>
    </li>
  </ul>

  <div ng-app="myApp" ng-controller="MainCtrl">
    <div ng-view>

    </div>
  </div>

Angular:

//Create App
var app = angular.module("myApp", ["ngRoute"]);

//Configure routes
app.config(function ($routeProvider) {
    $routeProvider
      .otherwise({ template: "<p>Coming soon</p>" })
      .when("/", {
        template: "<p>Home information</p>"
      })
      .when("/Info", {
        template: "<p>Basic information</p>"
        //templateUrl: "/content/views/Info.html"
      });
});

//Controller
app.controller('MainCtrl', function ($scope, $rootScope, $location) {
  $scope.location = $location.path();
  $rootScope.$on('$routeChangeStart', function () {
    console.log("routeChangeStart");
   //Place code here:....
   });
});

Hope this helps a total beginner like me. Here is the full working sample:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
  <ul>_x000D_
    <li>_x000D_
      <a href="#"> Home </a>_x000D_
    </li>_x000D_
    <li>_x000D_
      <a href="#Info"> Info </a>_x000D_
    </li>_x000D_
  </ul>_x000D_
_x000D_
  <div ng-app="myApp" ng-controller="MainCtrl">_x000D_
    <div ng-view>_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
  <script>_x000D_
//Create App_x000D_
var app = angular.module("myApp", ["ngRoute"]);_x000D_
_x000D_
//Configure routes_x000D_
app.config(function ($routeProvider) {_x000D_
    $routeProvider_x000D_
      .otherwise({ template: "<p>Coming soon</p>" })_x000D_
      .when("/", {_x000D_
        template: "<p>Home information</p>"_x000D_
      })_x000D_
      .when("/Info", {_x000D_
        template: "<p>Basic information</p>"_x000D_
        //templateUrl: "/content/views/Info.html"_x000D_
      });_x000D_
});_x000D_
_x000D_
//Controller_x000D_
app.controller('MainCtrl', function ($scope, $rootScope, $location) {_x000D_
  $scope.location = $location.path();_x000D_
  $rootScope.$on('$routeChangeStart', function () {_x000D_
    console.log("routeChangeStart");_x000D_
   //Place code here:...._x000D_
   });_x000D_
});_x000D_
  </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Merge two (or more) lists into one, in C# .NET

you can combine them using LINQ:

  list = list1.Concat(list2).Concat(list3).ToList();

the more traditional approach of using List.AddRange() might be more efficient though.

The service cannot be started, either because it is disabled or because it has no enabled devices associated with it

This error can occur on anything that requires elevated privileges in Windows.

It happens when the "Application Information" service is disabled in Windows services. There are a few viruses that use this as an attack vector to prevent people from removing the virus. It also prevents people from installing software to remove viruses.

The normal way to fix this would be to run services.msc, or to go into Administrative Tools and run "Services". However, you will not be able to do that if the "Application Information" service is disabled.

Instead, reboot your computer into Safe Mode (reboot and press F8 until the Windows boot menu appears, select Safe Mode with Networking). Then run services.msc and look for services that are designated as "Disabled" in the Startup Type column. Change these "Disabled" services to "Automatic".

Make sure the "Application Information" service is set to a Startup Type of "Automatic".

When you are done enabling your services, click Ok at the bottom of the tool and reboot your computer back into normal mode. The problem should be resolved when Windows reboots.

Push eclipse project to GitHub with EGit

I have the same issue and solved it by reading this post, while solving it, I hitted a problem: auth failed.

And I finally solved it by using a ssh key way to authorize myself. I found the EGit offical guide very useful and I configured the ssh way successfully by refer to the Eclipse SSH Configuration section in the link provided.

Hope it helps.

Deleting elements from std::set while iterating

I came across same old issue and found below code more understandable which is in a way per above solutions.

std::set<int*>::iterator beginIt = listOfInts.begin();
while(beginIt != listOfInts.end())
{
    // Use your member
    std::cout<<(*beginIt)<<std::endl;

    // delete the object
    delete (*beginIt);

    // erase item from vector
    listOfInts.erase(beginIt );

    // re-calculate the begin
    beginIt = listOfInts.begin();
}

How do I fetch only one branch of a remote Git repository?

The simplest way to do that

  git fetch origin <branch> && git checkout <branch>

Example: I want to fetch uat branch from origin and switch to this as the current working branch.

   git fetch origin uat && git checkout uat

How do you find all subclasses of a given class in Java?

The reason you see a difference between your implementation and Eclipse is because you scan each time, while Eclipse (and other tools) scan only once (during project load most of the times) and create an index. Next time you ask for the data it doesn't scan again, but look at the index.

How to go to a specific element on page?

here is a simple javascript for that

call this when you need to scroll the screen to an element which has id="yourSpecificElementId"

window.scroll(0,findPos(document.getElementById("yourSpecificElementId")));

and you need this function for the working:

//Finds y value of given object
function findPos(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        do {
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    return [curtop];
    }
}

the screen will be scrolled to your specific element.

How do I convert special UTF-8 chars to their iso-8859-1 equivalent using javascript?

you should add this line above your page

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

CSS - Overflow: Scroll; - Always show vertical scroll bar?

Try the following code to display scroll bar always on your page,

::-webkit-scrollbar {
  -webkit-appearance: none;
  width: 10px;
}

::-webkit-scrollbar-thumb {
  border-radius: 5px;
  background-color: rgba(0,0,0,.5);
  -webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}

this will always show the vertical and horizontal scroll bar on your page. If you need only a vertical scroll bar then put overflow-x: hidden

Specifying trust store information in spring boot application.properties

Here my extended version of Oleksandr Shpota's answer, including the imports. The package org.apache.http.* can be found in org.apache.httpcomponents:httpclient. I've commented the changes:

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Value("${http.client.ssl.key-store}")
private Resource keyStore;

@Value("${http.client.ssl.trust-store}")
private Resource trustStore;

// I use the same pw for both keystores:
@Value("${http.client.ssl.trust-store-password}")
private String keyStorePassword;

// wasn't able to provide this as a @Bean...:
private RestTemplate getRestTemplate() {
  try {
    SSLContext sslContext = SSLContexts.custom()
        // keystore wasn't within the question's scope, yet it might be handy:
        .loadKeyMaterial(
            keyStore.getFile(),
            keyStorePassword.toCharArray(),
            keyStorePassword.toCharArray())
        .loadTrustMaterial(
            trustStore.getURL(),
            keyStorePassword.toCharArray(),
            // use this for self-signed certificates only:
            new TrustSelfSignedStrategy())
        .build();

    HttpClient httpClient = HttpClients.custom()
        // use NoopHostnameVerifier with caution, see https://stackoverflow.com/a/22901289/3890673
        .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()))
        .build();

    return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
  } catch (IOException | GeneralSecurityException e) {
    throw new RuntimeException(e);
  }
}

Play a Sound with Python

wxPython has support for playing wav files on Windows and Unix - I am not sure if this includes Macs. However it only support wav files as far as I can tell - it does not support other common formats such as mp3 or ogg.

Create new user in MySQL and give it full access to one database

To create a user and grant all privileges on a database.

Log in to MySQL:

mysql -u root

Now create and grant

GRANT ALL PRIVILEGES ON dbTest.* To 'user'@'hostname' IDENTIFIED BY 'password';

Anonymous user (for local testing only)

Alternately, if you just want to grant full unrestricted access to a database (e.g. on your local machine for a test instance, you can grant access to the anonymous user, like so:

GRANT ALL PRIVILEGES ON dbTest.* To ''@'hostname'

Be aware

This is fine for junk data in development. Don't do this with anything you care about.

How to round up a number to nearest 10?

I wanted to round up to the next number in the largest digits place (is there a name for that?), so I made the following function (in php):

//Get the max value to use in a graph scale axis, 
//given the max value in the graph
function getMaxScale($maxVal) {
    $maxInt = ceil($maxVal);
    $numDigits = strlen((string)$maxInt)-1; //this makes 2150->3000 instead of 10000
    $dividend = pow(10,$numDigits);
    $maxScale= ceil($maxInt/ $dividend) * $dividend;
    return $maxScale;
}

How do you get/set media volume (not ringtone volume) in Android?

Instead of AudioManager.STREAM_RING you shoul use AudioManager.STREAM_MUSIC This question has already discussed here.

HTTP Status 504

You can't. The problem is not that your app is impatient and timing out; the problem is that an intermediate proxy is impatient and timing out. "The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI." (http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5) It most likely indicates that the origin server is having some sort of issue, so it's not responding quickly to the forwarded request.

Possible solutions, none of which are likely to make you happy:

  • Increase timeout value of the proxy (if it's under your control)
  • Make your request to a different server (if there's another server with the same data)
  • Make your request differently (if possible) such that you are requesting less data at a time
  • Try again once the server is not having issues

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

I'm afraid there's a conflict with the port number(80). Make sure you don't run some software like Skype that use the same port 80

SyntaxError: Cannot use import statement outside a module

  1. I had the same problem when I started to used babel... But later, I had a solution... I haven't had the problem anymore so far... Currently, Node v12.14.1, "@babel/node": "^7.8.4", I use babel-node and nodemon to execute (node is fine as well..)
  2. package.json: "start": "nodemon --exec babel-node server.js "debug": "babel-node debug server.js" !!note: server.js is my entry file, you can use yours.
  3. launch.json When you debug, you also need to config your launch.json file "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/babel-node" !!note: plus runtimeExecutable into the configuration.
  4. Of course, with babel-node, you also normally need and edit another file, such as babel.config.js/.babelrc file

Django set default form values

As explained in Django docs, initial is not default.

  • The initial value of a field is intended to be displayed in an HTML . But if the user delete this value, and finally send back a blank value for this field, the initial value is lost. So you do not obtain what is expected by a default behaviour.

  • The default behaviour is : the value that validation process will take if data argument do not contain any value for the field.

To implement that, a straightforward way is to combine initial and clean_<field>():

class JournalForm(ModelForm):
    tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) 

    (...)

    def clean_tank(self):
        if not self['tank'].html_name in self.data:
            return self.fields['tank'].initial
        return self.cleaned_data['tank']

Failed to find Build Tools revision 23.0.1

I faced the same problem and I solved it doing the following:

Go to /home/[USER]/Android/Sdk/tools and execute:

$android list sdk -a

Which will show a list like:

  1. Android SDK Tools, revision 24.0.2
  2. Android SDK Platform-tools, revision 23.0.2
  3. Android SDK Platform-tools, revision 23.0.1

... and many more

Then, execute the command (attention! at your computer the third option may be different):

$android update sdk -a -u -t 3

It will install the 23.0.1 SDK Platform-tools components.

Try to build your project again.

'if' statement in jinja2 template

Why the loop?

You could simply do this:

{% if 'priority' in data %}
    <p>Priority: {{ data['priority'] }}</p>
{% endif %}

When you were originally doing your string comparison, you should have used == instead.

Use multiple custom fonts using @font-face?

You can use multiple font faces quite easily. Below is an example of how I used it in the past:

<!--[if (IE)]><!-->
    <style type="text/css" media="screen">
        @font-face {
            font-family: "Century Schoolbook";
            src: url(/fonts/century-schoolbook.eot);
        }
        @font-face {
            font-family: "Chalkduster";
            src: url(/fonts/chalkduster.eot);
        }
    </style>
<!--<![endif]-->
<!--[if !(IE)]><!-->
    <style type="text/css" media="screen">
        @font-face {
            font-family: "Century Schoolbook";
            src: url(/fonts/century-schoolbook.ttf);
        }
        @font-face {
            font-family: "Chalkduster";
            src: url(/fonts/chalkduster.ttf);
        }
    </style>
<!--<![endif]-->

It is worth noting that fonts can be funny across different Browsers. Font face on earlier browsers works, but you need to use eot files instead of ttf.

That is why I include my fonts in the head of the html file as I can then use conditional IE tags to use eot or ttf files accordingly.

If you need to convert ttf to eot for this purpose there is a brilliant website you can do this for free online, which can be found at http://ttf2eot.sebastiankippe.com/.

Hope that helps.

How do I replace text inside a div element?

If you're inclined to start using a lot of JavaScript on your site, jQuery makes playing with the DOM extremely simple.

http://docs.jquery.com/Manipulation

Makes it as simple as: $("#field-name").text("Some new text.");

Maximum value of maxRequestLength?

2,147,483,647 bytes, since the value is a signed integer (Int32). That's probably more than you'll need.

For Loop on Lua

names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
  print (names)
end
  1. You're deleting your table and replacing it with an int
  2. You aren't pulling a value from the table

Try:

names = {'John','Joe','Steve'}
for i = 1,3 do
    print(names[i])
end

Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

Made a couple of additions to the above answers so that you get returned a type instead of string value.

I figured that this is primarily going to be used for UI adjustments so I didn't think it relevant to include all the sub models i.e. iPhone 5s but this could be easily extended by adding in model tests to the isDevice Array

Tested working in Swift 3.1 Xcode 8.3.2 with physical and simulator devices

Implementation:

UIDevice.whichDevice()

public enum SVNDevice {
  case isiPhone4, isIphone5, isIphone6or7, isIphone6por7p, isIphone, isIpad, isIpadPro
}

extension UIDevice {
  class func whichDevice() -> SVNDevice? {
    let isDevice = { (comparision: Array<(Bool, SVNDevice)>) -> SVNDevice? in
      var device: SVNDevice?
      comparision.forEach({
        device = $0.0 ? $0.1 : device
      })
      return device
    }

    return isDevice([
      (UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0, SVNDevice.isiPhone4),
      (UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0, SVNDevice.isIphone5),
      (UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0, SVNDevice.isIphone6or7),
      (UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0, SVNDevice.isIphone6por7p),
      (UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0, SVNDevice.isIpad),
      (UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1366.0, SVNDevice.isIpadPro)])
  }
}



private struct ScreenSize {
  static let SCREEN_WIDTH         = UIScreen.main.bounds.size.width
  static let SCREEN_HEIGHT        = UIScreen.main.bounds.size.height
  static let SCREEN_MAX_LENGTH    = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
  static let SCREEN_MIN_LENGTH    = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}

I've created a framework called SVNBootstaper which includes this and some other helper protocols, it's public and available through Carthage.

How to reload the datatable(jquery) data?

For the newer versions use:

var datatable = $('#table').dataTable().api();

$.get('myUrl', function(newDataArray) {
    datatable.clear();
    datatable.rows.add(newDataArray);
    datatable.draw();
});

Taken from: https://stackoverflow.com/a/27781459/4059810

Splitting a table cell into two columns in HTML

Please try the following way.

<table>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
  <tr>
    <td colspan="2">Sum: $180</td>
  </tr>
</table>

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

If you are Clion/anyOtherJetBrainsIDE user, and yourFile.exe cause this problem, just delete it and let the app create and link it with libs from a scratch. It helps.

Getting a list of all subdirectories in the current directory

Building upon Eli Bendersky's solution, use the following example:

import os
test_directory = <your_directory>
for child in os.listdir(test_directory):
    test_path = os.path.join(test_directory, child)
    if os.path.isdir(test_path):
        print test_path
        # Do stuff to the directory "test_path"

where <your_directory> is the path to the directory you want to traverse.

How to sort a data frame by date

In case you want to sort dates with descending order the minus sign doesn't work with Dates.

out <- DF[rev(order(as.Date(DF$end))),]

However you can have the same effect with a general purpose function: rev(). Therefore, you mix rev and order like:

#init data
DF <- data.frame(ID=c('ID3', 'ID2','ID1'), end=c('4/1/09 12:00', '6/1/10 14:20', '1/1/11 11:10')
#change order
out <- DF[rev(order(as.Date(DF$end))),]

Hope it helped.

Constants in Objective-C

I am generally using the way posted by Barry Wark and Rahul Gupta.

Although, I do not like repeating the same words in both .h and .m file. Note, that in the following example the line is almost identical in both files:

// file.h
extern NSString* const MyConst;

//file.m
NSString* const MyConst = @"Lorem ipsum";

Therefore, what I like to do is to use some C preprocessor machinery. Let me explain through the example.

I have a header file which defines the macro STR_CONST(name, value):

// StringConsts.h
#ifdef SYNTHESIZE_CONSTS
# define STR_CONST(name, value) NSString* const name = @ value
#else
# define STR_CONST(name, value) extern NSString* const name
#endif

The in my .h/.m pair where I want to define the constant I do the following:

// myfile.h
#import <StringConsts.h>

STR_CONST(MyConst, "Lorem Ipsum");
STR_CONST(MyOtherConst, "Hello world");

// myfile.m
#define SYNTHESIZE_CONSTS
#import "myfile.h"

et voila, I have all the information about the constants in .h file only.

How to perform grep operation on all files in a directory?

If you want to do multiple commands, you could use:

for I in `ls *.sql`
do
    grep "foo" $I >> foo.log
    grep "bar" $I >> bar.log
done

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

I needed to do this because I have an ajax login form. When users login successfully I redirect to a new page and end the previous request because the other page handles redirecting back to the relying party (because it's a STS SSO System).

However, I also wanted it to work with javascript disabled, being the central login hop and all, so I came up with this,

    public static string EnsureUrlEndsWithSlash(string url)
    {
        if (string.IsNullOrEmpty(url))
            throw new ArgumentNullException("url");
        if (!url.EndsWith("/"))
            return string.Concat(url, "/");
        return url;
    }

    public static string GetQueryStringFromArray(KeyValuePair<string, string>[] values)
    {
        Dictionary<string, string> dValues = new Dictionary<string,string>();
        foreach(var pair in values)            
            dValues.Add(pair.Key, pair.Value);            
        var array = (from key in dValues.Keys select string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(dValues[key]))).ToArray();
        return "?" + string.Join("&", array);
    }

    public static void RedirectTo(this HttpRequestBase request, string url, params KeyValuePair<string, string>[] queryParameters)
    {            
        string redirectUrl = string.Concat(EnsureUrlEndsWithSlash(url), GetQueryStringFromArray(queryParameters));
        if (request.IsAjaxRequest())
            HttpContext.Current.Response.Write(string.Format("<script type=\"text/javascript\">window.location='{0}';</script>", redirectUrl));
        else
            HttpContext.Current.Response.Redirect(redirectUrl, true);

    }

RandomForestClassfier.fit(): ValueError: could not convert string to float

You have to do some encoding before using fit. As it was told fit() does not accept Strings but you solve this.

There are several classes that can be used :

  • LabelEncoder : turn your string into incremental value
  • OneHotEncoder : use One-of-K algorithm to transform your String into integer

Personally I have post almost the same question on StackOverflow some time ago. I wanted to have a scalable solution but didn't get any answer. I selected OneHotEncoder that binarize all the strings. It is quite effective but if you have a lot different strings the matrix will grow very quickly and memory will be required.

How do you determine what SQL Tables have an identity column programmatically

By some reason sql server save some identity columns in different tables, the code that work for me, is the following:

select      TABLE_NAME tabla,COLUMN_NAME columna
from        INFORMATION_SCHEMA.COLUMNS
where       COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
union all
select      o.name tabla, c.name columna
from        sys.objects o 
inner join  sys.columns c on o.object_id = c.object_id
where       c.is_identity = 1

Pass variables between two PHP pages without using a form or the URL of page

Sessions would be good choice for you. Take a look at these two examples from PHP Manual:

Code of page1.php

<?php
// page1.php

session_start();

echo 'Welcome to page #1';

$_SESSION['favcolor'] = 'green';
$_SESSION['animal']   = 'cat';
$_SESSION['time']     = time();

// Works if session cookie was accepted
echo '<br /><a href="page2.php">page 2</a>';

// Or pass along the session id, if needed
echo '<br /><a href="page2.php?' . SID . '">page 2</a>';
?>

Code of page2.php

<?php
// page2.php

session_start();

echo 'Welcome to page #2<br />';

echo $_SESSION['favcolor']; // green
echo $_SESSION['animal'];   // cat
echo date('Y m d H:i:s', $_SESSION['time']);

// You may want to use SID here, like we did in page1.php
echo '<br /><a href="page1.php">page 1</a>';
?>

To clear up things - SID is PHP's predefined constant which contains session name and its id. Example SID value:

PHPSESSID=d78d0851898450eb6aa1e6b1d2a484f1

Remove rows with all or some NAs (missing values) in data.frame

tidyr has a new function drop_na:

library(tidyr)
df %>% drop_na()
#              gene hsap mmul mmus rnor cfam
# 2 ENSG00000199674    0    2    2    2    2
# 6 ENSG00000221312    0    1    2    3    2
df %>% drop_na(rnor, cfam)
#              gene hsap mmul mmus rnor cfam
# 2 ENSG00000199674    0    2    2    2    2
# 4 ENSG00000207604    0   NA   NA    1    2
# 6 ENSG00000221312    0    1    2    3    2

How many bytes is unsigned long long?

The beauty of C++, like C, is that the sized of these things are implementation-defined, so there's no correct answer without your specifying the compiler you're using. Are those two the same? Yes. "long long" is a synonym for "long long int", for any compiler that will accept both.

JPA - Persisting a One to Many relationship

You have to set the associatedEmployee on the Vehicle before persisting the Employee.

Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);

newEmployee.setVehicles(vehicles);

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

Why aren't python nested functions called closures?

def nested1(num1): 
    print "nested1 has",num1
    def nested2(num2):
        print "nested2 has",num2,"and it can reach to",num1
        return num1+num2    #num1 referenced for reading here
    return nested2

Gives:

In [17]: my_func=nested1(8)
nested1 has 8

In [21]: my_func(5)
nested2 has 5 and it can reach to 8
Out[21]: 13

This is an example of what a closure is and how it can be used.

How to do multiple conditions for single If statement

As Hogan notes above, use an AND instead of &. See this tutorial for more info.

Check if Cell value exists in Column, and then get the value of the NEXT Cell

How about this?

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", INDIRECT(ADDRESS(MATCH(A1,B:B, 0), 3)))

The "3" at the end means for column C.

Pandas split column of lists into multiple columns

There seems to be a syntactically simpler way, and therefore easier to remember, as opposed to the proposed solutions. I'm assuming that the column is called 'meta' in a dataframe df:

df2 = pd.DataFrame(df['meta'].str.split().values.tolist())

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

The Scriptler Groovy script doesn't seem to get all the environment variables of the build. But what you can do is force them in as parameters to the script:

  1. When you add the Scriptler build step into your job, select the option "Define script parameters"

  2. Add a parameter for each environment variable you want to pass in. For example "Name: JOB_NAME", "Value: $JOB_NAME". The value will get expanded from the Jenkins build environment using '$envName' type variables, most fields in the job configuration settings support this sort of expansion from my experience.

  3. In your script, you should have a variable with the same name as the parameter, so you can access the parameters with something like:

    println "JOB_NAME = $JOB_NAME"

I haven't used Sciptler myself apart from some experimentation, but your question posed an interesting problem. I hope this helps!

How do you create a hidden div that doesn't create a line break or horizontal space?

Since the release of HTML5 one can now simply do:

<div hidden>This div is hidden</div>

Note: This is not supported by some old browsers, most notably IE < 11.

Hidden Attribute Documentation (MDN,W3C)

How can I test that a variable is more than eight characters in PowerShell?

Use the length property of the [String] type:

if ($dbUserName.length -gt 8) {
    Write-Output "Please enter more than 8 characters."
    $dbUserName = Read-Host "Re-enter database username"
}

Please note that you have to use -gt instead of > in your if condition. PowerShell uses the following comparison operators to compare values and test conditions:

  • -eq = equals
  • -ne = not equals
  • -lt = less than
  • -gt = greater than
  • -le = less than or equals
  • -ge = greater than or equals

How to have image and text side by side

HTML

<div class='containerBox'>
    <div>
       <img src='http://ecx.images-amazon.com/images/I/21-leKb-zsL._SL500_AA300_.png' class='iconDetails'>
       <div>
       <h4>Facebook</h4>  
       <div style="font-size:.6em;float:left; margin-left:5px;color:white;">fine location, GPS, coarse location</div>
       <div style="float:right;font-size:.6em; margin-right:5px; color:white;">0 mins ago</div>
       </div>
   </div> 
</div>

CSS

 .iconDetails {
 margin-left:2%;
 float:left; 
 height:40px;
 width:40px;
 } 

.containerBox {
width:300px;
height:60px;
padding:1px;
background-color:#303030;
}
h4{
margin:0px;
margin-top:3%;
margin-left:50px;
color:white;
}

What is the difference between null=True and blank=True in Django?

null - default is False if True, Django will store empty as null in the database.

blank - default is False if true that field is allowed to be blank

more, goto https://docs.djangoproject.com/en/3.0/topics/db/models/

Deleting queues in RabbitMQ

I was struggling with finding an answer that suited my needs of manually delete a queue in rabbigmq. I therefore think it is worth mentioning in this thread that it is possible to delete a single queue without rabbitmqadmin using the following command:

rabbitmqctl delete_queue <queue_name>

JUnit assertEquals(double expected, double actual, double epsilon)

Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.

If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like

double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);

(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)

Click in OK button inside an Alert (Selenium IDE)

To click the "ok" button in an alert box:

driver.switchTo().alert().accept();

Can a for loop increment/decrement by more than one?

for (var i = 0; i < 10; i = i + 2) {
    // code here
}?

Perfect 100% width of parent container for a Bootstrap input?

Just add box-sizing:

input[type="text"] {
    box-sizing: border-box;
}

Access to the path denied error in C#

Did you try specifing some file name?

eg:

string route="D:\\somefilename.txt";

Implementing a slider (SeekBar) in Android

For future readers!

Starting from material components android 1.2.0-alpha01, you have slider component

ex:

<com.google.android.material.slider.Slider
        android:id="@+id/slider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:valueFrom="20f"
        android:valueTo="70f"
        android:stepSize="10" />

Difference between File.separator and slash in paths

With the Java libraries for dealing with files, you can safely use / (slash, not backslash) on all platforms. The library code handles translating things into platform-specific paths internally.

You might want to use File.separator in UI, however, because it's best to show people what will make sense in their OS, rather than what makes sense to Java.

Update: I have not been able, in five minutes of searching, to find the "you can always use a slash" behavior documented. Now, I'm sure I've seen it documented, but in the absense of finding an official reference (because my memory isn't perfect), I'd stick with using File.separator because you know that will work.

Eclipse reports rendering library more recent than ADT plug-in

Change the Target version to new updates you have. Otherwise, change what SDK version you have in the Android manifest file.

android:minSdkVersion="8"
android:targetSdkVersion="18"

Callback when CSS3 transition finishes

For anyone that this might be handy for, here is a jQuery dependent function I had success with for applying a CSS animation via a CSS class, then getting a callback from afterwards. It may not work perfectly since I had it being used in a Backbone.js App, but maybe useful.

var cssAnimate = function(cssClass, callback) {
    var self = this;

    // Checks if correct animation has ended
    var setAnimationListener = function() {
        self.one(
            "webkitAnimationEnd oanimationend msAnimationEnd animationend",
            function(e) {
                if(
                    e.originalEvent.animationName == cssClass &&
                    e.target === e.currentTarget
                ) {
                    callback();
                } else {
                    setAnimationListener();
                }
            }
        );
    }

    self.addClass(cssClass);
    setAnimationListener();
}

I used it kinda like this

cssAnimate.call($("#something"), "fadeIn", function() {
    console.log("Animation is complete");
    // Remove animation class name?
});

Original idea from http://mikefowler.me/2013/11/18/page-transitions-in-backbone/

And this seems handy: http://api.jqueryui.com/addClass/


Update

After struggling with the above code and other options, I would suggest being very cautious with any listening for CSS animation ends. With multiple animations going on, this can get messy very fast for event listening. I would strongly suggest an animation library like GSAP for every animation, even the small ones.

Datetime in C# add days

You need to catch the return value.

The DateTime.AddDays method returns an object who's value is the sum of the date and time of the instance and the added value.

endDate = endDate.AddDays(addedDays);

Psexec "run as (remote) admin"

Simply add a -h after adding your credentials using a -u -p, and it will run with elevated privileges.

Google.com and clients1.google.com/generate_204

In the event that Chrome detects SSL connection timeouts, certificate errors, or other network issues that might be caused by a captive portal (a hotel's WiFi network, for instance), Chrome will make a cookieless request to http://www.gstatic.com/generate_204 and check the response code. If that request is redirected, Chrome will open the redirect target in a new tab on the assumption that it's a login page. Requests to the captive portal detection page are not logged.

Source: Google Chrome Privacy Whitepaper

Create request with POST, which response codes 200 or 201 and content

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19

It's just a colon delimited key-value.

ETag: "xyzzy"

It can be any type of text data - I generally include a JSON string with the identifier of the item created. The ease of testing alone makes including it worthwhile.

ETag: "{ id: 1234, uri: 'http://domain.com/comments/1234', type: 'comment' }"

In this example, the identifier, the uri, and type of the created item are the "resource characteristics and location".

Difference between SurfaceView and View?

The main difference is that SurfaceView can be drawn on by background theads but Views can't. SurfaceViews use more resources though so you don't want to use them unless you have to.

How to get names of classes inside a jar file?

Description OF Solution : Eclipse IDE can be used for this by creating a sample java project and add all jars in the Project Build path

STEPS below:

  1. Create a sample Eclipse Java project.

  2. All all the jars you have in its Build Path

  3. CTRL+SHIFT+T and Type the full class name .

  4. Results will be displayed in the window with all the jars having that class. See attached picture . enter image description here

Date Format in Swift

Swift 3 with a Date extension

extension Date {
    func string(with format: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: self)
    }
}

Then you can use it like so:

let date = Date()
date.string(with: "MMM dd, yyyy")

ReactJS - How to use comments?

JavaScript comments in JSX get parsed as Text and show up in your app.

You can’t just use HTML comments inside of JSX because it treats them as DOM Nodes:

render() {
  return (
    <div>
      <!-- This doesn't work! -->
    </div>
  )
}

JSX comments for single line and multiline comments follows the convention

Single line comment:

{/* A JSX comment */}

Multiline comments:

{/* 
  Multi
  line
  comment
*/}  

How can I set the background color of <option> in a <select> element?

Just like normal background-color: #f0f

You just need a way to target it, eg: <option id="myPinkOption">blah</option>

How to get only numeric column values?

SELECT column1 FROM table WHERE column1 not like '%[0-9]%'

Removing the '^' did it for me. I'm looking at a varchar field and when I included the ^ it excluded all of my non-numerics which is exactly what I didn't want. So, by removing ^ I only got non-numeric values back.

What is the correct wget command syntax for HTTPS with username and password?

It's not that your file is partially downloaded. It fails authentication and hence downloads e.g "index.html" but it names it myfile.zip (since this is what you want to download).

I followed the link suggested by @thomasbabuj and figured it out eventually.

You should try adding --auth-no-challenge and as @thomasbabuj suggested replace your password entry

I.e

wget --auth-no-challenge --user=myusername --ask-password https://test.mydomain.com/files/myfile.zip

How / can I display a console window in Intellij IDEA?

IntelliJ IDEA 2018.3.6

Using macOS Mojave Version 10.14.4 and pressing ?F12(Alt+F12) will open Sound preferences.

A solution without changing the current keymap is to use the command above with the key fn.

fn ? F12(fn+Alt+F12) will open the Terminal. And you can use ShiftEsc to close it.

Rename Excel Sheet with VBA Macro

Suggest you add handling to test if any of the sheets to be renamed already exist:

Sub Test()

Dim ws As Worksheet
Dim ws1 As Worksheet
Dim strErr As String

On Error Resume Next
For Each ws In ActiveWorkbook.Sheets
Set ws1 = Sheets(ws.Name & "_v1")
    If ws1 Is Nothing Then
        ws.Name = ws.Name & "_v1"
    Else
         strErr = strErr & ws.Name & "_v1" & vbNewLine
    End If
Set ws1 = Nothing
Next
On Error GoTo 0

If Len(strErr) > 0 Then MsgBox strErr, vbOKOnly, "these sheets already existed"

End Sub

Is it possible to forward-declare a function in Python?

I apologize for reviving this thread, but there was a strategy not discussed here which may be applicable.

Using reflection it is possible to do something akin to forward declaration. For instance lets say you have a section of code that looks like this:

# We want to call a function called 'foo', but it hasn't been defined yet.
function_name = 'foo'
# Calling at this point would produce an error

# Here is the definition
def foo():
    bar()

# Note that at this point the function is defined
    # Time for some reflection...
globals()[function_name]()

So in this way we have determined what function we want to call before it is actually defined, effectively a forward declaration. In python the statement globals()[function_name]() is the same as foo() if function_name = 'foo' for the reasons discussed above, since python must lookup each function before calling it. If one were to use the timeit module to see how these two statements compare, they have the exact same computational cost.

Of course the example here is very useless, but if one were to have a complex structure which needed to execute a function, but must be declared before (or structurally it makes little sense to have it afterwards), one can just store a string and try to call the function later.

Using variables inside a bash heredoc

In answer to your first question, there's no parameter substitution because you've put the delimiter in quotes - the bash manual says:

The format of here-documents is:

      <<[-]word
              here-document
      delimiter

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. [...]

If you change your first example to use <<EOF instead of << "EOF" you'll find that it works.

In your second example, the shell invokes sudo only with the parameter cat, and the redirection applies to the output of sudo cat as the original user. It'll work if you try:

sudo sh -c "cat > /path/to/outfile" <<EOT
my text...
EOT

angular-cli server - how to proxy API requests to another server?

UPDATE 2017

Better documentation is now available and you can use both JSON and JavaScript based configurations: angular-cli documentation proxy

sample https proxy configuration

{
  "/angular": {
     "target":  {
       "host": "github.com",
       "protocol": "https:",
       "port": 443
     },
     "secure": false,
     "changeOrigin": true,
     "logLevel": "info"
  }
}

To my knowledge with Angular 2.0 release setting up proxies using .ember-cli file is not recommended. official way is like below

  1. edit "start" of your package.json to look below

    "start": "ng serve --proxy-config proxy.conf.json",

  2. create a new file called proxy.conf.json in the root of the project and inside of that define your proxies like below

    {
      "/api": {
        "target": "http://api.yourdomai.com",
        "secure": false
      }
    }
    
  3. Important thing is that you use npm start instead of ng serve

Read more from here : Proxy Setup Angular 2 cli

Python os.path.join() on a list

This can be also thought of as a simple map reduce operation if you would like to think of it from a functional programming perspective.

import os
folders = [("home",".vim"),("home","zathura")]
[reduce(lambda x,y: os.path.join(x,y), each, "") for each in folders]

reduce is builtin in Python 2.x. In Python 3.x it has been moved to itertools However the accepted the answer is better.

This has been answered below but answering if you have a list of items that needs to be joined.

Using CRON jobs to visit url?

* * * * * wget --quiet https://example.com/file --output-document=/dev/null

I find --quiet clearer than -q, and --output-document=/dev/null clearer than -O - > /dev/null

How to go back (ctrl+z) in vi/vim

Just in normal mode press:

  • u - undo,
  • Ctrl + r - redo changes which were undone (undo the undos).

Undo and Redo

javax.servlet.ServletException cannot be resolved to a type in spring web app

It seems to me that eclipse doesn't recognize the java ee web api (servlets, el, and so on). If you're using maven and don't want to configure eclipse with a specified server runtime, put the dependecy below in your web project pom:

<dependency>  
    <groupId>javax</groupId>    
    <artifactId>javaee-web-api</artifactId>    
    <version>7.0</version> <!-- Put here the version of your Java EE app, in my case 7.0 -->
    <scope>provided</scope>
</dependency>

How to display a list inline using Twitter's Bootstrap

I Amazed, list-inline wasn't working in bootstrap 4 then finally i got it in bootstrap 4 documentation.

Bootstrap 3 and 4

<ul class="list-inline">
  <li class="list-inline-item">Lorem ipsum</li>
  <li class="list-inline-item">Phasellus iaculis</li>
  <li class="list-inline-item">Nulla volutpat</li>
</ul>

Source: http://v4-alpha.getbootstrap.com/content/typography/#inline

PHP AES encrypt / decrypt

If you are using PHP >= 7.2 consider using inbuilt sodium core extension for encrption.

Find more information here - http://php.net/manual/en/intro.sodium.php.

How do I enable the column selection mode in Eclipse?

You can enable and disable column editing mode via the keyboard shortcut ALT-SHIFT-A.

Once enabled you can then use either the mouse to select a block of text, or the keyboard using SHIFT (like a normal keyboard select, except the selection will now be in a block).

If you've changed your default font for text editing, entering column editing mode will probably change your screen font to the default column editing font (which is probably different to your changed font. To change the font when in column editing mode, go to the menu and select Window -> Preferences, then in the tree on the left hand side, pick General -> Appearance -> Colors and Fonts, and then pick Basic -> Text Editor Block Selection Font on the right hand side tree. You can then select the font to be consistent with your "not in column editing mode" font.

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

To fix your specific error you need to run that command as sudo, ie:

sudo gem install rails --pre

How do I escape a string inside JavaScript code inside an onClick handler?

I have faced this problem as well. I made a script to convert single quotes into escaped double quotes that won't break the HTML.

function noQuote(text)
{
    var newtext = "";
    for (var i = 0; i < text.length; i++) {
        if (text[i] == "'") {
            newtext += "\"";
        }
        else {
            newtext += text[i];
        }
    }
    return newtext;
}

PHP CURL & HTTPS

Another option like Gavin Palmer answer is to use the .pem file but with a curl option

  1. download the last updated .pem file from https://curl.haxx.se/docs/caextract.html and save it somewhere on your server(outside the public folder)

  2. set the option in your code instead of the php.ini file.

In your code

curl_setopt($ch, CURLOPT_CAINFO, $_SERVER['DOCUMENT_ROOT'] .  "/../cacert-2017-09-20.pem");

NOTE: setting the cainfo in the php.ini like @Gavin Palmer did is better than setting it in your code like I did, because it will save a disk IO every time the function is called, I just make it like this in case you want to test the cainfo file on the fly instead of changing the php.ini while testing your function.

Angular 4 setting selected option in Dropdown

If you want to select a value as default, in your form builder give it a value :

this.myForm = this.FB.group({
    mySelect: [this.options[0].key, [/* Validators here */]]
});

Now in your HTML :

<form [formGroup]="myForm">
    <select [formControlName]="mySelect">
        <option *ngFor="let opt of options" [value]="opt.key">ANY TEXT YOU WANT HERE</option>
    </select>
</form>

What my code does is giving your select a value, that is equal to the first value of your options list. This is how you select an option as default in Angular, selected is useless.

@UniqueConstraint and @Column(unique = true) in hibernate annotation

From the Java EE documentation:

public abstract boolean unique

(Optional) Whether the property is a unique key. This is a shortcut for the UniqueConstraint annotation at the table level and is useful for when the unique key constraint is only a single field. This constraint applies in addition to any constraint entailed by primary key mapping and to constraints specified at the table level.

See doc

How to apply a function to two columns of Pandas dataframe

Here's an example using apply on the dataframe, which I am calling with axis = 1.

Note the difference is that instead of trying to pass two values to the function f, rewrite the function to accept a pandas Series object, and then index the Series to get the values needed.

In [49]: df
Out[49]: 
          0         1
0  1.000000  0.000000
1 -0.494375  0.570994
2  1.000000  0.000000
3  1.876360 -0.229738
4  1.000000  0.000000

In [50]: def f(x):    
   ....:  return x[0] + x[1]  
   ....:  

In [51]: df.apply(f, axis=1) #passes a Series object, row-wise
Out[51]: 
0    1.000000
1    0.076619
2    1.000000
3    1.646622
4    1.000000

Depending on your use case, it is sometimes helpful to create a pandas group object, and then use apply on the group.

Is it possible to reference one CSS rule within another?

If you're willing and able to employ a little jquery, you can simply do this:

$('.someDiv').css([".radius", ".opacity"]);

If you have a javascript that already processes the page or you can enclose it somewhere in <script> tags. If so, wrap the above in the document ready function:

$(document).ready( function() {
  $('.someDiv').css([".radius", ".opacity"]);
}

I recently came across this while updating a wordpress plugin. The them has been changed which used a lot of "!important" directives across the css. I had to use jquery to force my styles because of the genius decision to declare !important on several tags.

How do I encode URI parameter values?

I wrote my own, it's short, super simple, and you can copy it if you like: http://www.dmurph.com/2011/01/java-uri-encoder/

Why do I get the error "Unsafe code may only appear if compiling with /unsafe"?

For everybody who uses Rider you have to select your project>Right Click>Properties>Configurations Then select Debug and Release and check "Allow unsafe code" for both.Screenshot

Error: Uncaught SyntaxError: Unexpected token <

I too got this error, when developing a Backbone application using HTML5 push state in conjunction with an .htaccess which redirects any unknown files to index.html.

It turns out that when visiting a URL such as /something/5, my /index.html was effectively being served at /something/index.html (thanks to my .htaccess). This had the effect of breaking all the relative URLs to my JavaScript files (from inside the index.html ), which meant that they should have 404'd on me.

However, again due to my htaccess, instead of 404'ing when attempting to retrieve the JS files, they instead returned my index.html. Thus the browser was given an index.html for every JavaScript file it tried to pull in, and when it evaluated the HTML as if it were JavaScript, it returned a JS error due to the leading < (from my tag in index.html).

The fix in my case (as I was serving the site from inside a subdirectory) was to add a base tag in my html head.

<base href="/my-app/">

Get size of an Iterable in Java

If you are working with java 8 you may use:

Iterable values = ...
long size = values.spliterator().getExactSizeIfKnown();

it will only work if the iterable source has a determined size. Most Spliterators for Collections will, but you may have issues if it comes from a HashSetor ResultSetfor instance.

You can check the javadoc here.

If Java 8 is not an option, or if you don't know where the iterable comes from, you can use the same approach as guava:

  if (iterable instanceof Collection) {
        return ((Collection<?>) iterable).size();
    } else {
        int count = 0;
        Iterator iterator = iterable.iterator();
        while(iterator.hasNext()) {
            iterator.next();
            count++;
        }
        return count;
    }

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

Export to CSV using jQuery and html

What if you have your data in CSV format and convert it to HTML for display on the web page? You may use the http://code.google.com/p/js-tables/ plugin. Check this example http://code.google.com/p/js-tables/wiki/Table As you are already using jQuery library I have assumed you are able to add other javascript toolkit libraries.

If the data is in CSV format, you should be able to use the generic 'application/octetstream' mime type. All the 3 mime types you have tried are dependent on the software installed on the clients computer.

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

I had the same error when we imported a key into a keystore that was build using a 64bit OpenSSL Version. When we followed the same procedure to import the key into a keystore that was build using a 32 bit OpenSSL version everything went fine.

Executing Javascript from Python

One more solution as PyV8 seems to be unmaintained and dependent on the old version of libv8.

PyMiniRacer It's a wrapper around the v8 engine and it works with the new version and is actively maintained.

pip install py-mini-racer

from py_mini_racer import py_mini_racer
ctx = py_mini_racer.MiniRacer()
ctx.eval("""
function escramble_758(){
    var a,b,c
    a='+1 '
    b='84-'
    a+='425-'
    b+='7450'
    c='9'
    return a+c+b;
}
""")
ctx.call("escramble_758")

And yes, you have to replace document.write with return as others suggested

What Vim command(s) can be used to quote/unquote words?

For users of VSCodeVim you can do

vwS"

  • You can replace " with whatever you would like to wrap by.
  • You can replace w with any other selection operator

Increasing (or decreasing) the memory available to R processes

Use memory.limit(). You can increase the default using this command, memory.limit(size=2500), where the size is in MB. You need to be using 64-bit in order to take real advantage of this.

One other suggestion is to use memory efficient objects wherever possible: for instance, use a matrix instead of a data.frame.

Access PHP variable in JavaScript

You can't, you'll have to do something like

<script type="text/javascript">
   var php_var = "<?php echo $php_var; ?>";
</script>

You can also load it with AJAX

rhino is right, the snippet lacks of a type for the sake of brevity.

Also, note that if $php_var has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.

Animate background image change with jQuery

<style type="text/css">
    #homepage_outter { position:relative; width:100%; height:100%;}
    #homepage_inner { position:absolute; top:0; left:0; z-index:10; width:100%; height:100%;}
    #homepage_underlay { position:absolute; top:0; left:0; z-index:9; width:800px; height:500px; display:none;}
</style>

<script type="text/javascript">
    $(function () {

        $('a').hover(function () {

            $('#homepage_underlay').fadeOut('slow', function () {

                $('#homepage_underlay').css({ 'background-image': 'url("http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/nutrition_background.jpg")' });

                $('#homepage_underlay').fadeIn('slow');
            });

        }, function () {

            $('#homepage_underlay').fadeOut('slow', function () {

                $('#homepage_underlay').css({ 'background-image': 'url("http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/default_background.jpg")' });

                $('#homepage_underlay').fadeIn('slow');
            });


        });

    });

</script>


<body>
<div id="homepage_outter">
    <div id="homepage_inner">
        <a href="#" id="run">run</a>
    </div>
    <div id="homepage_underlay"></div>
</div>

JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

if any problem for JAVA installation version

C:\Where JAVA

will give the location of java it picking up. If you have any path other than your installation, remove those files or rename it (may be as _backup). you will get proper version of java file.

How to add CORS request in header in Angular 5

You can also try the fetch function and the no-cors mode. I sometimes find it easier to configure it than Angular's built-in http module. You can right-click requests in the Chrome Dev tools network tab and copy them in the fetch syntax, which is great.

import { from } from 'rxjs';

// ...

result = from( // wrap the fetch in a from if you need an rxjs Observable
  fetch(
    this.baseurl,
    {
      body: JSON.stringify(data)
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'POST',
      mode: 'no-cors'
    }
  )
);

ImportError: No module named pythoncom

Just go to cmd and install pip install pywin32 pythoncom is part of pywin32 for API window extension.... good luck

Fixed point vs Floating point number

The term ‘fixed point’ refers to the corresponding manner in which numbers are represented, with a fixed number of digits after, and sometimes before, the decimal point. With floating-point representation, the placement of the decimal point can ‘float’ relative to the significant digits of the number. For example, a fixed-point representation with a uniform decimal point placement convention can represent the numbers 123.45, 1234.56, 12345.67, etc, whereas a floating-point representation could in addition represent 1.234567, 123456.7, 0.00001234567, 1234567000000000, etc.

Java 8 LocalDate Jackson format

Simplest and shortest so far:

@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate localDate;

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime localDateTime;

no dependency required with Spring boot >= 2.2+

Bind failed: Address already in use

I was also facing that problem, but I resolved it. Make sure that both the programs for client-side and server-side are on different projects in your IDE, in my case NetBeans. Then assuming you're using localhost, I recommend you to implement both the programs as two different projects.

What is the difference between T(n) and O(n)?

Conclusion: we regard big O, big ? and big O as the same thing.

Why? I will tell the reason below:

Firstly, I will clarify one wrong statement, some people think that we just care the worst time complexity, so we always use big O instead of big ?. I will say this man is bullshitting. Upper and lower bound are used to describe one function, not used to describe the time complexity. The worst time function has its upper and lower bound; the best time function has its upper and lower bound too.

In order to explain clearly the relation between big O and big ?, I will explain the relation between big O and small o first. From the definition, we can easily know that small o is a subset of big O. For example:

T(n)= n^2 + n, we can say T(n)=O(n^2), T(n)=O(n^3), T(n)=O(n^4). But for small o, T(n)=o(n^2) does not meet the definition of small o. So just T(n)=o(n^3), T(n)=o(n^4) are correct for small o. The redundant T(n)=O(n^2) is what? It's big ?!

Generally, we say big O is O(n^2), hardly to say T(n)=O(n^3), T(n)=O(n^4). Why? Because we regard big O as big ? subconsciously.

Similarly, we also regard big O as big ? subconsciously.

In one word, big O, big ? and big O are not the same thing from the definitions, but they are the same thing in our mouth and brain.

How to read all rows from huge table?

The short version is, call stmt.setFetchSize(50); and conn.setAutoCommit(false); to avoid reading the entire ResultSet into memory.

Here's what the docs say:

Getting results based on a cursor

By default the driver collects all the results for the query at once. This can be inconvenient for large data sets so the JDBC driver provides a means of basing a ResultSet on a database cursor and only fetching a small number of rows.

A small number of rows are cached on the client side of the connection and when exhausted the next block of rows is retrieved by repositioning the cursor.

Note:

  • Cursor based ResultSets cannot be used in all situations. There a number of restrictions which will make the driver silently fall back to fetching the whole ResultSet at once.

  • The connection to the server must be using the V3 protocol. This is the default for (and is only supported by) server versions 7.4 and later.-

  • The Connection must not be in autocommit mode. The backend closes cursors at the end of transactions, so in autocommit mode the backend will have closed the cursor before anything can be fetched from it.-

  • The Statement must be created with a ResultSet type of ResultSet.TYPE_FORWARD_ONLY. This is the default, so no code will need to be rewritten to take advantage of this, but it also means that you cannot scroll backwards or otherwise jump around in the ResultSet.-

  • The query given must be a single statement, not multiple statements strung together with semicolons.

Example 5.2. Setting fetch size to turn cursors on and off.

Changing code to cursor mode is as simple as setting the fetch size of the Statement to the appropriate size. Setting the fetch size back to 0 will cause all rows to be cached (the default behaviour).

// make sure autocommit is off
conn.setAutoCommit(false);
Statement st = conn.createStatement();

// Turn use of the cursor on.
st.setFetchSize(50);
ResultSet rs = st.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
   System.out.print("a row was returned.");
}
rs.close();

// Turn the cursor off.
st.setFetchSize(0);
rs = st.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
   System.out.print("many rows were returned.");
}
rs.close();

// Close the statement.
st.close();

Using regular expressions to do mass replace in Notepad++ and Vim

In notepad++

Search

(<option value="\w\w">)\w+">(.+)

Replace with

\1\2

Setting up Vim for Python

Under Linux, What worked for me was John Anderson's (sontek) guide, which you can find at this link. However, I cheated and just used his easy configuration setup from his Git repostiory:

git clone -b vim https://github.com/sontek/dotfiles.git

cd dotfiles

./install.sh vim

His configuration is fairly up to date as of today.

Java - Convert int to Byte Array of 4 Bytes?

public static  byte[] my_int_to_bb_le(int myInteger){
    return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(myInteger).array();
}

public static int my_bb_to_int_le(byte [] byteBarray){
    return ByteBuffer.wrap(byteBarray).order(ByteOrder.LITTLE_ENDIAN).getInt();
}

public static  byte[] my_int_to_bb_be(int myInteger){
    return ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(myInteger).array();
}

public static int my_bb_to_int_be(byte [] byteBarray){
    return ByteBuffer.wrap(byteBarray).order(ByteOrder.BIG_ENDIAN).getInt();
}

What causes HttpHostConnectException?

In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.

How does numpy.histogram() work?

A bin is range that represents the width of a single bar of the histogram along the X-axis. You could also call this the interval. (Wikipedia defines them more formally as "disjoint categories".)

The Numpy histogram function doesn't draw the histogram, but it computes the occurrences of input data that fall within each bin, which in turns determines the area (not necessarily the height if the bins aren't of equal width) of each bar.

In this example:

 np.histogram([1, 2, 1], bins=[0, 1, 2, 3])

There are 3 bins, for values ranging from 0 to 1 (excl 1.), 1 to 2 (excl. 2) and 2 to 3 (incl. 3), respectively. The way Numpy defines these bins if by giving a list of delimiters ([0, 1, 2, 3]) in this example, although it also returns the bins in the results, since it can choose them automatically from the input, if none are specified. If bins=5, for example, it will use 5 bins of equal width spread between the minimum input value and the maximum input value.

The input values are 1, 2 and 1. Therefore, bin "1 to 2" contains two occurrences (the two 1 values), and bin "2 to 3" contains one occurrence (the 2). These results are in the first item in the returned tuple: array([0, 2, 1]).

Since the bins here are of equal width, you can use the number of occurrences for the height of each bar. When drawn, you would have:

  • a bar of height 0 for range/bin [0,1] on the X-axis,
  • a bar of height 2 for range/bin [1,2],
  • a bar of height 1 for range/bin [2,3].

You can plot this directly with Matplotlib (its hist function also returns the bins and the values):

>>> import matplotlib.pyplot as plt
>>> plt.hist([1, 2, 1], bins=[0, 1, 2, 3])
(array([0, 2, 1]), array([0, 1, 2, 3]), <a list of 3 Patch objects>)
>>> plt.show()

enter image description here

How to send a GET request from PHP?

For more advanced GET/POST requests, you can install the CURL library (http://us3.php.net/curl):

$ch = curl_init("REMOTE XML FILE URL GOES HERE"); // such as http://example.com/example.xml
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);

How to sum up elements of a C++ vector?

I found the most easiest way to find sum of all the elements of a vector

#include <iostream>
#include<vector>
using namespace std;

int main()
{
    vector<int>v(10,1);
    int sum=0;
    for(int i=0;i<v.size();i++)
    {
        sum+=v[i];
    }
    cout<<sum<<endl;

}

In this program, I have a vector of size 10 and are initialized by 1. I have calculated the sum by a simple loop like in array.

How to set the focus for a particular field in a Bootstrap modal, once it appears

A little cleaner and more modular solution might be:

$(document).ready(function(){
    $('.modal').success(function() { 
        $('input:text:visible:first').focus();
    });  
});

Or using your ID as an example instead:

$(document).ready(function(){
    $('#modal-content').modal('show').success(function() {
        $('input:text:visible:first').focus();
    });  
});

Hope that helps..

Node.js Error: Cannot find module express

Unless you set Node_PATH, the only other option is to install express in the app directory, like npm install express --save. Express may already be installed but node cannot find it for some reason

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

  1. Check your firewall
  2. Network settings - (Check with network admin, usually they have blocked apple services unknowingly)
  3. Check your system data/time.

I had same sort of issue, I resolved it by getting direct access to internet. Also check Application Loader logs to see at which point it gets stuck.

Populating a razor dropdownlist from a List<object> in MVC

You can separate out your business logic into a viewmodel, so your view has cleaner separation.

First create a viewmodel to store the Id the user will select along with a list of items that will appear in the DropDown.

ViewModel:

public class UserRoleViewModel
{
    // Display Attribute will appear in the Html.LabelFor
    [Display(Name = "User Role")]
    public int SelectedUserRoleId { get; set; }
    public IEnumerable<SelectListItem> UserRoles { get; set; }
}

References:

Inside the controller create a method to get your UserRole list and transform it into the form that will be presented in the view.

Controller:

private IEnumerable<SelectListItem> GetRoles()
{
    var dbUserRoles = new DbUserRoles();
    var roles = dbUserRoles
                .GetRoles()
                .Select(x =>
                        new SelectListItem
                            {
                                Value = x.UserRoleId.ToString(),
                                Text = x.UserRole
                            });

    return new SelectList(roles, "Value", "Text");
}

public ActionResult AddNewUser()
{
    var model = new UserRoleViewModel
                    {
                        UserRoles = GetRoles()
                    };
    return View(model);
}

References:

Now that the viewmodel is created the presentation logic is simplified

View:

@model UserRoleViewModel

@Html.LabelFor(m => m.SelectedUserRoleId)
@Html.DropDownListFor(m => m.SelectedUserRoleId, Model.UserRoles)

References:

This will produce:

<label for="SelectedUserRoleId">User Role</label>
<select id="SelectedUserRoleId" name="SelectedUserRoleId">
    <option value="1">First Role</option>
    <option value="2">Second Role</option>
    <option value="3">Etc...</option>
</select>

javascript, for loop defines a dynamic variable name

I think you could do it by creating parameters in an object maybe?

var myObject = {}; for(var i=0;i<myArray.length;i++) {     myObject[ myArray[i] ]; } 

If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.

Axios Delete request with body and headers?

For those who tried everything above and still don't see the payload with the request - make sure you have:

"axios": "^0.21.1" (not 0.20.0)

Then, the above solutions work

axios.delete("URL", {
      headers: {
        Authorization: `Bearer ${token}`,
      },
      data: {
        var1: "var1",
        var2: "var2"
      },
    })

You can access the payload with

req.body.var1, req.body.var2

Here's the issue:

https://github.com/axios/axios/issues/3335

How to check if a variable is empty in python?

See also this previous answer which recommends the not keyword

How to check if a list is empty in Python?

It generalizes to more than just lists:

>>> a = ""
>>> not a
True

>>> a = []
>>> not a
True

>>> a = 0
>>> not a
True

>>> a = 0.0
>>> not a
True

>>> a = numpy.array([])
>>> not a
True

Notably, it will not work for "0" as a string because the string does in fact contain something - a character containing "0". For that you have to convert it to an int:

>>> a = "0"
>>> not a
False

>>> a = '0'
>>> not int(a)
True

What is a .NET developer?

Most .NET jobs I've run across also either explicitly or implicitly assume some knowledge of SQL-based RDBMSes. While it's not "part of the description", it's usually part of the job.

ReactJS - .JS vs .JSX

JSX isn't standard JavaScript, based to Airbnb style guide 'eslint' could consider this pattern

// filename: MyComponent.js
function MyComponent() {
  return <div />;
}

as a warning, if you named your file MyComponent.jsx it will pass , unless if you edit the eslint rule you can check the style guide here

Change Tomcat Server's timeout in Eclipse

Windows->Preferences->Server

Server Timeout can be specified there.

or another method via the Servers tab here:

http://henneberke.wordpress.com/2009/09/28/fixing-eclipse-tomcat-timeout/

How to sort a Ruby Hash by number value?

No idea how you got your results, since it would not sort by string value... You should reverse a1 and a2 in your example

Best way in any case (as per Mladen) is:

metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" => 10 }
metrics.sort_by {|_key, value| value}
  # ==> [["siteb.com", 9], ["sitec.com", 10], ["sitea.com", 745]]

If you need a hash as a result, you can use to_h (in Ruby 2.0+)

metrics.sort_by {|_key, value| value}.to_h
  # ==> {"siteb.com" => 9, "sitec.com" => 10, "sitea.com", 745}