Programs & Examples On #Thrift

Thrift is a software framework for scalable cross-platform, cross-language services development available from Apache.

Biggest differences of Thrift vs Protocol Buffers?

They both offer many of the same features; however, there are some differences:

  • Thrift supports 'exceptions'
  • Protocol Buffers have much better documentation/examples
  • Thrift has a builtin Set type
  • Protocol Buffers allow "extensions" - you can extend an external proto to add extra fields, while still allowing external code to operate on the values. There is no way to do this in Thrift
  • I find Protocol Buffers much easier to read

Basically, they are fairly equivalent (with Protocol Buffers slightly more efficient from what I have read).

laravel Unable to prepare route ... for serialization. Uses Closure

If none of your routes contain closures, but you are still getting this error, please check

routes/api.php

Laravel has a default auth api route in the above file.

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

which can be commented or replaced with a call to controller method if required.

Rename Oracle Table or View

To rename a table you can use:

RENAME mytable TO othertable;

or

ALTER TABLE mytable RENAME TO othertable;

or, if owned by another schema:

ALTER TABLE owner.mytable RENAME TO othertable;

Interestingly, ALTER VIEW does not support renaming a view. You can, however:

RENAME myview TO otherview;

The RENAME command works for tables, views, sequences and private synonyms, for your own schema only.

If the view is not in your schema, you can recompile the view with the new name and then drop the old view.

(tested in Oracle 10g)

Python 3 Online Interpreter / Shell

Ideone supports Python 2.6 and Python 3

OpenCV NoneType object has no attribute shape

I work with artificially created images,i.e. I create them by myself and then train a neural network on them to perform a certain task. So, I created these images, saved them, but when I tried to open them ( with cv2.imread(...)), I got this error.It turned out that when saving artificially created images you need to add dtype=np.uint8. That resolved the issue for me!

Closing pyplot windows

Please use

plt.show(block=False)
plt.close('all')

Creating a singleton in Python

  • If one wants to have multiple number of instances of the same class, but only if the args or kwargs are different, one can use the third-party python package Handy Decorators (package decorators).
  • Ex.
    1. If you have a class handling serial communication, and to create an instance you want to send the serial port as an argument, then with traditional approach won't work
    2. Using the above mentioned decorators, one can create multiple instances of the class if the args are different.
    3. For same args, the decorator will return the same instance which is already been created.
>>> from decorators import singleton
>>>
>>> @singleton
... class A:
...     def __init__(self, *args, **kwargs):
...         pass
...
>>>
>>> a = A(name='Siddhesh')
>>> b = A(name='Siddhesh', lname='Sathe')
>>> c = A(name='Siddhesh', lname='Sathe')
>>> a is b  # has to be different
False
>>> b is c  # has to be same
True
>>>

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

How to validate date with format "mm/dd/yyyy" in JavaScript?

I pulled most of this code from another post found here. I have modified it for my purposes. This works well for what I need. It may help with your situation.

$(window).load(function() {
  function checkDate() {
    var dateFormat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
    var valDate = $(this).val();
    if ( valDate.match( dateFormat )) {
      $(this).css("border","1px solid #cccccc","color", "#555555", "font-weight", "normal");
      var seperator1 = valDate.split('/');
      var seperator2 = valDate.split('-');

      if ( seperator1.length > 1 ) {
        var splitdate = valDate.split('/');
      } else if ( seperator2.length > 1 ) {
        var splitdate = valDate.split('-');
      }

      var dd = parseInt(splitdate[0]);
      var mm = parseInt(splitdate[1]);
      var yy = parseInt(splitdate[2]);
      var ListofDays = [31,28,31,30,31,30,31,31,30,31,30,31];

      if ( mm == 1 || mm > 2 ) {
        if ( dd > ListofDays[mm - 1] ) {
          $(this).val("");
          $(this).css("border","solid red 1px","color", "red", "font-weight", "bold");
          alert('Invalid Date! You used a date which does not exist in the known calender.');
          return false;
        }
      }

      if ( mm == 2 ) {
       var lyear = false;
        if ( (!(yy % 4) && yy % 100) || !(yy % 400) ){
          lyear = true;
        }

        if ( (lyear==false) && (dd>=29) ) {
          $(this).val("");
          $(this).css("border","solid red 1px","color", "red", "font-weight", "bold");
          alert('Invalid Date! You used Feb 29th for an invalid leap year');
          return false;
        }

        if ( (lyear==true) && (dd>29) ) {
          $(this).val("");
          $(this).css("border","solid red 1px","color", "red", "font-weight", "bold");
          alert('Invalid Date! You used a date greater than Feb 29th in a valid leap year');
          return false;
        }
     }
    } else {
      $(this).val("");
      $(this).css("border","solid red 1px","color", "red", "font-weight", "bold");
      alert('Date format was invalid! Please use format mm/dd/yyyy');
      return false;
    }
  };

  $('#from_date').change( checkDate );
  $('#to_date').change( checkDate );
});

SVG gradient using CSS

Just use in the CSS whatever you would use in a fill attribute. Of course, this requires that you have defined the linear gradient somewhere in your SVG.

Here is a complete example:

_x000D_
_x000D_
rect {_x000D_
    cursor: pointer;_x000D_
    shape-rendering: crispEdges;_x000D_
    fill: url(#MyGradient);_x000D_
}
_x000D_
<svg width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
      <style type="text/css">_x000D_
        rect{fill:url(#MyGradient)}_x000D_
      </style>_x000D_
      <defs>_x000D_
        <linearGradient id="MyGradient">_x000D_
          <stop offset="5%" stop-color="#F60" />_x000D_
          <stop offset="95%" stop-color="#FF6" />_x000D_
        </linearGradient>_x000D_
      </defs>_x000D_
      _x000D_
      <rect width="100" height="50"/>_x000D_
    </svg>
_x000D_
_x000D_
_x000D_

Python style - line continuation with strings?

Since adjacent string literals are automatically joint into a single string, you can just use the implied line continuation inside parentheses as recommended by PEP 8:

print("Why, hello there wonderful "
      "stackoverflow people!")

CSS3 background image transition

You can transition background-image. Use the CSS below on the img element:

-webkit-transition: background-image 0.2s ease-in-out;
transition: background-image 0.2s ease-in-out;

This is supported natively by Chrome, Opera and Safari. Firefox hasn't implemented it yet (bugzil.la). Not sure about IE.

Change Volley timeout duration

To handle Android Volley Timeout you need to use RetryPolicy

RetryPolicy

  • Volley provides an easy way to implement your RetryPolicy for your requests.
  • Volley sets default Socket & ConnectionTImeout to 5 secs for all requests.

RetryPolicy is an interface where you need to implement your logic of how you want to retry a particular request when a timeout happens.

It deals with these three parameters

  • Timeout - Specifies Socket Timeout in millis per every retry attempt.
  • Number Of Retries - Number of times retry is attempted.
  • Back Off Multiplier - A multiplier which is used to determine exponential time set to socket for every retry attempt.

For ex. If RetryPolicy is created with these values

Timeout - 3000 ms, Num of Retry Attempts - 2, Back Off Multiplier - 2.0

Retry Attempt 1:

  • time = time + (time * Back Off Multiplier);
  • time = 3000 + 6000 = 9000ms
  • Socket Timeout = time;
  • Request dispatched with Socket Timeout of 9 Secs

Retry Attempt 2:

  • time = time + (time * Back Off Multiplier);
  • time = 9000 + 18000 = 27000ms
  • Socket Timeout = time;
  • Request dispatched with Socket Timeout of 27 Secs

So at the end of Retry Attempt 2 if still Socket Timeout happens Volley would throw a TimeoutError in your UI Error response handler.

//Set a retry policy in case of SocketTimeout & ConnectionTimeout Exceptions. 
//Volley does retry for you if you have specified the policy.
jsonObjRequest.setRetryPolicy(new DefaultRetryPolicy(5000, 
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

comparing strings in vb

In vb.net you can actually compare strings with =. Even though String is a reference type, in vb.net = on String has been redefined to do a case-sensitive comparison of contents of the two strings.

You can test this with the following code. Note that I have taken one of the values from user input to ensure that the compiler cannot use the same reference for the two variables like the Java compiler would if variables were defined from the same string Literal. Run the program, type "This" and press <Enter>.

Sub Main()
    Dim a As String = New String("This")
    Dim b As String

    b = Console.ReadLine()

    If a = b Then
        Console.WriteLine("They are equal")
    Else
        Console.WriteLine("Not equal")
    End If
    Console.ReadLine()
End Sub

entity framework Unable to load the specified metadata resource

Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.

The following res: (resource) references need to point to your model.

<add name="Entities" connectionString="metadata=
    res://*/Models.WraithNath.co.uk.csdl|
    res://*/Models.WraithNath.co.uk.ssdl|
    res://*/Models.WraithNath.co.uk.msl;

Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).

It also may help to specify the assembly rather than using "//*/".

Worst case, you can check everything (a bit slower but should always find the resource) by using

<add name="Entities" connectionString="metadata=
        res://*/;provider= <!-- ... -->

JAX-RS / Jersey how to customize error handling?

Jersey throws an com.sun.jersey.api.ParamException when it fails to unmarshall the parameters so one solution is to create an ExceptionMapper that handles these types of exceptions:

@Provider
public class ParamExceptionMapper implements ExceptionMapper<ParamException> {
    @Override
    public Response toResponse(ParamException exception) {
        return Response.status(Status.BAD_REQUEST).entity(exception.getParameterName() + " incorrect type").build();
    }
}

How to remove an element from the flow?

There's display: none, but I think that might be a bit more than what you're looking for.

Bootstrap 3 - 100% height of custom div inside column

My solution was to make all the parents 100% and set a specific percentage for each row:

html, body,div[class^="container"] ,.column {
    height: 100%;
}

.row0 {height: 10%;}
.row1 {height: 40%;}
.row2 {height: 50%;}

Is there an XSLT name-of element?

This will give you the current element name (tag name)

<xsl:value-of select ="name(.)"/>

OP-Edit: This will also do the trick:

<xsl:value-of select ="local-name()"/>

Is there any way to install Composer globally on Windows?

Start > Computer : Properties > Change Settings > Advanced > Environment Variables > PATH : Edit [add this string (without "") at the end of line ";C:\<path to php folder>\php5.5.3"].. open cmd and type composer thats it :-)

Using Keras & Tensorflow with AMD GPU

This is an old question, but since I spent the last few weeks trying to figure it out on my own:

  1. OpenCL support for Theano is hit and miss. They added a libgpuarray back-end which appears to still be buggy (i.e., the process runs on the GPU but the answer is wrong--like 8% accuracy on MNIST for a DL model that gets ~95+% accuracy on CPU or nVidia CUDA). Also because ~50-80% of the performance boost on the nVidia stack comes from the CUDNN libraries now, OpenCL will just be left in the dust. (SEE BELOW!) :)
  2. ROCM appears to be very cool, but the documentation (and even a clear declaration of what ROCM is/what it does) is hard to understand. They're doing their best, but they're 4+ years behind. It does NOT NOT NOT work on an RX550 (as of this writing). So don't waste your time (this is where 1 of the weeks went :) ). At first, it appears ROCM is a new addition to the driver set (replacing AMDGPU-Pro, or augmenting it), but it is in fact a kernel module and set of libraries that essentially replace AMDGPU-Pro. (Think of this as the equivalent of Nvidia-381 driver + CUDA some libraries kind of). https://rocm.github.io/dl.html (Honestly I still haven't tested the performance or tried to get it to work with more recent Mesa drivers yet. I will do that sometime.
  3. Add MiOpen to ROCM, and that is essentially CUDNN. They also have some pretty clear guides for migrating. But better yet.
  4. They created "HIP" which is an automagical translator from CUDA/CUDNN to MiOpen. It seems to work pretty well since they lined the API's up directly to be translatable. There are concepts that aren't perfect maps, but in general it looks good.

Now, finally, after 3-4 weeks of trying to figure out OpenCL, etc, I found this tutorial to help you get started quickly. It is a step-by-step for getting hipCaffe up and running. Unlike nVidia though, please ensure you have supported hardware!!!! https://rocm.github.io/hardware.html. Think you can get it working without their supported hardware? Good luck. You've been warned. Once you have ROCM up and running (AND RUN THE VERIFICATION TESTS), here is the hipCaffe tutorial--if you got ROCM up you'll be doing an MNIST validation test within 10 minutes--sweet! https://rocm.github.io/ROCmHipCaffeQuickstart.html

How can I use "." as the delimiter with String.split() in java

When splitting with a string literal delimiter, the safest way is to use the Pattern.quote() method:

String[] words = line.split(Pattern.quote("."));

As described by other answers, splitting with "\\." is correct, but quote() will do this escaping for you.

how to get program files x86 env variable?

Another relevant environment variable is:

%ProgramW6432%

So, on a 64-bit machine running in 32-bit (WOW64) mode:

  • echo %programfiles% ==> C:\Program Files (x86)
  • echo %programfiles(x86)% ==> C:\Program Files (x86)
  • echo %ProgramW6432% ==> C:\Program Files

From Wikipedia:

The %ProgramFiles% variable points to the Program Files directory, which stores all the installed programs of Windows and others. The default on English-language systems is "C:\Program Files". In 64-bit editions of Windows (XP, 2003, Vista), there are also %ProgramFiles(x86)%, which defaults to "C:\Program Files (x86)", and %ProgramW6432%, which defaults to "C:\Program Files". The %ProgramFiles% itself depends on whether the process requesting the environment variable is itself 32-bit or 64-bit (this is caused by Windows-on-Windows 64-bit redirection).

Reference: http://en.wikipedia.org/wiki/Environment_variable

How to use a SQL SELECT statement with Access VBA

Access 2007 can lose the CurrentDb: see http://support.microsoft.com/kb/167173, so in the event of getting "Object Invalid or no longer set" with the examples, use:

Dim db as Database
Dim rs As DAO.Recordset
Set db = CurrentDB
Set rs = db.OpenRecordset("SELECT * FROM myTable")

How is Docker different from a virtual machine?

With a virtual machine, we have a server, we have a host operating system on that server, and then we have a hypervisor. And then running on top of that hypervisor, we have any number of guest operating systems with an application and its dependent binaries, and libraries on that server. It brings a whole guest operating system with it. It's quite heavyweight. Also there's a limit to how much you can actually put on each physical machine.

Enter image description here

Docker containers on the other hand, are slightly different. We have the server. We have the host operating system. But instead a hypervisor, we have the Docker engine, in this case. In this case, we're not bringing a whole guest operating system with us. We're bringing a very thin layer of the operating system, and the container can talk down into the host OS in order to get to the kernel functionality there. And that allows us to have a very lightweight container.

All it has in there is the application code and any binaries and libraries that it requires. And those binaries and libraries can actually be shared across different containers if you want them to be as well. And what this enables us to do, is a number of things. They have much faster startup time. You can't stand up a single VM in a few seconds like that. And equally, taking them down as quickly.. so we can scale up and down very quickly and we'll look at that later on.

Enter image description here

Every container thinks that it’s running on its own copy of the operating system. It’s got its own file system, own registry, etc. which is a kind of a lie. It’s actually being virtualized.

How to return a table from a Stored Procedure?

Where is your problem??

For the stored procedure, just create:

CREATE PROCEDURE dbo.ReadEmployees @EmpID INT
AS
   SELECT *  -- I would *strongly* recommend specifying the columns EXPLICITLY
   FROM dbo.Emp
   WHERE ID = @EmpID

That's all there is.

From your ASP.NET application, just create a SqlConnection and a SqlCommand (don't forget to set the CommandType = CommandType.StoredProcedure)

DataTable tblEmployees = new DataTable();

using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
{
    _cmd.CommandType = CommandType.StoredProcedure;

    _cmd.Parameters.Add(new SqlParameter("@EmpID", SqlDbType.Int));
    _cmd.Parameters["@EmpID"].Value = 42;

    SqlDataAdapter _dap = new SqlDataAdapter(_cmd);

    _dap.Fill(tblEmployees);
}

YourGridView.DataSource = tblEmployees;
YourGridView.DataBind();

and then fill e.g. a DataTable with that data and bind it to e.g. a GridView.

In c, in bool, true == 1 and false == 0?

You neglected to say which version of C you are concerned about. Let's assume it's this one:

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf

As you can see by reading the specification, the standard definitions of true and false are 1 and 0, yes.

If your question is about a different version of C, or about non-standard definitions for true and false, then ask a more specific question.

How to set JAVA_HOME in Mac permanently?

add following

setenv JAVA_HOME /System/Library/Frameworks/JavaVM.framework/Home

in your ~/.login file:

Emulator: ERROR: x86 emulation currently requires hardware acceleration

A more detailed answer for dummies like me:

  1. Open the SDK manager open sdk
  2. Select the SDK Tools tab. SDK tools tab
  3. Download – Make sure that intel x86 Emulator Accelerator (HAXM) is downloaded. haxm download
  4. Install – Now that HAXM is downloaded, make sure it is installed. In the SDK window it will show you where the SDK is located on your computer: get SDK location Click/tap 3 times quickly to highlight this text and copy the folder location. Open the file explorer and paste in the file location. From here you can search “hax” to find the folder location for HAXM stuff. Once a file comes up in the search results, right click and select “open file location”. For me the location was C:\Users\Datu1\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelerated_Execution_Manager . Find the file intelhaxm-android.exe and open/run it. haxm-android.exe file Follow the instructions when it runs. You may wish to run haxm_check as an administrator (it’s in this same folder), but it may or may not work for you. The surefire way to tell if you can run hardware acceleration and if it’s enabled is to go to your computer’s bios settings from the startup menu.
  5. BIOS settings – Make sure hardware acceleration is enabled in your BIOS settings. The way to do this may vary a bit from system to system. You may need to press f10 or esc on startup. But with most (updated) Windows 10 computers you can access the BIOS settings by doing the following: type “advanced startup” in the Windows search bar; click on “change advanced startup uptions:” when it comes up. Click “Restart now”. After your computer restarts click on Troubleshoot. Troubleshoot Windows startup Click advanced options >firmware settings, then restart to change EUFI firmware settings. Wait for the restart then select the menu option for bios settings. With Intel processors the steps will be as follows or similar: Press the right arrow to go to the Configuration tab. Arrow down to Intel Virtual/Virtualizaion Technology and turn it on (should say Enabled). Enable virtualization in bios Exit and save changes.

  6. If Virtual Technology was previously disabled in your bios settings You will need to run the intelhaxm-android.exe file now to install haxm.

  7. Try restarting Android Studio and running your emulator again. If it’s still not working, restart your computer and try again, it should work.

NOTE: if you have Windows Hyper-V turned on this will cause you to not be able to run haxm. If you are having an issue with Hyper-V, make sure it is turned off in your settings: search in the Windows bar for “hyper”; the search result should take you to “Turn Windows features on or off”. Then make sure all the Hyper-V boxes are unchecked.
disable hyper-v

Min and max value of input in angular4 application

Here is the solution :

This is kind of hack , but it will work

<input type="number" 
placeholder="Charge" 
[(ngModel)]="rateInput" 
name="rateInput"
pattern="^$|^([0-9]|[1-9][0-9]|[1][0][0])?"
required 
#rateInput2 = "ngModel">

<div *ngIf="rateInput2.errors && (rateInput2.dirty || rateInput2.touched)"
    <div [hidden]="!rateInput2.errors.pattern">
        Number should be between 0 and 100
    </div>
</div>

Here is the link to the plunker , please have a look.

How might I force a floating DIV to match the height of another floating DIV?

Here is a jQuery plugin to set the heights of multiple divs to be the same. And below is the actual code of the plugin.

$.fn.equalHeights = function(px) {
$(this).each(function(){
var currentTallest = 0;
$(this).children().each(function(i){
    if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
        });
    if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
        // for ie6, set height since min-height isn't supported
    if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
        $(this).children().css({'min-height': currentTallest}); 
    });
    return this;
};

Is it possible to set transparency in CSS3 box-shadow?

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

_x000D_
_x000D_
div {_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    line-height: 50px;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
  box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_

Executing a command stored in a variable from PowerShell

Here is yet another way without Invoke-Expression but with two variables (command:string and parameters:array). It works fine for me. Assume 7z.exe is in the system path.

$cmd = '7z.exe'
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'

& $cmd $prm

If the command is known (7z.exe) and only parameters are variable then this will do

$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'

& 7z.exe $prm

BTW, Invoke-Expression with one parameter works for me, too, e.g. this works

$cmd = '& 7z.exe a -tzip "c:\temp\with space\test2.zip" "C:\TEMP\with space\changelog"'

Invoke-Expression $cmd

P.S. I usually prefer the way with a parameter array because it is easier to compose programmatically than to build an expression for Invoke-Expression.

How do I create batch file to rename large number of files in a folder?

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET old=Vacation2010
SET new=December
for /f "tokens=*" %%f in ('dir /b *.jpg') do (
  SET newname=%%f
  SET newname=!newname:%old%=%new%!
  move "%%f" "!newname!"
)

What this does is it loops over all .jpg files in the folder where the batch file is located and replaces the Vacation2010 with December inside the filenames.

MySQL Check if username and password matches in Database

Instead of selecting all the columns in count count(*) you can limit count for one column count(UserName).

You can limit the whole search to one row by using Limit 0,1

SELECT COUNT(UserName)
  FROM TableName
 WHERE UserName = 'User' AND
       Password = 'Pass'
 LIMIT 0, 1

"An access token is required to request this resource" while accessing an album / photo with Facebook php sdk

Well, you are having a valid access token to access your information and not others( this is because you got logged in and you have given permission to access your information). But the picture owner has not done the same (logged in + permission ) and so you are getting a violation error.

To obtain permission see this link and decide what kind of informations you want from any user and decide the permissions. Later on embed this in your code. (In the login function call)

Thanks

VBA setting the formula for a cell

If Cells(1, 1).Formula gives a 1004 error, like in my case, changes it to:

Cells(1, 1).FormulaLocal

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

Make sure you have closed your MSAccess file before running the java program.

How do I set a Windows scheduled task to run in the background?

Assuming the application you are attempting to run in the background is CLI based, you can try calling the scheduled jobs using Hidden Start

Also see: http://www.howtogeek.com/howto/windows/hide-flashing-command-line-and-batch-file-windows-on-startup/

.attr('checked','checked') does not work

It works, but

$('input[name="myname"][checked]').val()

will return the value of the first element with attribute checked. And the a radio button still has this attribute (and it comes before the b button). Selecting b does not remove the checked attribute from a.

You can use jQuery's :checked:

$('input[name="myname"]:checked').val()

DEMO


Further notes:

  • Using $('b').attr('checked',true); is enough.
  • As others mentioned, don't use inline event handlers, use jQuery to add the event handler.

Creating a JavaScript cookie on a domain and reading it across sub domains

Here is a working example :

document.cookie = "testCookie=cookieval; domain=." + 
location.hostname.split('.').reverse()[1] + "." + 
location.hostname.split('.').reverse()[0] + "; path=/"

This is a generic solution that takes the root domain from the location object and sets the cookie. The reversing is because you don't know how many subdomains you have if any.

How to dynamic filter options of <select > with jQuery?

Slightly different to all the other but I think this is the most simple:

$(document).ready(function(){

    var $this, i, filter,
        $input = $('#my_other_id'),
        $options = $('#my_id').find('option');

    $input.keyup(function(){
        filter = $(this).val();
        i = 1;
        $options.each(function(){
            $this = $(this);
            $this.removeAttr('selected');
            if ($this.text().indexOf(filter) != -1) {
                $this.show();
                if(i == 1){
                    $this.attr('selected', 'selected');
                }
                i++;
            } else {
                $this.hide();
            }
        });
    });

});

Copy an entire worksheet to a new worksheet in Excel 2010

ThisWorkbook.Worksheets("Master").Sheet1.Cells.Copy _
    Destination:=newWorksheet.Cells

The above will copy the cells. If you really want to duplicate the entire sheet, then I'd go with @brettdj's answer.

Command for restarting all running docker containers?

Just run

docker restart $(docker ps -q)

Update

For Docker 1.13.1 use docker restart $(docker ps -a -q) as in answer lower.

PHP Error: Function name must be a string

It will be $_COOKIE['CaptchaResponseValue'], not $_COOKIE('CaptchaResponseValue')

Visual Studio : short cut Key : Duplicate Line

In Visual Studio 2013 you can use Ctrl+C+V

Javascript search inside a JSON object

You can simply save your data in a variable and use find(to get single object of records) or filter(to get single array of records) method of JavaScript.

For example :-

let data = {
 "list": [
   {"name":"my Name","id":12,"type":"car owner"},
   {"name":"my Name2","id":13,"type":"car owner2"},
   {"name":"my Name4","id":14,"type":"car owner3"},
   {"name":"my Name4","id":15,"type":"car owner5"}
]}

and now use below command onkeyup or enter

to get single object

data.list.find( record => record.name === "my Name")

to get single array object

data.list.filter( record => record.name === "my Name")

Setting up a git remote origin

You can include the branch to track when setting up remotes, to keep things working as you might expect:

git remote add --track master origin [email protected]:group/project.git   # git
git remote add --track master origin [email protected]:group/project.git   # git w/IP
git remote add --track master origin http://github.com/group/project.git   # http
git remote add --track master origin http://172.16.1.100/group/project.git # http w/IP
git remote add --track master origin /Volumes/Git/group/project/           # local
git remote add --track master origin G:/group/project/                     # local, Win

This keeps you from having to manually edit your git config or specify branch tracking manually.

Uncaught TypeError: data.push is not a function

you can use push method only if the object is an array:

var data = new Array();
data.push({"country": "IN"}).

OR

data['country'] = "IN"

if it's just an object you can use

data.country = "IN";

Update a column value, replacing part of a string

Try this...

update [table_name] set [field_name] = 
replace([field_name],'[string_to_find]','[string_to_replace]');

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

The database must have a name (example DB1), try this one:

OracleConnection con = new OracleConnection("data source=DB1;user id=fastecit;password=fastecit"); 

In case the TNS is not defined you can also try this one:

OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DB1)));
User Id=fastecit;Password=fastecit"); 

Efficient evaluation of a function at every cell of a NumPy array

A similar question is: Mapping a NumPy array in place. If you can find a ufunc for your f(), then you should use the out parameter.

How to multiply all integers inside list

Try a list comprehension:

l = [x * 2 for x in l]

This goes through l, multiplying each element by two.

Of course, there's more than one way to do it. If you're into lambda functions and map, you can even do

l = map(lambda x: x * 2, l)

to apply the function lambda x: x * 2 to each element in l. This is equivalent to:

def timesTwo(x):
    return x * 2

l = map(timesTwo, l)

Note that map() returns a map object, not a list, so if you really need a list afterwards you can use the list() function afterwards, for instance:

l = list(map(timesTwo, l))

Thanks to Minyc510 in the comments for this clarification.

Configure WAMP server to send email

I used Mercury/32 and Pegasus Mail to get the mail() functional. It works great too as a mail server if you want an email address ending with your domain name.

how to get current month and year

using System.Globalization;

LblMonth.Text = DateTime.Now.Month.ToString();

DateTimeFormatInfo dinfo = new DateTimeFormatInfo();
int month = Convert.ToInt16(LblMonth.Text);

LblMonth.Text = dinfo.GetMonthName(month);

what is .subscribe in angular?

subscribe() -Invokes an execution of an Observable and registers Observer handlers for notifications it will emit. -Observable- representation of any set of values over any amount of time.

Converting Stream to String and back...what are we missing?

Try this.

string output1 = Encoding.ASCII.GetString(byteArray, 0, byteArray.Length)

How to create a file in Ruby

Use:

File.open("out.txt", [your-option-string]) {|f| f.write("write your stuff here") }

where your options are:

  • r - Read only. The file must exist.
  • w - Create an empty file for writing.
  • a - Append to a file.The file is created if it does not exist.
  • r+ - Open a file for update both reading and writing. The file must exist.
  • w+ - Create an empty file for both reading and writing.
  • a+ - Open a file for reading and appending. The file is created if it does not exist.

In your case, 'w' is preferable.

OR you could have:

out_file = File.new("out.txt", "w")
#...
out_file.puts("write your stuff here")
#...
out_file.close

What is Dependency Injection?

What is the purpose of DI?

The purpose of Dependency Injection is to reduce coupling in your application to make it more flexible and easier to test.

How does it benefit?

Objects don't have hard coded dependencies. If you need to change the implementation of a dependency, all you have to do is Inject a different type of Object.

How does it implemented?

There are various methods of Dependency Injection. Check out the Wikipedia article to see examples of each. Once you understand those, you can start investigating the various Dependency Injection frameworks.

How to generate and auto increment Id with Entity Framework

This is a guess :)

Is it because the ID is a string? What happens if you change it to int?

I mean:

 public int Id { get; set; }

How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

The below code will work for Sql Server 2000/2005/2008

CREATE FUNCTION fnConcatVehicleCities(@VehicleId SMALLINT)
RETURNS VARCHAR(1000) AS
BEGIN
  DECLARE @csvCities VARCHAR(1000)
  SELECT @csvCities = COALESCE(@csvCities + ', ', '') + COALESCE(City,'')
  FROM Vehicles 
  WHERE VehicleId = @VehicleId 
  return @csvCities
END

-- //Once the User defined function is created then run the below sql

SELECT VehicleID
     , dbo.fnConcatVehicleCities(VehicleId) AS Locations
FROM Vehicles
GROUP BY VehicleID

Rolling or sliding window iterator?

This seems tailor-made for a collections.deque since you essentially have a FIFO (add to one end, remove from the other). However, even if you use a list you shouldn't be slicing twice; instead, you should probably just pop(0) from the list and append() the new item.

Here is an optimized deque-based implementation patterned after your original:

from collections import deque

def window(seq, n=2):
    it = iter(seq)
    win = deque((next(it, None) for _ in xrange(n)), maxlen=n)
    yield win
    append = win.append
    for e in it:
        append(e)
        yield win

In my tests it handily beats everything else posted here most of the time, though pillmuncher's tee version beats it for large iterables and small windows. On larger windows, the deque pulls ahead again in raw speed.

Access to individual items in the deque may be faster or slower than with lists or tuples. (Items near the beginning are faster, or items near the end if you use a negative index.) I put a sum(w) in the body of my loop; this plays to the deque's strength (iterating from one item to the next is fast, so this loop ran a a full 20% faster than the next fastest method, pillmuncher's). When I changed it to individually look up and add items in a window of ten, the tables turned and the tee method was 20% faster. I was able to recover some speed by using negative indexes for the last five terms in the addition, but tee was still a little faster. Overall I would estimate that either one is plenty fast for most uses and if you need a little more performance, profile and pick the one that works best.

Appending to 2D lists in Python

Came here to see how to append an item to a 2D array, but the title of the thread is a bit misleading because it is exploring an issue with the appending.

The easiest way I found to append to a 2D list is like this:

list=[[]]

list.append((var_1,var_2))

This will result in an entry with the 2 variables var_1, var_2. Hope this helps!

Use StringFormat to add a string to a WPF XAML binding

Here's an alternative that works well for readability if you have the Binding in the middle of the string or multiple bindings:

<TextBlock>
  <Run Text="Temperature is "/>
  <Run Text="{Binding CelsiusTemp}"/>
  <Run Text="°C"/>  
</TextBlock>

<!-- displays: 0°C (32°F)-->
<TextBlock>
  <Run Text="{Binding CelsiusTemp}"/>
  <Run Text="°C"/>
  <Run Text=" ("/>
  <Run Text="{Binding Fahrenheit}"/>
  <Run Text="°F)"/>
</TextBlock>

Scripting Language vs Programming Language

Back when the world was young and in the PC world you chose from .exe or .bat, the delineation was simple. Unix systems have always had shell scripts (/bin/sh, /bin/csh, /bin/ksh, etc) and Compiled languages (C/C++/Fortran).

To differentiate roles and responsibilities, the compiled languages (often referred to as 3rd Generation Languages) were seen a 'programming' languages and 'scripting' languages were seen as those that invoked an interpreter (often referred to as 4th Generation Languages). Scripting languages were often used as 'glue' to connect between multiple commands/compiled programs so that the user didn't have to worry about a set of steps in order to carry out their task - they developed a single file, that delineated what steps they wanted to accomplish, and this became a 'script' for anyone to follow.

Various people/groups wrote new interpreters to solve a specific problem domain. awk is one of the better-known ones, and it was used mostly for pattern matching and applying a series of data transforms on input. It worked well, but had a limited problem domain. The expansion of that domain was all but impossible because the source code was unavailable. Perl (Larry Wall, principle author/architect) tool scripting to the next level - and developed an interpreter that not only allowed the user to run system commands, manipulate input and output data, supported typeless variables, but also to access Unix system level APIs as functions from within the scripts themselves. It was probably one of the first widely used high-level scripting languages. It is with Perl (IMHO) that scripting languages crossed the arbitrary line and added the capabilities of programming languages.

Your question was specifically about Python. Because the python interpreter runs against a text file containing the python code, and that the python code can run anywhere that there is a python interpreter, I would say that it is a scripting language (in the same vein as Perl). You do not need to recompile the user python command file for each different OS/CPU Architecture (as you would with C/C++/Fortran), making it significantly more portable and easier to use.

Credit for this answer goes to Jerrold (Jerry) Heyman. Original thread: https://www.researchgate.net/post/Is_Python_a_Programming_language_or_Scripting_Language

Delete terminal history in Linux

You can clear your bash history like this:

history -cw

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

None of the solutions here solves my problem - only when I install Windows Update for universal C runtime.

Now CMake is working and no more link hangs from Visual Studio.

Update for Universal C Runtime in Windows

Using PHP to upload file and add the path to MySQL database

mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;

These are deprecated use the following..

 // Connects to your Database
            $link = mysqli_connect("localhost", "root", "", "");

and to insert data use the following

 $sql = "INSERT INTO  Table-Name (Column-Name)
VALUES ('$filename')" ;

What issues should be considered when overriding equals and hashCode in Java?

The theory (for the language lawyers and the mathematically inclined):

equals() (javadoc) must define an equivalence relation (it must be reflexive, symmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null) must always return false.

hashCode() (javadoc) must also be consistent (if the object is not modified in terms of equals(), it must keep returning the same value).

The relation between the two methods is:

Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().

In practice:

If you override one, then you should override the other.

Use the same set of fields that you use to compute equals() to compute hashCode().

Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. An example:

public class Person {
    private String name;
    private int age;
    // ...

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
            // if deriving: appendSuper(super.hashCode()).
            append(name).
            append(age).
            toHashCode();
    }

    @Override
    public boolean equals(Object obj) {
       if (!(obj instanceof Person))
            return false;
        if (obj == this)
            return true;

        Person rhs = (Person) obj;
        return new EqualsBuilder().
            // if deriving: appendSuper(super.equals(obj)).
            append(name, rhs.name).
            append(age, rhs.age).
            isEquals();
    }
}

Also remember:

When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, Hashtable, or WeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits.

Download file from web in Python 3

from urllib import request

def get(url):
    with request.urlopen(url) as r:
        return r.read()


def download(url, file=None):
    if not file:
        file = url.split('/')[-1]
    with open(file, 'wb') as f:
        f.write(get(url))

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

What worked with me, in the Storyboard, go to the Navigation Controller, select the navigation bar, click on the Attributes Inspector, then change the style from default to black. That's it!

Object passed as parameter to another class, by value or reference?

Objects will be passed by reference irrespective of within methods of same class or another class. Here is a modified version of same sample code to help you understand. The value will be changed to 'xyz.'

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class Employee
    {
        public string Name { get; set; }
    }

    public class MyClass
    {
        public Employee EmpObj;

        public void SetObject(Employee obj)
        {
            EmpObj = obj;
        }
    }

    public class Program
    {
       static void Main(string[] args)
        {
            Employee someTestObj = new Employee();
            someTestObj.Name = "ABC";

            MyClass cls = new MyClass();
            cls.SetObject(someTestObj);

            Console.WriteLine("Changing Emp Name To xyz");
            someTestObj.Name = "xyz";

            Console.WriteLine("Accessing Assigned Emp Name");
            Console.WriteLine(cls.EmpObj.Name); 

           Console.ReadLine();
       }       
    }
 }

Is it possible to set the equivalent of a src attribute of an img tag in CSS?

A collection of possible methods to set images from CSS


CSS2's :after pseudo-element or the newer syntax ::after from CSS3 along with the content: property:

First W3C Recommendation: Cascading Style Sheets, level 2 CSS2 Specification 12 May 1998
Latest W3C Recommendation: Selectors Level 3 W3C Recommendation 29 September 2011

This method appends content just after an element's document tree content.

Note: some browsers experimentally render the content property directly over some element selectors disregarding even the latest W3C recommendation that defines:

Applies to: :before and :after pseudo-elements

CSS2 syntax (forward-compatible):

.myClass:after {
  content: url("somepicture.jpg");
}

CSS3 Selector:

.myClass::after {
  content: url("somepicture.jpg");
}

Default rendering: Original Size (does not depend on explicit size declaration)

This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.

but even at the time of this writing, behaviour with a <IMG> tag is still not defined and although it can be used in a hacked and non standards compliant way, usage with <img> is not recommended!

Great candidate method, see conclusions...



CSS1's background-image: property:

First W3C Recommendation: Cascading Style Sheets, level 1 17 Dec 1996

This property sets the background image of an element. When setting a background image, one should also set a background color that will be used when the image is unavailable. When the image is available, it is overlaid on top of the background color.

This property has been around from the beginning of CSS and nevertheless it deserve a glorious mention.

Default rendering: Original Size (cannot be scaled, only positioned)

However,

CSS3's background-size: property improved on it by allowing multiple scaling options:

Latest W3C Status: Candidate Recommendation CSS Backgrounds and Borders Module Level 3 9 September 2014

[length> | <percentage> | auto ]{1,2} | cover | contain

But even with this property, it depends on container size.

Still a good candidate method, see conclusions...



CSS2's list-style: property along with display: list-item:

First W3C Recommendation: Cascading Style Sheets, level 2 CSS2 Specification 12 May 1998

list-style-image: property sets the image that will be used as the list item marker (bullet)

The list properties describe basic visual formatting of lists: they allow style sheets to specify the marker type (image, glyph, or number)

display: list-item — This value causes an element (e.g., <li> in HTML) to generate a principal block box and a marker box.

.myClass {
    display: list-item;
    list-style-position: inside;
    list-style-image: url("someimage.jpg");
}

Shorthand CSS: (<list-style-type> <list-style-position> <list-style-image>)

.myClass {
    display: list-item;
    list-style: square inside url("someimage.jpg");
}

Default rendering: Original Size (does not depend on explicit size declaration)

Restrictions:

  • Inheritance will transfer the 'list-style' values from OL and UL elements to LI elements. This is the recommended way to specify list style information.

  • They do not allow authors to specify distinct style (colors, fonts, alignment, etc.) for the list marker or adjust its position

This method is also not suitable for the <img> tag as the conversion cannot be made between element types, and here's the limited, non compliant hack that doesn't work on Chrome.

Good candidate method, see conclusions...



CSS3's border-image: property recommendation:

Latest W3C Status: Candidate Recommendation CSS Backgrounds and Borders Module Level 3 9 September 2014

A background-type method that relies on specifying sizes in a rather peculiar manner (not defined for this use case) and fallback border properties so far (eg. border: solid):

Note that, even though they never cause a scrolling mechanism, outset images may still be clipped by an ancestor or by the viewport.

This example illustrates the image being composed only as a bottom-right corner decoration:

.myClass {
    border: solid;
    border-width: 0 480px 320px 0;
    border-image: url("http://i.imgur.com/uKnMvyp.jpg") 0 100% 100% 0;
}

Applies to: All elements, except internal table elements when border-collapse: collapse

Still it can't change an <img>'s tag src (but here's a hack), instead we can decorate it:

_x000D_
_x000D_
.myClass {_x000D_
    border: solid;_x000D_
    border-width: 0 96px 96px 0;_x000D_
    border-image: url("http://upload.wikimedia.org/wikipedia/commons/9/95/Christmas_bell_icon_1.png") _x000D_
                  0 100% 100% 0;_x000D_
}
_x000D_
<img width="300" height="120" _x000D_
     src="http://fc03.deviantart.net/fs71/f/2012/253/b/0/merry_christmas_card_by_designworldwide-d5e9746.jpg" _x000D_
     class="myClass"
_x000D_
_x000D_
_x000D_

Good candidate method to be considered after standards propagate.



CSS3's element() notation working draft is worth a mention also:

Note: The element() function only reproduces the appearance of the referenced element, not the actual content and its structure.

<div id="img1"></div>

<img id="pic1" src="http://i.imgur.com/uKnMvyp.jpg" class="hide" alt="wolf">
<img id="pic2" src="http://i.imgur.com/TOUfCfL.jpg" class="hide" alt="cat">

We'll use the rendered contents of one of the two hidden images to change the image background in #img1 based on the ID Selector via CSS:

#img1 {
    width: 480px; 
    height: 320px; 
    background: -moz-element(#pic1) no-repeat;
    background-size: 100% 100%;
}

.hide {display: none}

Notes: It's experimental and only works with the -moz prefix in Firefox and only over background or background-image properties, also needs sizes specified.


Conclusions

  1. Any semantic content or structural information goes in HTML.
  2. Styling and presentational information goes in CSS.
  3. For SEO purposes, don't hide meaningful images in CSS.
  4. Background graphics are usually disabled when printing.
  5. Custom tags could be used and styled from CSS, but primitive versions of Internet Explorer do not understand](IE not styling HTML5 tags (with shiv)) without Javascript or CSS guidance.
  6. SPA's (Single Page Applications), by design, usually incorporate images in the background

Having said that, let's explore HTML tags fit for image display:

The <li> element [HTML4.01+]

Perfect usecase of the list-style-image with display: list-item method.

The <li> element, can be empty, allows flow content and it's even permitted to omit the </li> end tag.

_x000D_
_x000D_
.bulletPics > li {display: list-item}_x000D_
#img1 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/4/4d/Nuvola_erotic.png")}_x000D_
#img2 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/7/74/Globe_icon_2014-06-26_22-09.png")}_x000D_
#img3 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/c/c4/Kiwi_fruit.jpg")}
_x000D_
<ul class="bulletPics">_x000D_
    <li id="img1">movie</li>_x000D_
    <li id="img2">earth</li>_x000D_
    <li id="img3">kiwi</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Limitations: hard to style (width: or float: might help)

The <figure> element [HTML5+]

The figure element represents some flow content, optionally with a caption, that is self-contained (like a complete sentence) and is typically referenced as a single unit from the main flow of the document.

The element is valid with no content, but is recommended to contain a <figcaption>.

The element can thus be used to annotate illustrations, diagrams, photos, code listings, etc.

Default rendering: the element is right aligned, with both left and right padding!

The <object> element [HTML4+]

To include images, authors may use the OBJECT element or the IMG element.

The data attribute is required and can have a valid MIME type as a value!

<object data="data:x-image/x,"></object>

Note: a trick to make use of the <object> tag from CSS would be to set a custom valid MimeType x-image/x followed by no data (value has no data after the required comma ,)

Default rendering: 300 x 150px, but size can be specified either in HTML or CSS.

The <SVG> tag

Needs a SVG capable browser and has a <image> element for raster images

The <canvas> element [HTML5+].

The width attribute defaults to 300, and the height attribute defaults to 150.

The <input> element with type="image"

Limitations:

... the element is expected to appear button-like to indicate that the element is a button.

which Chrome follows and renders a 4x4px empty square when no text

Partial solution, set value=" ":

<input type="image" id="img1" value=" ">

Also watch out for the upcoming <picture> element in HTML5.1, currently a working draft.

An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

Eclipse has an error log. There you will see the complete stack trace. In my case it seems to be caused by a bad jar file combined with the java.util.zip libs not throwing a proper exception, just a NullPointerException.

How can I check if some text exist or not in the page using Selenium?

In python, you can simply check as follow:

# on your `setUp` definition.
from selenium import webdriver
self.selenium = webdriver.Firefox()

self.assertTrue('your text' in self.selenium.page_source)

How to display all methods of an object?

You can use Object.getOwnPropertyNames() to get all properties that belong to an object, whether enumerable or not. For example:

console.log(Object.getOwnPropertyNames(Math));
//-> ["E", "LN10", "LN2", "LOG2E", "LOG10E", "PI", ...etc ]

You can then use filter() to obtain only the methods:

console.log(Object.getOwnPropertyNames(Math).filter(function (p) {
    return typeof Math[p] === 'function';
}));
//-> ["random", "abs", "acos", "asin", "atan", "ceil", "cos", "exp", ...etc ]

In ES3 browsers (IE 8 and lower), the properties of built-in objects aren't enumerable. Objects like window and document aren't built-in, they're defined by the browser and most likely enumerable by design.

From ECMA-262 Edition 3:

Global Object
There is a unique global object (15.1), which is created before control enters any execution context. Initially the global object has the following properties:

• Built-in objects such as Math, String, Date, parseInt, etc. These have attributes { DontEnum }.
• Additional host defined properties. This may include a property whose value is the global object itself; for example, in the HTML document object model the window property of the global object is the global object itself.

As control enters execution contexts, and as ECMAScript code is executed, additional properties may be added to the global object and the initial properties may be changed.

I should point out that this means those objects aren't enumerable properties of the Global object. If you look through the rest of the specification document, you will see most of the built-in properties and methods of these objects have the { DontEnum } attribute set on them.


Update: a fellow SO user, CMS, brought an IE bug regarding { DontEnum } to my attention.

Instead of checking the DontEnum attribute, [Microsoft] JScript will skip over any property in any object where there is a same-named property in the object's prototype chain that has the attribute DontEnum.

In short, beware when naming your object properties. If there is a built-in prototype property or method with the same name then IE will skip over it when using a for...in loop.

Best method to download image from url in Android

            public void DownloadImageFromPath(String path){
            InputStream in =null;
            Bitmap bmp=null;
             ImageView iv = (ImageView)findViewById(R.id.img1);
             int responseCode = -1;
            try{

                 URL url = new URL(path);//"http://192.xx.xx.xx/mypath/img1.jpg
                 HttpURLConnection con = (HttpURLConnection)url.openConnection();
                 con.setDoInput(true);
                 con.connect();
                 responseCode = con.getResponseCode();
                 if(responseCode == HttpURLConnection.HTTP_OK)
                 {
                     //download 
                     in = con.getInputStream();
                     bmp = BitmapFactory.decodeStream(in);
                     in.close();
                     iv.setImageBitmap(bmp);
                 }

            }
            catch(Exception ex){
                Log.e("Exception",ex.toString());
            }
        }

How to access single elements in a table in R

?"[" pretty much covers the various ways of accessing elements of things.

Under usage it lists these:

x[i]
x[i, j, ... , drop = TRUE]
x[[i, exact = TRUE]]
x[[i, j, ..., exact = TRUE]]
x$name
getElement(object, name)

x[i] <- value
x[i, j, ...] <- value
x[[i]] <- value
x$i <- value

The second item is sufficient for your purpose

Under Arguments it points out that with [ the arguments i and j can be numeric, character or logical

So these work:

data[1,1]
data[1,"V1"]

As does this:

data$V1[1]

and keeping in mind a data frame is a list of vectors:

data[[1]][1]
data[["V1"]][1]

will also both work.

So that's a few things to be going on with. I suggest you type in the examples at the bottom of the help page one line at a time (yes, actually type the whole thing in one line at a time and see what they all do, you'll pick up stuff very quickly and the typing rather than copypasting is an important part of helping to commit it to memory.)

How to tell 'PowerShell' Copy-Item to unconditionally copy files

From the documentation (help copy-item -full):

-force <SwitchParameter>
    Allows cmdlet to override restrictions such as renaming existing files as long as security is not compromised.

    Required?                    false
    Position?                    named
    Default value                False
    Accept pipeline input?       false
    Accept wildcard characters?  false

Is not an enclosing class Java

One thing I didn't realize at first when reading the accepted answer was that making an inner class static is basically the same thing as moving it to its own separate class.

Thus, when getting the error

xxx is not an enclosing class

You can solve it in either of the following ways:

  • Add the static keyword to the inner class, or
  • Move it out to its own separate class.

Displaying tooltip on mouse hover of a text

I would also like to add something here that if you load desired form that contain tooltip controll before the program's run then tool tip control on that form will not work as described below...

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        objfrmmain = new Frm_Main();
        Showtop();//this is procedure in program.cs to load an other form, so if that contain's tool tip control then it will not work
        Application.Run(objfrmmain);


    }

so I solved this problem by puting following code in Fram_main_load event procedure like this

    private void Frm_Main_Load(object sender, EventArgs e)
    {
        Program.Showtop();
    }

Excluding files/directories from Gulp task

Quick answer

On src, you can always specify files to ignore using "!".

Example (you want to exclude all *.min.js files on your js folder and subfolder:

gulp.src(['js/**/*.js', '!js/**/*.min.js'])

You can do it as well for individual files.

Expanded answer:

Extracted from gulp documentation:

gulp.src(globs[, options])

Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.

glob refers to node-glob syntax or it can be a direct file path.

So, looking to node-glob documentation we can see that it uses the minimatch library to do its matching.

On minimatch documentation, they point out the following:

if the pattern starts with a ! character, then it is negated.

And that is why using ! symbol will exclude files / directories from a gulp task

GitHub "fatal: remote origin already exists"

The concept of remote is simply the URL of your remote repository.

The origin is an alias pointing to that URL. So instead of writing the whole URL every single time we want to push something to our repository, we just use this alias and run:

git push -u origin master

Telling to git to push our code from our local master branch to the remote origin repository.

Whenever we clone a repository, git creates this alias for us by default. Also whenever we create a new repository, we just create it our self.

Whatever the case it is, we can always change this name to anything we like, running this:

git remote rename [current-name] [new-name]

Since it is stored on the client side of the git application (on our machine) changing it will not affect anything in our development process, neither at our remote repository. Remember, it is only a name pointing to an address.

The only thing that changes here by renaming the alias, is that we have to declare this new name every time we push something to our repository.

git push -u my-remote-alias master

Obviously a single name can not point to two different addresses. That's why you get this error message. There is already an alias named origin at your local machine. To see how many aliases you have and what are they, you can initiate this command:

git remote -v

This will show you all the aliases you have plus the corresponding URLs.

You can remove them as well if you like running this:

git remote rm my-remote-alias

So in brief:

  • find out what do you have already,
  • remove or rename them,
  • add your new aliases.

Happy coding.

Groovy String to Date

Below is the way we are going within our developing application.

import java.text.SimpleDateFormat

String newDateAdded = "2018-11-11T09:30:31"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
Date dateAdded = dateFormat.parse(newDateAdded)

println(dateAdded)

The output looks like

Sun Nov 11 09:30:31 GMT 2018

In your example, we could adjust a bit to meet your need. If I were you, I will do:

String datePattern = "d/M/yyyy H:m:s"
String theDate = "28/09/2010 16:02:43"
SimpleDateFormat df = new SimpleDateFormat(datePattern)
println df.parse(theDate)

I hope this would help you much.

How to resolve this JNI error when trying to run LWJGL "Hello World"?

A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib to include all the .jar files in that directory, it won't. You have to name them explicitly.

Where does Android emulator store SQLite database?

The databases are stored as SQLite files in /data/data/PACKAGE/databases/DATABASEFILE where:

You can see (copy from/to filesystem) the database file in the emulator selecting DDMS perspective, in the File Explorer tab.

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

Also you need to check if individual record is not getting updated in the logic because with update trigger in the place causes time out error too.

So, the solution is to make sure you perform bulk update after the loop/cursor instead of one record at a time in the loop.

How should I load files into my Java application?

What are you loading the files for - configuration or data (like an input file) or as a resource?

  • If as a resource, follow the suggestion and example given by Will and Justin
  • If configuration, then you can use a ResourceBundle or Spring (if your configuration is more complex).
  • If you need to read a file in order to process the data inside, this code snippet may help BufferedReader file = new BufferedReader(new FileReader(filename)) and then read each line of the file using file.readLine(); Don't forget to close the file.

Regular expression to match standard 10 digit phone number

I find this regular expression most useful for me for 10 digit contact number :

^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$

Reference: https://regex101.com/r/QeQewP/1

Explanation:

enter image description here

How do I alias commands in git?

Follwing are the 4 git shortcuts or aliases youc an use to save time.

Open the commandline and type these below 4 commands and use the shortcuts after.

git config --global alias.co checkout  
git config --global alias.ci commit    
git config --global alias.st status    
git config --global alias.br branch  

Now test them!

$ git co              # use git co instead of git checkout
$ git ci              # use git ci instead of git commit
$ git st              # use git st instead of git status
$ git br              # use git br instead of git branch

How do I get a reference to the app delegate in Swift?

extension AppDelegate {

    // MARK: - App Delegate Ref
    class func delegate() -> AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }
}

Getting list of files in documents folder

Swift 5

// Get the document directory url
let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

do {
    // Get the directory contents urls (including subfolders urls)
    let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
    print(directoryContents)

    // if you want to filter the directory contents you can do like this:
    let mp3Files = directoryContents.filter{ $0.pathExtension == "mp3" }
    print("mp3 urls:",mp3Files)
    let mp3FileNames = mp3Files.map{ $0.deletingPathExtension().lastPathComponent }
    print("mp3 list:", mp3FileNames)

} catch {
    print(error)
}

Make copy of an array

you can use

int[] a = new int[]{1,2,3,4,5};
int[] b = a.clone();

as well.

Sort objects in ArrayList by date?

All the answers here I found to be un-neccesarily complex for a simple problem (at least to an experienced java developer, which I am not). I had a similar problem and chanced upon this (and other) solutions, and though they provided a pointer, for a beginner I found as stated above. My solution, depends on where in the the Object your Date is, in this case, the date is the first element of the Object[] where dataVector is the ArrayList containing your Objects.

Collections.sort(dataVector, new Comparator<Object[]>() {
    public int compare(Object[] o1, Object[] o2) {
        return ((Date)o1[0]).compareTo(((Date)o2[0]));
    }
});

How to install SQL Server 2005 Express in Windows 8

I found that on Windows 8.1 with an instance of SQL 2014 already installed, if I ran the SQLEXPR.EXE and then dismissed the Windows 'warning this may be incompatible' dialogs, that the installer completed successfully.

I suspect having 2014 bits already in place probably helped.

Non-recursive depth first search algorithm

Suppose you want to execute a notification when each node in a graph is visited. The simple recursive implementation is:

void DFSRecursive(Node n, Set<Node> visited) {
  visited.add(n);
  for (Node x : neighbors_of(n)) {  // iterate over all neighbors
    if (!visited.contains(x)) {
      DFSRecursive(x, visited);
    }
  }
  OnVisit(n);  // callback to say node is finally visited, after all its non-visited neighbors
}

Ok, now you want a stack-based implementation because your example doesn't work. Complex graphs might for instance cause this to blow the stack of your program and you need to implement a non-recursive version. The biggest issue is to know when to issue a notification.

The following pseudo-code works (mix of Java and C++ for readability):

void DFS(Node root) {
  Set<Node> visited;
  Set<Node> toNotify;  // nodes we want to notify

  Stack<Node> stack;
  stack.add(root);
  toNotify.add(root);  // we won't pop nodes from this until DFS is done
  while (!stack.empty()) {
    Node current = stack.pop();
    visited.add(current);
    for (Node x : neighbors_of(current)) {
      if (!visited.contains(x)) {
        stack.add(x);
        toNotify.add(x);
      }
    }
  }
  // Now issue notifications. toNotifyStack might contain duplicates (will never
  // happen in a tree but easily happens in a graph)
  Set<Node> notified;
  while (!toNotify.empty()) {
  Node n = toNotify.pop();
  if (!toNotify.contains(n)) {
    OnVisit(n);  // issue callback
    toNotify.add(n);
  }
}

It looks complicated but the extra logic needed for issuing notifications exists because you need to notify in reverse order of visit - DFS starts at root but notifies it last, unlike BFS which is very simple to implement.

For kicks, try following graph: nodes are s, t, v and w. directed edges are: s->t, s->v, t->w, v->w, and v->t. Run your own implementation of DFS and the order in which nodes should be visited must be: w, t, v, s A clumsy implementation of DFS would maybe notify t first and that indicates a bug. A recursive implementation of DFS would always reach w last.

$.ajax - dataType

  • contentType is the HTTP header sent to the server, specifying a particular format.
    Example: I'm sending JSON or XML
  • dataType is you telling jQuery what kind of response to expect.
    Expecting JSON, or XML, or HTML, etc. The default is for jQuery to try and figure it out.

The $.ajax() documentation has full descriptions of these as well.


In your particular case, the first is asking for the response to be in UTF-8, the second doesn't care. Also the first is treating the response as a JavaScript object, the second is going to treat it as a string.

So the first would be:

success: function(data) {
  // get data, e.g. data.title;
}

The second:

success: function(data) {
  alert("Here's lots of data, just a string: " + data);
}

Simple PHP Pagination script

 <?php
// Custom PHP MySQL Pagination Tutorial and Script
// You have to put your mysql connection data and alter the SQL queries(both queries)

mysql_connect("DATABASE_Host_Here","DATABASE_Username_Here","DATABASE_Password_Here") or die (mysql_error());
mysql_select_db("DATABASE_Name_Here") or die (mysql_error());
//////////////  QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
$sql = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC");
//////////////////////////////////// Pagination Logic ////////////////////////////////////////////////////////////////////////
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
    $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
    //$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
    $pn = 1;
}
//This is where we set how many database items to show on each page
$itemsPerPage = 10;
// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
    $pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
    $pn = $lastPage; // force it to be $lastpage's value
}
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
} else if ($pn == $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> &nbsp;';
} else if ($pn > 1 && $pn < $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
}
// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC $limit");
//////////////////////////////// END Pagination Logic ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Pagination Display Setup /////////////////////////////////////////////////////////////////////
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1"){
    // This shows the user what page they are on, and the total number of pages
    $paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. '&nbsp;  &nbsp;  &nbsp; ';
    // If we are not on page 1 we can place the Back button
    if ($pn != 1) {
        $previous = $pn - 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
    }
    // Lay in the clickable numbers display here between the Back and Next links
    $paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
    // If we are not on the very last page we can place the Next button
    if ($pn != $lastPage) {
        $nextPage = $pn + 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
    }
}
///////////////////////////////////// END Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
// Build the Output Section Here
$outputList = '';
while($row = mysql_fetch_array($sql2)){

    $id = $row["id"];
    $firstname = $row["firstname"];
    $country = $row["country"];

    $outputList .= '<h1>' . $firstname . '</h1><h2>' . $country . ' </h2><hr />';

} // close while loop
?>
<html>
<head>
<title>Simple Pagination</title>
</head>
<body>
   <div style="margin-left:64px; margin-right:64px;">
     <h2>Total Items: <?php echo $nr; ?></h2>
   </div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
      <div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
</body>
</html> 

Twig ternary operator, Shorthand if-then-else

{{ (ability.id in company_abilities) ? 'selected' : '' }}

The ternary operator is documented under 'other operators'

Eclipse - Unable to install breakpoint due to missing line number attributes

I had the same issue with one specific project and I kept trying to reset the line number attributes in Window->Preferences... Then I realized each project has it's own settings for line number attributes. Right click the project, go into properties, choose JavaCompiler, and check the box to "Add line number attributes..."

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

I was having the same problem while importing the certificate in local keystore. Whenever i issue the keytool command i got the following error.

Certificate was added to keystore keytool error: java.io.FileNotFoundException: C:\Program Files\Java\jdk1.8.0_151\jre\lib\security (Access is denied)

Following solution work for me.

1) make sure you are running command prompt in Rus as Administrator mode

2) Change your current directory to %JAVA_HOME%\jre\lib\security

3) then Issue the below command

keytool -import -alias "mycertificatedemo" -file "C:\Users\name\Downloads\abc.crt" -keystore cacerts

3) give the password changeit

4) enter y

5) you will see the following message on successful "Certificate was added to keystore"

Make sure you are giving the "cacerts" only in -keystore param value , as i was giving the full path like "C**:\Program Files\Java\jdk1.8.0_151\jre\lib\security**".

Hope this will work

iTunes Connect: How to choose a good SKU?

Might be answer is late but look at Simple Information of SKU (Stock keeping unit) number is, it's an unique tracking number (an arbi­trary num­ber) that are used in appStore for your application. You can put what­ever you want in there as long as it is unique among your appli­ca­tions. Try to fol­low a pat­tern for the SKU Num­ber of your apps so that you will be able to bet­ter orga­nize them. I sug­gest a com­bi­na­tion of the cur­rent year + month + ID for your app. So if you’re devel­op­ing your first appli­ca­tion on september 1991 (oh,, yah it's my b'day's month and year :D ), you could put your SKU Num­ber as “19910901”. Here, I am just suggesting you for this pattern but you can take/choose any pattern which easy for you.

jQuery Toggle Text?

In most cases you would have more complex behavior tied to your click event. For example a link that toggles visibility of some element, in which case you would want to swap link text from "Show Details" to "Hide Details" in addition to other behavior. In that case this would be a preferred solution:

$.fn.extend({
  toggleText: function (a, b){
    if (this.text() == a){ this.text(b); }
    else { this.text(a) }
  }
);

You could use it this way:

$(document).on('click', '.toggle-details', function(e){
  e.preventDefault();
  //other things happening
  $(this).toggleText("Show Details", "Hide Details");
});

Execution sequence of Group By, Having and Where clause in SQL Server?

I think it is implemented in the engine as Matthias said: WHERE, GROUP BY, HAVING

Was trying to find a reference online that lists the entire sequence (i.e. "SELECT" comes right down at the bottom), but I can't find it. It was detailed in a "Inside Microsoft SQL Server 2005" book I read not that long ago, by Solid Quality Learning

Edit: Found a link: http://blogs.x2line.com/al/archive/2007/06/30/3187.aspx

Multiple Order By with LINQ

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

C# : Passing a Generic Object

In your generic method, T is just a placeholder for a type. However, the compiler doesn't per se know anything about the concrete type(s) being used runtime, so it can't assume that they will have a var member.

The usual way to circumvent this is to add a generic type constraint to your method declaration to ensure that the types used implement a specific interface (in your case, it could be ITest):

public void PrintGeneric<T>(T test) where T : ITest

Then, the members of that interface would be directly available inside the method. However, your ITest is currently empty, you need to declare common stuff there in order to enable its usage within the method.

Netbeans - Error: Could not find or load main class

Possible Fixes:

Fix 1

  1. Go to project properties (right click on the folder of your project in netbeans)
  2. On left tab where it shows the categories, click on the "Run" selection
  3. Then click on Browse to find the Main class you use on your project

Fix 2

  1. Go to C:\Users\name\AppData\Local\Netbeans
  2. delete the Cache folder.
  3. Rebuild and Run

Fix 3 Download most recent version of Netbeans

Fix 4 Download most recent version of JDK and configure Netbeans to use that

jQuery CSS Opacity

Try this:

jQuery('#main').css('opacity', '0.6');

or

jQuery('#main').css({'filter':'alpha(opacity=60)', 'zoom':'1', 'opacity':'0.6'});

if you want to support IE7, IE8 and so on.

How do I convert a Python program to a runnable .exe Windows program?

For this you have two choices:

  • A downgrade to python 2.6. This is generally undesirable because it is backtracking and may nullify a small portion of your scripts
  • Your second option is to use some form of exe converter. I recommend pyinstaller as it seems to have the best results.

Getting value of select (dropdown) before change

I needed to reveal a different div based on the selection

This is how you can do it with jquery and es6 syntax

HTML

<select class="reveal">
    <option disabled selected value>Select option</option>
    <option value="value1" data-target="#target-1" >Option 1</option>
    <option value="value2" data-target="#target-2" >Option 2</option>
</select>
<div id="target-1" style="display: none">
    option 1
</div>
<div id="target-2" style="display: none">
    option 2
</div>

JS

$('select.reveal').each((i, element)=>{
    //create reference variable 
    let $option = $('option:selected', element)
    $(element).on('change', event => {
        //get the current select element
        let selector = event.currentTarget
        //hide previously selected target
        if(typeof $option.data('target') !== 'undefined'){
            $($option.data('target')).hide()
        }
        //set new target id
        $option = $('option:selected', selector)
        //show new target
        if(typeof $option.data('target') !== 'undefined'){
            $($option.data('target')).show()
        }
    })
})

ERROR 1049 (42000): Unknown database 'mydatabasename'

when u import database from workbench or other method ,should be give same name as your dump to avoid this kind of error

TypeError: 'function' object is not subscriptable - Python

You have two objects both named bank_holiday -- one a list and one a function. Disambiguate the two.

bank_holiday[month] is raising an error because Python thinks bank_holiday refers to the function (the last object bound to the name bank_holiday), whereas you probably intend it to mean the list.

How to get the mysql table columns data type?

Refer this link

mysql> SHOW COLUMNS FROM mytable FROM mydb;
mysql> SHOW COLUMNS FROM mydb.mytable;

Hope this may help you

Is there a way to make AngularJS load partials in the beginning and not at when needed?

Another method is to use HTML5's Application Cache to download all files once and keep them in the browser's cache. The above link contains much more information. The following information is from the article:

Change your <html> tag to include a manifest attribute:

<html manifest="http://www.example.com/example.mf">

A manifest file must be served with the mime-type text/cache-manifest.

A simple manifest looks something like this:

CACHE MANIFEST
index.html
stylesheet.css
images/logo.png
scripts/main.js
http://cdn.example.com/scripts/main.js

Once an application is offline it remains cached until one of the following happens:

  1. The user clears their browser's data storage for your site.
  2. The manifest file is modified. Note: updating a file listed in the manifest doesn't mean the browser will re-cache that resource. The manifest file itself must be altered.

Create ul and li elements in javascript.

Try out below code snippet:

 var list = [];
 var text;

function update() {
    console.log(list);    

    for (var i = 0; i < list.length; i++) {
       console.log( i );
       var letters;
       var ul = document.getElementById("list");
       var li = document.createElement("li");

       li.appendChild(document.createTextNode(list[i]));
       ul.appendChild(li);

       letters += "<li>"  + list[i] + "</li>";
    }

 document.getElementById("list").innerHTML = letters;

}

function myFunction() {
    text = prompt("enter TODO");  
    list.push(text);
    update();
}   

How can I force browsers to print background images in CSS?

Browsers, by default, have their option to print background-colors and images turned off. You can add some lines in CSS to bypass this. Just add:

* {
    -webkit-print-color-adjust: exact !important;   /* Chrome, Safari */
    color-adjust: exact !important;                 /*Firefox*/
}

Note: It's not working on the entire body but you could speciy it for a inner element or a container div element.

How can I list all cookies for the current page with Javascript?

No there isn't. You can only read information associated with the current domain.

What is time_t ultimately a typedef to?

time_t is of type long int on 64 bit machines, else it is long long int.

You could verify this in these header files:

time.h: /usr/include
types.h and typesizes.h: /usr/include/x86_64-linux-gnu/bits

(The statements below are not one after another. They could be found in the resp. header file using Ctrl+f search.)

1)In time.h

typedef __time_t time_t;

2)In types.h

# define __STD_TYPE     typedef  
__STD_TYPE __TIME_T_TYPE __time_t;  

3)In typesizes.h

#define __TIME_T_TYPE       __SYSCALL_SLONG_TYPE  
#if defined __x86_64__ && defined __ILP32__  
# define __SYSCALL_SLONG_TYPE   __SQUAD_TYPE  
#else
# define __SYSCALL_SLONG_TYPE   __SLONGWORD_TYPE
#endif  

4) Again in types.h

#define __SLONGWORD_TYPE    long int
#if __WORDSIZE == 32
# define __SQUAD_TYPE       __quad_t
#elif __WORDSIZE == 64
# define __SQUAD_TYPE       long int  

#if __WORDSIZE == 64
typedef long int __quad_t;  
#else
__extension__ typedef long long int __quad_t;

MySQL Workbench - Connect to a Localhost

if you are using localhost database, try port 3306

Get environment variable value in Dockerfile

So you can do: cat Dockerfile | envsubst | docker build -t my-target -

Then have a Dockerfile with something like:

ENV MY_ENV_VAR $MY_ENV_VAR

I guess there might be a problem with some special characters, but this works for most cases at least.

What is the difference between HTTP status code 200 (cache) vs status code 304?

For your last question, why ? I'll try to explain with what I know

A brief explanation of those three status codes in layman's terms.

  • 200 - success (browser requests and get file from server)

If caching is enabled in the server

  • 200 (from memory cache) - file found in browser, so browser is not going request from server
  • 304 - browser request a file but it is rejected by server

For some files browser is deciding to request from server and for some it's deciding to read from stored (cached) files. Why is this ? Every files has an expiry date, so

If a file is not expired then the browser will use from cache (200 cache).

If file is expired, browser requests server for a file. Server check file in both places (browser and server). If same file found, server refuses the request. As per protocol browser uses existing file.

look at this nginx configuration

location / {
    add_header Cache-Control must-revalidate;
    expires     60;
    etag on;

    ...
}

Here the expiry is set to 60 seconds, so all static files are cached for 60 seconds. So if u request a file again within 60 seconds browser will read from memory (200 memory). If u request after 60 seconds browser will request server (304).

I assumed that the file is not changed after 60 seconds, in that case you would get 200 (ie, updated file will be fetched from server).

So, if the servers are configured with different expiring and caching headers (policies), the status may differ.

In your case you are using cdn, the main purpose of cdn is high availability and fast delivery. Therefore they use multiple servers. Even though it seems like files are in same directory, cdn might use multiple servers to provide u content, if those servers have different configurations. Then these status can change. Hope it helps.

What is Model in ModelAndView from Spring MVC?

ModelAndView: The name itself explains it is data structure which contains Model and View data.

Map() model=new HashMap(); 
model.put("key.name", "key.value");
new ModelAndView("view.name", model);

// or as follows

ModelAndView mav = new ModelAndView();
mav.setViewName("view.name");
mav.addObject("key.name", "key.value");

if model contains only single value, we can write as follows:

ModelAndView("view.name","key.name", "key.value");

iOS8 Beta Ad-Hoc App Download (itms-services)

If you have already installed app on your device, try to change bundle identifer on the web .plist (not app plist) with something else like "com.vistair.docunet-test2", after that refresh webpage and try to reinstall... It works for me

Draw a curve with css

@Navaneeth and @Antfish, no need to transform you can do like this also because in above solution only top border is visible so for inside curve you can use bottom border.

_x000D_
_x000D_
.box {_x000D_
  width: 500px;_x000D_
  height: 100px;_x000D_
  border: solid 5px #000;_x000D_
  border-color: transparent transparent #000 transparent;_x000D_
  border-radius: 0 0 240px 50%/60px;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_

Run a batch file with Windows task scheduler

Please check which user account you use to execute our task. It may happen that you run your task with different user then your default user, and this user requires some extra privileges. Also it may happen that the task is executed but you cant see any effect because the batch file waits for some user response so please check task manager if you see your process running. Once it happen that I schedule a batch with svn update of some web page and the process hangs because svn asked for accepting server certificate.

Options for embedding Chromium instead of IE WebBrowser control with WPF/C#

Here is another one:

http://www.essentialobjects.com/Products/WebBrowser/Default.aspx

This one is also based on the latest Chrome engine but it's much easier to use than CEF. It's a single .NET dll that you can simply reference and use.

Execute jar file with multiple classpath libraries from command prompt

This will not work java -cp lib\*.jar -jar myproject.jar. You have to put it jar by jar.

So in case of commons-codec-1.3.jar.

java -cp lib/commons-codec-1.3.jar;lib/next_jar.jar and so on.

The other solution might be putting all your jars to ext directory of your JRE. This is ok if you are using a standalone JRE. If you are using the same JRE for running more than one application I do not recommend doing it.

How to exit a function in bash

Use return operator:

function FUNCT {
  if [ blah is false ]; then
    return 1 # or return 0, or even you can omit the argument.
  else
    keep running the function
  fi
}

composer laravel create project

There are two simple methods for creating laravel Project

Method 1

composer create-project --prefer-dist laravel/laravel <project-name>

Method 2

laravel new <project-name>

Method 2 might require you to run one extra command

composer global require laravel/installer

if you face 'laravel command not found' error

How to upgrade scikit-learn package in anaconda

Following Worked for me for scikit-learn on Anaconda-Jupyter Notebook.

Upgrading my scikit-learn from 0.19.1 to 0.19.2 in anaconda installed on Ubuntu on Google VM instance:

Run the following commands in the terminal:

First, check existing available packages with versions by using:

conda list    

It will show different packages and their installed versions in the output. Here check for scikit-learn. e.g. for me, the output was:

scikit-learn              0.19.1           py36hedc7406_0  

Now I want to Upgrade to 0.19.2 July 2018 release i.e. latest available version.

conda config --append channels conda-forge
conda install scikit-learn=0.19.2

As you are trying to upgrade to 0.17 version try the following command:

conda install scikit-learn=0.17

Now check the required version of the scikit-learn is installed correctly or not by using:

conda list 

For me the Output was:

scikit-learn              0.19.2          py36_blas_openblasha84fab4_201  [blas_openblas]  conda-forge

Note: Don't use pip command if you are using Anaconda or Miniconda

I tried following commands:

!conda update conda 
!pip install -U scikit-learn

It will install the required packages also will show in the conda list but if you try to import that package it will not work.

On the website http://scikit-learn.org/stable/install.html it is mentioned as: Warning To upgrade or uninstall scikit-learn installed with Anaconda or conda you should not use the pip.

How to convert hex to rgb using Java?

For shortened hex code like #fff or #000

int red = "colorString".charAt(1) == '0' ? 0 : 
     "colorString".charAt(1) == 'f' ? 255 : 228;  
int green =
     "colorString".charAt(2) == '0' ? 0 :  "colorString".charAt(2) == 'f' ?
     255 : 228;  
int blue = "colorString".charAt(3) == '0' ? 0 : 
     "colorString".charAt(3) == 'f' ? 255 : 228;

Color.rgb(red, green,blue);

When should one use a spinlock instead of mutex?

Using spinlocks on a single-core/single-CPU system makes usually no sense, since as long as the spinlock polling is blocking the only available CPU core, no other thread can run and since no other thread can run, the lock won't be unlocked either. IOW, a spinlock wastes only CPU time on those systems for no real benefit

This is wrong. There is no wastage of cpu cycles in using spinlocks on uni processor systems, because once a process takes a spin lock , preemption is disabled , so as such, there could be no one else spinning! It's just that using it doesn't make any sense! Hence, spinlocks on Uni systems are replaced by preempt_disable at compile time by the kernel!

IntelliJ: Working on multiple projects

Open preference -> appearance & behaviour -> System settings -> select (open project in new window) then apply.enter image description here

Then you could open and edit multiple projects.

Angular cli generate a service and include the provider in one step

run the below code in Terminal

makesure You are inside your project folder in terminal

ng g s servicename --module=app.module

Create a batch file to copy and rename file

type C:\temp\test.bat>C:\temp\test.log

Printf width specifier to maintain precision of floating-point value

To my knowledge, there is a well diffused algorithm allowing to output to the necessary number of significant digits such that when scanning the string back in, the original floating point value is acquired in dtoa.c written by Daniel Gay, which is available here on Netlib (see also the associated paper). This code is used e.g. in Python, MySQL, Scilab, and many others.

Converting java.util.Properties to HashMap<String,String>

How about this?

   Map properties = new Properties();
   Map<String, String> map = new HashMap<String, String>(properties);

Will cause a warning, but works without iterations.

Howto? Parameters and LIKE statement SQL

Sometimes the symbol used as a placeholder % is not the same if you execute a query from VB as when you execute it from MS SQL / Access. Try changing your placeholder symbol from % to *. That might work.
However, if you debug and want to copy your SQL string directly in MS SQL or Access to test it, you may have to change the symbol back to % in MS SQL or Access in order to actually return values.

Hope this helps

What is 'Currying'?

Currying is a transformation that can be applied to functions to allow them to take one less argument than previously.

For example, in F# you can define a function thus:-

let f x y z = x + y + z

Here function f takes parameters x, y and z and sums them together so:-

f 1 2 3

Returns 6.

From our definition we can can therefore define the curry function for f:-

let curry f = fun x -> f x

Where 'fun x -> f x' is a lambda function equivilent to x => f(x) in C#. This function inputs the function you wish to curry and returns a function which takes a single argument and returns the specified function with the first argument set to the input argument.

Using our previous example we can obtain a curry of f thus:-

let curryf = curry f

We can then do the following:-

let f1 = curryf 1

Which provides us with a function f1 which is equivilent to f1 y z = 1 + y + z. This means we can do the following:-

f1 2 3

Which returns 6.

This process is often confused with 'partial function application' which can be defined thus:-

let papply f x = f x

Though we can extend it to more than one parameter, i.e.:-

let papply2 f x y = f x y
let papply3 f x y z = f x y z
etc.

A partial application will take the function and parameter(s) and return a function that requires one or more less parameters, and as the previous two examples show is implemented directly in the standard F# function definition so we could achieve the previous result thus:-

let f1 = f 1
f1 2 3

Which will return a result of 6.

In conclusion:-

The difference between currying and partial function application is that:-

Currying takes a function and provides a new function accepting a single argument, and returning the specified function with its first argument set to that argument. This allows us to represent functions with multiple parameters as a series of single argument functions. Example:-

let f x y z = x + y + z
let curryf = curry f
let f1 = curryf 1
let f2 = curryf 2
f1 2 3
6
f2 1 3
6

Partial function application is more direct - it takes a function and one or more arguments and returns a function with the first n arguments set to the n arguments specified. Example:-

let f x y z = x + y + z
let f1 = f 1
let f2 = f 2
f1 2 3
6
f2 1 3
6

UIButton: set image for selected-highlighted state

Where you want to call from

[button addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchUpInside];

The method:

-(void)test:(id)sender{
    UIButton *button=(UIButton *)sender;
    if (_togon){
      [button setTitleColor:UIColorFromRGB(89,89, 89) forState:UIControlStateNormal];
      _togon=NO;
    }
    else{
      [button setTitleColor:UIColorFromRGB(28, 154, 214) forState:UIControlStateNormal];
      _togon=YES;
    }
}

Credit above to Jorge but I improved it a bit giving the full working solution

What's the most concise way to read query parameters in AngularJS?

It's a bit late, but I think your problem was your URL. If instead of

http://127.0.0.1:8080/test.html?target=bob

you had

http://127.0.0.1:8080/test.html#/?target=bob

I'm pretty sure it would have worked. Angular is really picky about its #/

How to create a cron job using Bash automatically without the interactive editor?

Thanks everybody for your help. Piecing together what I found here and elsewhere I came up with this:

The Code

command="php $INSTALL/indefero/scripts/gitcron.php"
job="0 0 * * 0 $command"
cat <(fgrep -i -v "$command" <(crontab -l)) <(echo "$job") | crontab -

I couldn't figure out how to eliminate the need for the two variables without repeating myself.

command is obviously the command I want to schedule. job takes $command and adds the scheduling data. I needed both variables separately in the line of code that does the work.

Details

  1. Credit to duckyflip, I use this little redirect thingy (<(*command*)) to turn the output of crontab -l into input for the fgrep command.
  2. fgrep then filters out any matches of $command (-v option), case-insensitive (-i option).
  3. Again, the little redirect thingy (<(*command*)) is used to turn the result back into input for the cat command.
  4. The cat command also receives echo "$job" (self explanatory), again, through use of the redirect thingy (<(*command*)).
  5. So the filtered output from crontab -l and the simple echo "$job", combined, are piped ('|') over to crontab - to finally be written.
  6. And they all lived happily ever after!

In a nutshell:

This line of code filters out any cron jobs that match the command, then writes out the remaining cron jobs with the new one, effectively acting like an "add" or "update" function. To use this, all you have to do is swap out the values for the command and job variables.

grep --ignore-case --only

If your grep -i does not work then try using tr command to convert the the output of your file to lower case and then pipe it into standard grep with whatever you are looking for. (it sounds complicated but the actual command which I have provided for you is not !).

Notice the tr command does not change the content of your original file, it just converts it just before it feeds it into grep.

1.here is how you can do this on a file

tr '[:upper:]' '[:lower:]' <your_file.txt|grep what_ever_you_are_searching_in_lower_case

2.or in your case if you are just echoing something

echo "ABC"|tr '[:upper:]' '[:lower:]' | grep abc

How to implement common bash idioms in Python?

Your best bet is a tool that is specifically geared towards your problem. If it's processing text files, then Sed, Awk and Perl are the top contenders. Python is a general-purpose dynamic language. As with any general purpose language, there's support for file-manipulation, but that isn't what it's core purpose is. I would consider Python or Ruby if I had a requirement for a dynamic language in particular.

In short, learn Sed and Awk really well, plus all the other goodies that come with your flavour of *nix (All the Bash built-ins, grep, tr and so forth). If it's text file processing you're interested in, you're already using the right stuff.

How does a PreparedStatement avoid or prevent SQL injection?

The SQL used in a PreparedStatement is precompiled on the driver. From that point on, the parameters are sent to the driver as literal values and not executable portions of SQL; thus no SQL can be injected using a parameter. Another beneficial side effect of PreparedStatements (precompilation + sending only parameters) is improved performance when running the statement multiple times even with different values for the parameters (assuming that the driver supports PreparedStatements) as the driver does not have to perform SQL parsing and compilation each time the parameters change.

Difference between arguments and parameters in Java

The term parameter refers to any declaration within the parentheses following the method/function name in a method/function declaration or definition; the term argument refers to any expression within the parentheses of a method/function call. i.e.

  1. parameter used in function/method definition.
  2. arguments used in function/method call.

Please have a look at the below example for better understanding:

package com.stackoverflow.works;

public class ArithmeticOperations {

    public static int add(int x, int y) { //x, y are parameters here
        return x + y;
    }

    public static void main(String[] args) {
        int x = 10;
        int y = 20;
        int sum = add(x, y); //x, y are arguments here
        System.out.println("SUM IS: " +sum);
    }

}

Thank you!

push() a two-dimensional array

In your case you can do that without using push at all:

var myArray = [
    [1,1,1,1,1],
    [1,1,1,1,1],
    [1,1,1,1,1]
]

var newRows = 8;
var newCols = 7;

var item;

for (var i = 0; i < newRows; i++) {
    item = myArray[i] || (myArray[i] = []);

    for (var k = item.length; k < newCols; k++)
        item[k] = 0;    
}

How to convert Set<String> to String[]?

Use toArray(T[] a) method:

String[] array = set.toArray(new String[0]);

MySQL: Delete all rows older than 10 minutes

The answer is right in the MYSQL manual itself.

"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"

Converting a string to a date in DB2

Okay, seems like a bit of a hack. I have got it to work using a substring, so that only the part of the string with the date (not the time) gets passed into the DATE function...

DATE(substr(SETTLEMENTDATE.VALUE,7,4)||'-'|| substr(SETTLEMENTDATE.VALUE,4,2)||'-'|| substr(SETTLEMENTDATE.VALUE,1,2))

I will still accept any answers that are better than this one!

Random float number generation

C++11 gives you a lot of new options with random. The canonical paper on this topic would be N3551, Random Number Generation in C++11

To see why using rand() can be problematic see the rand() Considered Harmful presentation material by Stephan T. Lavavej given during the GoingNative 2013 event. The slides are in the comments but here is a direct link.

I also cover boost as well as using rand since legacy code may still require its support.

The example below is distilled from the cppreference site and uses the std::mersenne_twister_engine engine and the std::uniform_real_distribution which generates numbers in the [0,10) interval, with other engines and distributions commented out (see it live):

#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>

int main()
{
    std::random_device rd;

    //
    // Engines 
    //
    std::mt19937 e2(rd());
    //std::knuth_b e2(rd());
    //std::default_random_engine e2(rd()) ;

    //
    // Distribtuions
    //
    std::uniform_real_distribution<> dist(0, 10);
    //std::normal_distribution<> dist(2, 2);
    //std::student_t_distribution<> dist(5);
    //std::poisson_distribution<> dist(2);
    //std::extreme_value_distribution<> dist(0,2);

    std::map<int, int> hist;
    for (int n = 0; n < 10000; ++n) {
        ++hist[std::floor(dist(e2))];
    }

    for (auto p : hist) {
        std::cout << std::fixed << std::setprecision(1) << std::setw(2)
                  << p.first << ' ' << std::string(p.second/200, '*') << '\n';
    }
}

output will be similar to the following:

0 ****
1 ****
2 ****
3 ****
4 *****
5 ****
6 *****
7 ****
8 *****
9 ****

The output will vary depending on which distribution you choose, so if we decided to go with std::normal_distribution with a value of 2 for both mean and stddev e.g. dist(2, 2) instead the output would be similar to this (see it live):

-6 
-5 
-4 
-3 
-2 **
-1 ****
 0 *******
 1 *********
 2 *********
 3 *******
 4 ****
 5 **
 6 
 7 
 8 
 9 

The following is a modified version of some of the code presented in N3551 (see it live) :

#include <algorithm>
#include <array>
#include <iostream>
#include <random>

std::default_random_engine & global_urng( )
{
    static std::default_random_engine u{};
    return u ;
}

void randomize( )
{
    static std::random_device rd{};
    global_urng().seed( rd() );
}

int main( )
{
  // Manufacture a deck of cards:
  using card = int;
  std::array<card,52> deck{};
  std::iota(deck.begin(), deck.end(), 0);

  randomize( ) ;  

  std::shuffle(deck.begin(), deck.end(), global_urng());
  // Display each card in the shuffled deck:
  auto suit = []( card c ) { return "SHDC"[c / 13]; };
  auto rank = []( card c ) { return "AKQJT98765432"[c % 13]; };

  for( card c : deck )
      std::cout << ' ' << rank(c) << suit(c);

   std::cout << std::endl;
}

Results will look similar to:

5H 5S AS 9S 4D 6H TH 6D KH 2S QS 9H 8H 3D KC TD 7H 2D KS 3C TC 7D 4C QH QC QD JD AH JC AC KD 9D 5C 2H 4H 9C 8C JH 5D 4S 7C AD 3S 8S TS 2C 8D 3H 6C JS 7S 6S

Boost

Of course Boost.Random is always an option as well, here I am using boost::random::uniform_real_distribution:

#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real_distribution.hpp>

int main()
{
    boost::random::mt19937 gen;
    boost::random::uniform_real_distribution<> dist(0, 10);

    std::map<int, int> hist;
    for (int n = 0; n < 10000; ++n) {
        ++hist[std::floor(dist(gen))];
    }

    for (auto p : hist) {
        std::cout << std::fixed << std::setprecision(1) << std::setw(2)
                  << p.first << ' ' << std::string(p.second/200, '*') << '\n';
    }
}

rand()

If you must use rand() then we can go to the C FAQ for a guides on How can I generate floating-point random numbers? , which basically gives an example similar to this for generating an on the interval [0,1):

#include <stdlib.h>

double randZeroToOne()
{
    return rand() / (RAND_MAX + 1.);
}

and to generate a random number in the range from [M,N):

double randMToN(double M, double N)
{
    return M + (rand() / ( RAND_MAX / (N-M) ) ) ;  
}

How to include files outside of Docker's build context?

The best way to work around this is to specify the Dockerfile independently of the build context, using -f.

For instance, this command will give the ADD command access to anything in your current directory.

docker build -f docker-files/Dockerfile .

Update: Docker now allows having the Dockerfile outside the build context (fixed in 18.03.0-ce, https://github.com/docker/cli/pull/886). So you can also do something like

docker build -f ../Dockerfile .

Extract names of objects from list

Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want

x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)

WORD.C <- function(WORDS){
  require(wordcloud)

  L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))

  # Takes a dataframe and the text you want to display
  FUN <- function(X, text){
    windows() 
    wordcloud(X[, 1], X[, 2], min.freq=1)
    mtext(text, 3, padj=-4.5, col="red")  #what I'm trying that isn't working
  }

  # Now creates the sequence 1,...,length(L2)
  # Loops over that and then create an anonymous function
  # to send in the information you want to use.
  lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})

  # Since you asked about loops
  # you could use i in seq_along(L2) 
  # instead of 1:length(L2) if you wanted to
  #for(i in 1:length(L2)){
  #  FUN(L2[[i]], names(L2)[i])
  #}
}

WORD.C(list.xy)

Xcode Objective-C | iOS: delay function / NSTimer help?

sleep doesn't work because the display can only be updated after your main thread returns to the system. NSTimer is the way to go. To do this, you need to implement methods which will be called by the timer to change the buttons. An example:

- (void)button_circleBusy:(id)sender {
    firstButton.enabled = NO;
    // 60 milliseconds is .06 seconds
    [NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO];
}
- (void)goToSecondButton:(id)sender {
    firstButton.enabled = YES;
    secondButton.enabled = NO;
    [NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToThirdButton:) userInfo:nil repeats:NO];
}
...

Swift: print() vs println() vs NSLog()

If you're using Swift 2, now you can only use print() to write something to the output.

Apple has combined both println() and print() functions into one.

Updated to iOS 9

By default, the function terminates the line it prints by adding a line break.

print("Hello Swift")

Terminator

To print a value without a line break after it, pass an empty string as the terminator

print("Hello Swift", terminator: "")

Separator

You now can use separator to concatenate multiple items

print("Hello", "Swift", 2, separator:" ")

Both

Or you could combine using in this way

print("Hello", "Swift", 2, separator:" ", terminator:".")

Git: How to commit a manually deleted file?

The answer's here, I think.

It's better if you do git rm <fileName>, though.

How can I detect when the mouse leaves the window?

Please keep in mind that my answer has aged a lot.

This type of behavior is usually desired while implementing drag-drop behavior on an html page. The solution below was tested on IE 8.0.6, FireFox 3.6.6, Opera 10.53, and Safari 4 on an MS Windows XP machine.
First a little function from Peter-Paul Koch; cross browser event handler:

function addEvent(obj, evt, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evt, fn, false);
    }
    else if (obj.attachEvent) {
        obj.attachEvent("on" + evt, fn);
    }
}

And then use this method to attach an event handler to the document objects mouseout event:

addEvent(document, "mouseout", function(e) {
    e = e ? e : window.event;
    var from = e.relatedTarget || e.toElement;
    if (!from || from.nodeName == "HTML") {
        // stop your drag event here
        // for now we can just use an alert
        alert("left window");
    }
});

Finally, here is an html page with the script embedded for debugging:

<html>
<head>
<script type="text/javascript">
function addEvent(obj, evt, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evt, fn, false);
    }
    else if (obj.attachEvent) {
        obj.attachEvent("on" + evt, fn);
    }
}
addEvent(window,"load",function(e) {
    addEvent(document, "mouseout", function(e) {
        e = e ? e : window.event;
        var from = e.relatedTarget || e.toElement;
        if (!from || from.nodeName == "HTML") {
            // stop your drag event here
            // for now we can just use an alert
            alert("left window");
        }
    });
});
</script>
</head>
<body></body>
</html>

Fit Image in ImageButton in Android

It worked well in my case. First, you download an image and rename it as iconimage, locates it in the drawable folder. You can change the size by setting android:layout_width or android:layout_height. Finally, we have

 <ImageButton
        android:id="@+id/answercall"
        android:layout_width="120dp"
        android:layout_height="80dp"
        android:src="@drawable/iconimage"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:scaleType="fitCenter" />

CSS for grabbing cursors (drag & drop)

In case anyone else stumbles across this question, this is probably what you were looking for:

.grabbable {
    cursor: move; /* fallback if grab cursor is unsupported */
    cursor: grab;
    cursor: -moz-grab;
    cursor: -webkit-grab;
}

 /* (Optional) Apply a "closed-hand" cursor during drag operation. */
.grabbable:active {
    cursor: grabbing;
    cursor: -moz-grabbing;
    cursor: -webkit-grabbing;
}

Disable Pinch Zoom on Mobile Web

EDIT: Because this keeps getting commented on, we all know that we shouldn't do this. The question was how do I do it, not should I do it.

Add this into your for mobile devices. Then do your widths in percentages and you'll be fine:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

Add this in for devices that can't use viewport too:

<meta name="HandheldFriendly" content="true" />

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

The GUI can be fickle at times. The error you got when using T-SQL is because you're trying to overwrite an existing database, but did not specify to overwrite/replace the existing database. The following might work:

Use Master
Go
RESTORE DATABASE Publications
  FROM DISK = 'C:\Publications_backup_2012_10_15_010004_5648316.bak'
  WITH 
    MOVE 'Publications' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS2008R2\MSSQL\DATA\Publications.mdf',--adjust path
    MOVE 'Publications_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS2008R2\MSSQL\DATA\Publications.ldf'
, REPLACE -- Add REPLACE to specify the existing database which should be overwritten.

How to save local data in a Swift app?

For someone who'd not prefer to handle UserDefaults for some reasons, there's another option - NSKeyedArchiver & NSKeyedUnarchiver. It helps save objects into a file using archiver, and load archived file to original objects.

// To archive object,
let mutableData: NSMutableData = NSMutableData()
let archiver: NSKeyedArchiver = NSKeyedArchiver(forWritingWith: mutableData)
archiver.encode(object, forKey: key)
archiver.finishEncoding()
return mutableData.write(toFile: path, atomically: true)

// To unarchive objects,
if let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
    let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
    let object = unarchiver.decodeObject(forKey: key)
}

I've write an simple utility to save/load objects in local storage, used sample codes above. You might want to see this. https://github.com/DragonCherry/LocalStorage

Class has been compiled by a more recent version of the Java Environment

For temporary solution just right click on Project => Properties => Java compiler => over there please select compiler compliance level 1.8 => .class compatibility 1.8 => source compatibility 1.8.

Then your code will start to execute on version 1.8.

Android splash screen image sizes to fit all devices

Density buckets

LDPI    120dpi    .75x
MDPI    160dpi    1x
HDPI    240dpi    1.5x
XHDPI   320dpi    2x
XXHDPI  480dpi    3x
XXXHDPI 640dpi    4x

px / dp = dpi / 160 dpi

Jquery bind double click and single click separately

I found that John Strickler's answer did not quite do what I was expecting. Once the alert is triggered by a second click within the two-second window, every subsequent click triggers another alert until you wait two seconds before clicking again. So with John's code, a triple click acts as two double clicks where I would expect it to act like a double click followed by a single click.

I have reworked his solution to function in this way and to flow in a way my mind can better comprehend. I dropped the delay down from 2000 to 700 to better simulate what I would feel to be a normal sensitivity. Here's the fiddle: http://jsfiddle.net/KpCwN/4/.

Thanks for the foundation, John. I hope this alternate version is useful to others.

var DELAY = 700, clicks = 0, timer = null;

$(function(){

    $("a").on("click", function(e){

        clicks++;  //count clicks

        if(clicks === 1) {

            timer = setTimeout(function() {

                alert("Single Click");  //perform single-click action    
                clicks = 0;             //after action performed, reset counter

            }, DELAY);

        } else {

            clearTimeout(timer);    //prevent single-click action
            alert("Double Click");  //perform double-click action
            clicks = 0;             //after action performed, reset counter
        }

    })
    .on("dblclick", function(e){
        e.preventDefault();  //cancel system double-click event
    });

});

Selenium and xPath - locating a link by containing text

Use this

//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(text(),'Some text')]

OR

//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(.,'Some text')]

Java - Search for files in a directory

This looks like a homework question, so I'll just give you a few pointers:

Try to give good distinctive variable names. Here you used "fileName" first for the directory, and then for the file. That is confusing, and won't help you solve the problem. Use different names for different things.

You're not using Scanner for anything, and it's not needed here, get rid of it.

Furthermore, the accept method should return a boolean value. Right now, you are trying to return a String. Boolean means that it should either return true or false. For example return a > 0; may return true or false, depending on the value of a. But return fileName; will just return the value of fileName, which is a String.

Recommended way to save uploaded files in a servlet application

I post my final way of doing it based on the accepted answer:

@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {

    private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
    private String uploadsDirName;

    @Override
    public void init() throws ServletException {
        super.init();
        uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // ...
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Collection<Part> parts = req.getParts();
        for (Part part : parts) {
            File save = new File(uploadsDirName, getFilename(part) + "_"
                + System.currentTimeMillis());
            final String absolutePath = save.getAbsolutePath();
            log.debug(absolutePath);
            part.write(absolutePath);
            sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
        }
    }

    // helpers
    private static String getFilename(Part part) {
        // courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim()
                        .replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1)
                        .substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }
}

where :

@SuppressWarnings("serial")
class Controller extends HttpServlet {

    static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
    static ServletContext sc;
    Logger log;
    // private
    // "/WEB-INF/app.properties" also works...
    private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
    private Properties properties;

    @Override
    public void init() throws ServletException {
        super.init();
        // synchronize !
        if (sc == null) sc = getServletContext();
        log = LoggerFactory.getLogger(this.getClass());
        try {
            loadProperties();
        } catch (IOException e) {
            throw new RuntimeException("Can't load properties file", e);
        }
    }

    private void loadProperties() throws IOException {
        try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
                if (is == null)
                    throw new RuntimeException("Can't locate properties file");
                properties = new Properties();
                properties.load(is);
        }
    }

    String property(final String key) {
        return properties.getProperty(key);
    }
}

and the /WEB-INF/app.properties :

upload.location=C:/_/

HTH and if you find a bug let me know

linux shell script: split string, put them in an array then loop through them

Here's a variation on ashirazi's answer which doesn't rely on $IFS. It does have its own issues which I ouline below.

sentence="one;two;three"
sentence=${sentence//;/$'\n'}  # change the semicolons to white space
for word in $sentence
do
    echo "$word"
done

Here I've used a newline, but you could use a tab "\t" or a space. However, if any of those characters are in the text it will be split there, too. That's the advantage of $IFS - it can not only enable a separator, but disable the default ones. Just make sure you save its value before you change it - as others have suggested.

Passing parameter to controller from route in laravel

You don't need anything special for adding paramaters. Just like you had it.

Route::get('groups/(:any)', array('as' => 'group', 'uses' => 'groups@show'));


class Groups_Controller extends Base_Controller {

    public $restful = true;    

    public function get_show($groupID) {
        return 'I am group id ' . $groupID;
    }  


}

Smooth scroll to div id jQuery

Plain JS:

Can be done in plain JS if you use modern browsers.

document
    .getElementById("range-calculator")
    .scrollIntoView({ behavior: "smooth" });

Browser support is a bit issue, but modern browsers support it.

Android: How do I prevent the soft keyboard from pushing my view up?

For xamarin users add this code to Activity attribute of the MainActivity class,

WindowSoftInputMode =Android.Views.SoftInput.AdjustNothing

or you can add this code Window.SetSoftInputMode(Android.Views.SoftInput.AdjustNothing) to the OnCreate method of MainActivity class.

Can I call a function of a shell script from another shell script?

Refactor your second.sh script like this:

function func1 {
   fun=$1
   book=$2
   printf "fun=%s,book=%s\n" "${fun}" "${book}"
}

function func2 {
   fun2=$1
   book2=$2
   printf "fun2=%s,book2=%s\n" "${fun2}" "${book2}"
}

And then call these functions from script first.sh like this:

source ./second.sh
func1 love horror
func2 ball mystery

OUTPUT:

fun=love,book=horror
fun2=ball,book2=mystery

How can I change the current URL?

Hmm, I would use

window.location = 'http://localhost/index.html#?options=go_here';

I'm not exactly sure if that is what you mean.

PHP to search within txt file and echo the whole line

Using file() and strpos():

<?php
// What to look for
$search = 'foo';
// Read from file
$lines = file('file.txt');
foreach($lines as $line)
{
  // Check if the line contains the string we're looking for, and print if it does
  if(strpos($line, $search) !== false)
    echo $line;
}

When tested on this file:

foozah
barzah
abczah

It outputs:

foozah


Update:
To show text if the text is not found, use something like this:

<?php
$search = 'foo';
$lines = file('file.txt');
// Store true when the text is found
$found = false;
foreach($lines as $line)
{
  if(strpos($line, $search) !== false)
  {
    $found = true;
    echo $line;
  }
}
// If the text was not found, show a message
if(!$found)
{
  echo 'No match found';
}

Here I'm using the $found variable to find out if a match was found.

Fixed header table with horizontal scrollbar and vertical scrollbar on

The solution is to use JS to horizontally scroll the top div so that it matches the bottom div.

You must be very careful to make sure the top and bottom are exactly the same sizes, for example you might need to make the TD and TH use fixed widths.

Here is a fiddle https://jsfiddle.net/jdhenckel/yzjhk08h/5/

The important parts: CSS use

.head {
  overflow-x: hidden;
  overflow-y: scroll;
  width: 500px;
}
.lower {
  overflow-x: auto;
  overflow-y: scroll;
  width: 500px;
  height: 400px;
}

Notice overflow-y must be the same on both head and lower.

And the Javascript...

var head = document.querySelector('.head');

var lower = document.querySelector('.lower');

lower.addEventListener('scroll', function (e) {
  console.log(lower.scrollLeft);
  head.scrollLeft = lower.scrollLeft;
});

Get total number of items on Json object?

That's an Object and you want to count the properties of it.

Object.keys(jsonArray).length

References:

How to detect chrome and safari browser (webkit)

/WebKit/.test(navigator.userAgent) — that's it.

How to get a div to resize its height to fit container?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
#top, #bottom {
    height: 100px;
    width: 100%;
    position: relative;
}
#container {
    overflow: hidden;
    position: relative;
    width: 100%;
}
#container .left {
    height: 550px;
    width: 55%;
    position: relative;
    float: left;
    background-color: #3399FF;
}
#container .right {
    height: 100%;
    position: absolute;
    right: 0;
    left: 55%;
    bottom: 0px;
    top: 0px;
    background-color: #3366CC;
}
</style>
</head>

<body>
<div id="top"></div>
<div id="container">
  <div class="left"></div>
  <div class="right"></div>
</div>
<div id="bottom"></div>
</body>
</html>

How do I remove all HTML tags from a string without knowing which tags are in it?

You can use the below code on your string and you will get the complete string without html part.

string title = "<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)".Replace("&nbsp;",string.Empty);            
        string s = Regex.Replace(title, "<.*?>", String.Empty);

How to generate UL Li list from string array using jquery?

    <script type="text/javascript" >
        function aa()
        {
            var YourArray = ['United States', 'Canada', 'Argentina', 'Armenia'];
            var ObjUl = $('<ul></ul>');
            for (i = 0; i < YourArray.length; i++)
            {
                var Objli = $('<li></li>');
                var Obja = $('<a></a>');

                ObjUl.addClass("ui-menu-item");
                ObjUl.attr("role", "menuitem");

                Obja.addClass("ui-all");
                Obja.attr("tabindex", "-1");

                Obja.text(YourArray[i]);
                Objli.append(Obja);

                ObjUl.append(Objli);
            }
            $('.DivSai').append(ObjUl);
        }
    </script>
</head>
<body onload="aa()">
    <form id="form1" runat="server">
    <div class="DivSai" >

    </div>
    </form>
</body>

NodeJS / Express: what is "app.use"?

app.use
is created by express(nodejs middleware framework )
app.use is use to execute any specific query at intilization process
server.js(node)
var app = require('express');
app.use(bodyparser.json())
so the basically app.use function called every time when server up

Difference between "char" and "String" in Java

char means single character. In java it is UTF-16 character. String can be thought as an array of chars.

So, imagine "Android" string. It consists of 'A', 'n', 'd', 'r', 'o', 'i' and again 'd' characters.

char is a primitive type in java and String is a class, which encapsulates array of chars.

Vertical (rotated) text in HTML table

I was using the Font Awesome library and was able to achieve this affect by tacking on the following to any html element.

<div class="fa fa-rotate-270">
  My Test Text
</div>

Your mileage may vary.

Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

Yet another usage of th:class, same as @NewbLeech and @Charles have posted, but simplified to maximum if there is no "else" case:

<input th:class="${#fields.hasErrors('password')} ? formFieldHasError" />

Does not include class attribute if #fields.hasErrors('password') is false.

Open soft keyboard programmatically

This is the required source code :

public static void openKeypad(final Context context, final View v) 
 {
new Handler().postDelayed(new Runnable() 
{
    @Override
    public void run() 
    {
        InputMethodManager inputManager =   (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); 
        inputManager.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);    
        Log.e("openKeypad", "Inside Handler");
    }
},300);}

For details , Please go through this link. This helped me. https://github.com/Nikhillosalka/Keyboard/blob/master/README.md

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

In some cases, DateTime.MinValue (or equivalenly, default(DateTime)) is used to indicate an unknown value.

This simple extension method can help handle such situations:

public static class DbDateHelper
{
    /// <summary>
    /// Replaces any date before 01.01.1753 with a Nullable of 
    /// DateTime with a value of null.
    /// </summary>
    /// <param name="date">Date to check</param>
    /// <returns>Input date if valid in the DB, or Null if date is 
    /// too early to be DB compatible.</returns>
    public static DateTime? ToNullIfTooEarlyForDb(this DateTime date)
    {
        return (date >= (DateTime) SqlDateTime.MinValue) ? date : (DateTime?)null;
    }
}

Usage:

 DateTime? dateToPassOnToDb = tooEarlyDate.ToNullIfTooEarlyForDb();

Removing duplicate rows from table in Oracle

Use the rowid pseudocolumn.

DELETE FROM your_table
WHERE rowid not in
(SELECT MIN(rowid)
FROM your_table
GROUP BY column1, column2, column3);

Where column1, column2, and column3 make up the identifying key for each record. You might list all your columns.

Strings in C, how to get subString

Generalized:

char* subString (const char* input, int offset, int len, char* dest)
{
  int input_len = strlen (input);

  if (offset + len > input_len)
  {
     return NULL;
  }

  strncpy (dest, input + offset, len);
  return dest;
}

char dest[80];
const char* source = "hello world";

if (subString (source, 0, 5, dest))
{
  printf ("%s\n", dest);
}

SQL Views - no variables?

EDIT: I tried using a CTE on my previous answer which was incorrect, as pointed out by @bummi. This option should work instead:

Here's one option using a CROSS APPLY, to kind of work around this problem:

SELECT st.Value, Constants.CONSTANT_ONE, Constants.CONSTANT_TWO
FROM SomeTable st
CROSS APPLY (
    SELECT 'Value1' AS CONSTANT_ONE,
           'Value2' AS CONSTANT_TWO
) Constants

Write output to a text file in PowerShell

Use the Out-File cmdlet

 Compare-Object ... | Out-File C:\filename.txt

Optionally, add -Encoding utf8 to Out-File as the default encoding is not really ideal for many uses.

Checking if a variable exists in javascript

If you want to check if a variable (say v) has been defined and is not null:

if (typeof v !== 'undefined' && v !== null) {
    // Do some operation  
}

If you want to check for all falsy values such as: undefined, null, '', 0, false:

if (v) {
   // Do some operation
}

How do I use typedef and typedef enum in C?

typedef enum state {DEAD,ALIVE} State;
|     | |                     | |   |^ terminating semicolon, required! 
|     | |   type specifier    | |   |
|     | |                     | ^^^^^  declarator (simple name)
|     | |                     |    
|     | ^^^^^^^^^^^^^^^^^^^^^^^  
|     |
^^^^^^^-- storage class specifier (in this case typedef)

The typedef keyword is a pseudo-storage-class specifier. Syntactically, it is used in the same place where a storage class specifier like extern or static is used. It doesn't have anything to do with storage. It means that the declaration doesn't introduce the existence of named objects, but rather, it introduces names which are type aliases.

After the above declaration, the State identifier becomes an alias for the type enum state {DEAD,ALIVE}. The declaration also provides that type itself. However that isn't typedef doing it. Any declaration in which enum state {DEAD,ALIVE} appears as a type specifier introduces that type into the scope:

enum state {DEAD, ALIVE} stateVariable;

If enum state has previously been introduced the typedef has to be written like this:

typedef enum state State;

otherwise the enum is being redefined, which is an error.

Like other declarations (except function parameter declarations), the typedef declaration can have multiple declarators, separated by a comma. Moreover, they can be derived declarators, not only simple names:

typedef unsigned long ulong, *ulongptr;
|     | |           | |  1 | |   2   |
|     | |           | |    | ^^^^^^^^^--- "pointer to" declarator
|     | |           | ^^^^^^------------- simple declarator
|     | ^^^^^^^^^^^^^-------------------- specifier-qualifier list
^^^^^^^---------------------------------- storage class specifier

This typedef introduces two type names ulong and ulongptr, based on the unsigned long type given in the specifier-qualifier list. ulong is just a straight alias for that type. ulongptr is declared as a pointer to unsigned long, thanks to the * syntax, which in this role is a kind of type construction operator which deliberately mimics the unary * for pointer dereferencing used in expressions. In other words ulongptr is an alias for the "pointer to unsigned long" type.

Alias means that ulongptr is not a distinct type from unsigned long *. This is valid code, requiring no diagnostic:

unsigned long *p = 0;
ulongptr q = p;

The variables q and p have exactly the same type.

The aliasing of typedef isn't textual. For instance if user_id_t is a typedef name for the type int, we may not simply do this:

unsigned user_id_t uid;  // error! programmer hoped for "unsigned int uid". 

This is an invalid type specifier list, combining unsigned with a typedef name. The above can be done using the C preprocessor:

#define user_id_t int
unsigned user_id_t uid;

whereby user_id_t is macro-expanded to the token int prior to syntax analysis and translation. While this may seem like an advantage, it is a false one; avoid this in new programs.

Among the disadvantages that it doesn't work well for derived types:

 #define silly_macro int *

 silly_macro not, what, you, think;

This declaration doesn't declare what, you and think as being of type "pointer to int" because the macro-expansion is:

 int * not, what, you, think;

The type specifier is int, and the declarators are *not, what, you and think. So not has the expected pointer type, but the remaining identifiers do not.

And that's probably 99% of everything about typedef and type aliasing in C.

How to create custom exceptions in Java?

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super(message); }
  public FooException(String message, Throwable cause) { super(message, cause); }
  public FooException(Throwable cause) { super(cause); }
}

Methods that can potentially throw or propagate this exception must declare it:

public void calculate(int i) throws FooException, IOException;

... and code calling this method must either handle or propagate this exception (or both):

try {
  int i = 5;
  myObject.calculate(5);
} catch(FooException ex) {
  // Print error and terminate application.
  ex.printStackTrace();
  System.exit(1);
} catch(IOException ex) {
  // Rethrow as FooException.
  throw new FooException(ex);
}

You'll notice in the above example that IOException is caught and rethrown as FooException. This is a common technique used to encapsulate exceptions (typically when implementing an API).

Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}

Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

public void calculate(int i) {
  if (i < 0) {
    throw new FooRuntimeException("i < 0: " + i);
  }
}

Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.

The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable. Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError). Likewise you should avoid catching Throwable, which could result in you catching Errors in addition to Exceptions.

How to extract a floating number from a string

If your float is always expressed in decimal notation something like

>>> import re
>>> re.findall("\d+\.\d+", "Current Level: 13.4 db.")
['13.4']

may suffice.

A more robust version would be:

>>> re.findall(r"[-+]?\d*\.\d+|\d+", "Current Level: -13.2 db or 14.2 or 3")
['-13.2', '14.2', '3']

If you want to validate user input, you could alternatively also check for a float by stepping to it directly:

user_input = "Current Level: 1e100 db"
for token in user_input.split():
    try:
        # if this succeeds, you have your (first) float
        print float(token), "is a float"
    except ValueError:
        print token, "is something else"

# => Would print ...
#
# Current is something else
# Level: is something else
# 1e+100 is a float
# db is something else

Sockets - How to find out what port and address I'm assigned

If it's a server socket, you should call listen() on your socket, and then getsockname() to find the port number on which it is listening:

struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
    perror("getsockname");
else
    printf("port number %d\n", ntohs(sin.sin_port));

As for the IP address, if you use INADDR_ANY then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname() on the socket for a specific connection (which you get from accept()) in order to find out which local IP address is being used on that connection.

Newline in markdown table?

Use <br/> . For example:

Change log, upgrade version

Dependency | Old version | New version |
---------- | ----------- | -----------
Spring Boot | `1.3.5.RELEASE` | `1.4.3.RELEASE`
Gradle | `2.13` | `3.2.1`
Gradle plugin <br/>`com.gorylenko.gradle-git-properties` | `1.4.16` | `1.4.17`
`org.webjars:requirejs` | `2.2.0` | `2.3.2`
`org.webjars.npm:stompjs` | `2.3.3` | `2.3.3`
`org.webjars.bower:sockjs-client` | `1.1.0` | `1.1.1`

URL: https://github.com/donhuvy/lsb/wiki

How to convert an iterator to a stream?

Great suggestion! Here's my reusable take on it:

public class StreamUtils {

    public static <T> Stream<T> asStream(Iterator<T> sourceIterator) {
        return asStream(sourceIterator, false);
    }

    public static <T> Stream<T> asStream(Iterator<T> sourceIterator, boolean parallel) {
        Iterable<T> iterable = () -> sourceIterator;
        return StreamSupport.stream(iterable.spliterator(), parallel);
    }
}

And usage (make sure to statically import asStream):

List<String> aPrefixedStrings = asStream(sourceIterator)
                .filter(t -> t.startsWith("A"))
                .collect(toList());

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

Hopefully I'm not late for the party.

Encountered this using Eclipse Kepler and Maven 3.1.

The solution is to use a JDK and not a JRE for your Eclipse project. Make sure to try maven clean and test from eclipse just to download missing jars.

How to recognize swipe in all 4 directions

In Swift 5,

let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe))
swipeGesture.direction = [.left, .right, .up, .down]
view.addGestureRecognizer(swipeGesture)