Programs & Examples On #Threadabortexception

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

Just put the

Response.End();

within a finally block instead of within the try block.

This has worked for me!!!.

I had the following problematic (with the Exception) code structure

...
Response.Clear();
...
...
try{
 if (something){
   Reponse.Write(...);
   Response.End();

   return;

 } 

 some_more_code...

 Reponse.Write(...);
 Response.End();

}
catch(Exception){
}
finally{}

and it throws the exception. I suspect the Exception is thrown where there is code / work to execute after response.End(); . In my case the extra code was just the return itself.

When I just moved the response.End(); to the finally block (and left the return in its place - which causes skipping the rest of code in the try block and jumping to the finally block (not just exiting the containing function) ) the Exception ceased to take place.

The following works OK:

...
Response.Clear();
...
...
try{
 if (something){
   Reponse.Write(...);

   return;

 } 

 some_more_code...

 Reponse.Write(...);

}
catch(Exception){
}
finally{
    Response.End();
}

Why am I getting "Thread was being aborted" in ASP.NET?

Nope, ThreadAbortException is thrown by a simple Response.Redirect

Why Response.Redirect causes System.Threading.ThreadAbortException?

There is no simple and elegant solution to the Redirect problem in ASP.Net WebForms. You can choose between the Dirty solution and the Tedious solution

Dirty: Response.Redirect(url) sends a redirect to the browser, and then throws a ThreadAbortedException to terminate the current thread. So no code is executed past the Redirect()-call. Downsides: It is bad practice and have performance implications to kill threads like this. Also, ThreadAbortedExceptions will show up in exception logging.

Tedious: The recommended way is to call Response.Redirect(url, false) and then Context.ApplicationInstance.CompleteRequest() However, code execution will continue and the rest of the event handlers in the page lifecycle will still be executed. (E.g. if you perform the redirect in Page_Load, not only will the rest of the handler be executed, Page_PreRender and so on will also still be called - the rendered page will just not be sent to the browser. You can avoid the extra processing by e.g. setting a flag on the page, and then let subsequent event handlers check this flag before before doing any processing.

(The documentation to CompleteRequest states that it "Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution". This can easily be misunderstood. It does bypass further HTTP filters and modules, but it doesn't bypass further events in the current page lifecycle.)

The deeper problem is that WebForms lacks a level of abstraction. When you are in a event handler, you are already in the process of building a page to output. Redirecting in an event handler is ugly because you are terminating a partially generated page in order to generate a different page. MVC does not have this problem since the control flow is separate from rendering views, so you can do a clean redirect by simply returning a RedirectAction in the controller, without generating a view.

Is there a difference between "throw" and "throw ex"?

When you do throw ex, that thrown exception becomes the "original" one. So all previous stack trace will not be there.

If you do throw, the exception just goes down the line and you'll get the full stack trace.

How to create a jQuery plugin with methods?

A simpler approach is to use nested functions. Then you can chain them in an object-oriented fashion. Example:

jQuery.fn.MyPlugin = function()
{
  var _this = this;
  var a = 1;

  jQuery.fn.MyPlugin.DoSomething = function()
  {
    var b = a;
    var c = 2;

    jQuery.fn.MyPlugin.DoSomething.DoEvenMore = function()
    {
      var d = a;
      var e = c;
      var f = 3;
      return _this;
    };

    return _this;
  };

  return this;
};

And here's how to call it:

var pluginContainer = $("#divSomeContainer");
pluginContainer.MyPlugin();
pluginContainer.MyPlugin.DoSomething();
pluginContainer.MyPlugin.DoSomething.DoEvenMore();

Be careful though. You cannot call a nested function until it has been created. So you cannot do this:

var pluginContainer = $("#divSomeContainer");
pluginContainer.MyPlugin();
pluginContainer.MyPlugin.DoSomething.DoEvenMore();
pluginContainer.MyPlugin.DoSomething();

The DoEvenMore function doesn't even exist because the DoSomething function hasn't been run yet which is required to create the DoEvenMore function. For most jQuery plugins, you really are only going to have one level of nested functions and not two as I've shown here.
Just make sure that when you create nested functions that you define these functions at the beginning of their parent function before any other code in the parent function gets executed.

Finally, note that the "this" member is stored in a variable called "_this". For nested functions, you should return "_this" if you need a reference to the instance in the calling client. You cannot just return "this" in the nested function because that will return a reference to the function and not the jQuery instance. Returning a jQuery reference allows you to chain intrinsic jQuery methods on return.

How can I convert a string to a float in mysql?

mysql> SELECT CAST(4 AS DECIMAL(4,3));
+-------------------------+
| CAST(4 AS DECIMAL(4,3)) |
+-------------------------+
|                   4.000 |
+-------------------------+
1 row in set (0.00 sec)

mysql> SELECT CAST('4.5s' AS DECIMAL(4,3));
+------------------------------+
| CAST('4.5s' AS DECIMAL(4,3)) |
+------------------------------+
|                        4.500 |
+------------------------------+
1 row in set (0.00 sec)

mysql> SELECT CAST('a4.5s' AS DECIMAL(4,3));
+-------------------------------+
| CAST('a4.5s' AS DECIMAL(4,3)) |
+-------------------------------+
|                         0.000 |
+-------------------------------+
1 row in set, 1 warning (0.00 sec)

What does it mean by select 1 from table?

The result is 1 for every record in the table. __

400 vs 422 response to POST of data

400 Bad Request is proper HTTP status code for your use case. The code is defined by HTTP/0.9-1.1 RFC.

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

http://tools.ietf.org/html/rfc2616#section-10.4.1

422 Unprocessable Entity is defined by RFC 4918 - WebDav. Note that there is slight difference in comparison to 400, see quoted text below.

This error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

To keep uniform interface you should use 422 only in a case of XML responses and you should also support all status codes defined by Webdav extension, not just 422.

http://tools.ietf.org/html/rfc4918#page-78

See also Mark Nottingham's post on status codes:

it’s a mistake to try to map each part of your application “deeply” into HTTP status codes; in most cases the level of granularity you want to be aiming for is much coarser. When in doubt, it’s OK to use the generic status codes 200 OK, 400 Bad Request and 500 Internal Service Error when there isn’t a better fit.

How to Think About HTTP Status Codes

Javascript form validation with password confirming

add this to your form:

<form  id="regform" action="insert.php" method="post">

add this to your function:

<script>
    function myFunction() {
        var pass1 = document.getElementById("pass1").value;
        var pass2 = document.getElementById("pass2").value;
        if (pass1 != pass2) {
            //alert("Passwords Do not match");
            document.getElementById("pass1").style.borderColor = "#E34234";
            document.getElementById("pass2").style.borderColor = "#E34234";
        }
        else {
            alert("Passwords Match!!!");
            document.getElementById("regForm").submit();
        }
    }
</script>

SQL Server Management Studio, how to get execution time down to milliseconds

I don't know about expanding the information bar.

But you can get the timings set as a default for all queries showing in the "Messages" tab.

When in a Query window, go to the Query Menu item, select "query options" then select "advanced" in the "Execution" group and check the "set statistics time" / "set statistics IO" check boxes. These values will then show up in the messages area for each query without having to remember to put in the set stats on and off.

You could also use Shift + Alt + S to enable client statistics at any time

HTML img onclick Javascript

Developers also take care about accessibility.

Do not use onClick on images without defining the ARIA role.

Non-interactive HTML elements and non-interactive ARIA roles indicate content and containers in the user interface. A non-interactive element does not support event handlers (mouse and key handlers).

The developer and designers are responsible for providing the expected behavior of an element that the role suggests it would have: focusability and key press support. More info see WAI-ARIA Authoring Practices Guide - Design Patterns and Widgets.

tldr; this is how it should be done:

  <img
    src="pond1.jpg"
    alt="pic id code"
    onClick="window.open(this.src)"
    role="button"
    tabIndex="0"
  />

How to call codeigniter controller function from view

Codeigniter is an MVC (Model - View - Controller) framework. It's really not a good idea to call a function from the view. The view should be used just for presentation, and all your logic should be happening before you get to the view in the controllers and models.

A good start for clarifying the best practice is to follow this tutorial:

https://codeigniter.com/user_guide/tutorial/index.html

It's simple, but it really lays out an excellent how-to.

I hope this helps!

C# - using List<T>.Find() with custom objects

Find() will find the element that matches the predicate that you pass as a parameter, so it is not related to Equals() or the == operator.

var element = myList.Find(e => [some condition on e]);

In this case, I have used a lambda expression as a predicate. You might want to read on this. In the case of Find(), your expression should take an element and return a bool.

In your case, that would be:

var reponse = list.Find(r => r.Statement == "statement1")

And to answer the question in the comments, this is the equivalent in .NET 2.0, before lambda expressions were introduced:

var response = list.Find(delegate (Response r) {
    return r.Statement == "statement1";
});

How to disable clicking inside div

If using function onclick DIV and then want to disable click it again you can use this :

for (var i=0;i<document.getElementsByClassName('ads').length;i++){
    document.getElementsByClassName('ads')[i].onclick = false;
}

Example :
HTML

<div id='mybutton'>Click Me</div>

Javascript

document.getElementById('mybutton').onclick = function () {
    alert('You clicked');
    this.onclick = false;
}

base_url() function not working in codeigniter

Check if you have something configured inside the config file /application/config/config.php e.g.

$config['base_url'] = 'http://example.com/';

How to suppress Update Links warning?

Hope to give some extra input in solving this question (or part of it).

This will work for opening an Excel file from another. A line of code from Mr. Peter L., for the change, use the following:

Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx", UpdateLinks:=3

This is in MSDS. The effect is that it just updates everything (yes, everything) with no warning. This can also be checked if you record a macro.

In MSDS, it refers this to MS EXCEL 2010 and 2013. I'm thinking that MS EXCEL 2016 has this covered as well.

I have MS EXCEL 2013, and have a situation pretty much the same as this topic. So I have a file (call it A) with Workbook_Open event code that always get's stuck on the update links prompt. I have another file (call it B) connected to this one, and Pivot Tables force me to open the file A so that the data model can be loaded. Since I want to open the A file silently in the background, I just use the line that I wrote above, with a Windows("A.xlsx").visible = false, and, apart from a bigger loading time, I open the A file from the B file with no problems or warnings, and fully updated.

RequiredIf Conditional Validation Attribute

Expanding on the notes from Adel Mourad and Dan Hunex, I amended the code to provide an example that only accepts values that do not match the given value.

I also found that I didn't need the JavaScript.

I added the following class to my Models folder:

public class RequiredIfNotAttribute : ValidationAttribute, IClientValidatable
{
    private String PropertyName { get; set; }
    private Object InvalidValue { get; set; }
    private readonly RequiredAttribute _innerAttribute;

    public RequiredIfNotAttribute(String propertyName, Object invalidValue)
    {
        PropertyName = propertyName;
        InvalidValue = invalidValue;
        _innerAttribute = new RequiredAttribute();
    }

    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        var dependentValue = context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);

        if (dependentValue.ToString() != InvalidValue.ToString())
        {
            if (!_innerAttribute.IsValid(value))
            {
                return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
            }
        }
        return ValidationResult.Success;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = ErrorMessageString,
            ValidationType = "requiredifnot",
        };
        rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);
        rule.ValidationParameters["invalidvalue"] = InvalidValue is bool ? InvalidValue.ToString().ToLower() : InvalidValue;

        yield return rule;
    }

I didn't need to make any changes to my view, but did make a change to the properties of my model:

    [RequiredIfNot("Id", 0, ErrorMessage = "Please select a Source")]
    public string TemplateGTSource { get; set; }

    public string TemplateGTMedium
    {
        get
        {
            return "Email";
        }
    }

    [RequiredIfNot("Id", 0, ErrorMessage = "Please enter a Campaign")]
    public string TemplateGTCampaign { get; set; }

    [RequiredIfNot("Id", 0, ErrorMessage = "Please enter a Term")]
    public string TemplateGTTerm { get; set; }

Hope this helps!

MySQL select where column is not empty

Check for NULL and empty string values:

select phone
, phone2 
from users 
where phone like '813%' 
and trim(coalesce(phone2, '')) <>''

N.B. I think COALESCE() is SQL standard(-ish), whereas ISNULL() is not.

How do I upload a file with the JS fetch API?

This is a basic example with comments. The upload function is what you are looking for:

// Select your input type file and store it in a variable
const input = document.getElementById('fileinput');

// This will upload the file after having read it
const upload = (file) => {
  fetch('http://www.example.net', { // Your POST endpoint
    method: 'POST',
    headers: {
      // Content-Type may need to be completely **omitted**
      // or you may need something
      "Content-Type": "You will perhaps need to define a content-type here"
    },
    body: file // This is your file object
  }).then(
    response => response.json() // if the response is a JSON object
  ).then(
    success => console.log(success) // Handle the success response object
  ).catch(
    error => console.log(error) // Handle the error response object
  );
};

// Event handler executed when a file is selected
const onSelectFile = () => upload(input.files[0]);

// Add a listener on your input
// It will be triggered when a file will be selected
input.addEventListener('change', onSelectFile, false);

How to get local server host and port in Spring Boot?

To get the port number in your code you can use the following:

@Autowired
Environment environment;

@GetMapping("/test")
String testConnection(){
    return "Your server is up and running at port: "+environment.getProperty("local.server.port");      
}

To understand the Environment property you can go through this Spring boot Environment

What does the line "#!/bin/sh" mean in a UNIX shell script?

#!/bin/sh or #!/bin/bash has to be first line of the script because if you don't use it on the first line then the system will treat all the commands in that script as different commands. If the first line is #!/bin/sh then it will consider all commands as a one script and it will show the that this file is running in ps command and not the commands inside the file.

./echo.sh

ps -ef |grep echo
trainee   3036  2717  0 16:24 pts/0    00:00:00 /bin/sh ./echo.sh
root      3042  2912  0 16:24 pts/1    00:00:00 grep --color=auto echo

Tesseract OCR simple example

This worked for me, I had 3-4 more PDF to Text extractor and if one doesnot work the other one will ... tesseract in particular this code can be used on Windows 7, 8, Server 2008 . Hope this is helpful to you

    do
    {
    // Sleep or Pause the Thread for 1 sec, if service is running too fast...
    Thread.Sleep(millisecondsTimeout: 1000);
    Guid tempGuid = ToSeqGuid();
    string newFileName = tempGuid.ToString().Split('-')[0];
    string outputFileName = appPath + "\\pdf2png\\" + fileNameithoutExtension + "-" + newFileName +
                            ".png";
    extractor.SaveCurrentImageToFile(outputFileName, ImageFormat.Png);
    // Create text file here using Tesseract
    foreach (var file in Directory.GetFiles(appPath + "\\pdf2png"))
    {
        try
        {
            var pngFileName = Path.GetFileNameWithoutExtension(file);
            string[] myArguments =
            {
                "/C tesseract ", file,
                " " + appPath + "\\png2text\\" + pngFileName
            }; // /C for closing process automatically whent completes
            string strParam = String.Join(" ", myArguments);

            var myCmdProcess = new Process();
            var theProcess = new ProcessStartInfo("cmd.exe", strParam)
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                WindowStyle = ProcessWindowStyle.Minimized
            }; // Keep the cmd.exe window minimized
            myCmdProcess.StartInfo = theProcess;
            myCmdProcess.Exited += myCmdProcess_Exited;
            myCmdProcess.Start();

            //if (process)
            {
                /*
                MessageBox.Show("cmd.exe process started: " + Environment.NewLine +
                                "Process Name: " + myCmdProcess.ProcessName +
                                Environment.NewLine + " Process Id: " + myCmdProcess.Id
                                + Environment.NewLine + "process.Handle: " +
                                myCmdProcess.Handle);
                */
                Process.EnterDebugMode();
                //ShowWindow(hWnd: process.Handle, nCmdShow: 2);
                /*
                MessageBox.Show("After EnterDebugMode() cmd.exe process Exited: " +
                                Environment.NewLine +
                                "Process Name: " + myCmdProcess.ProcessName +
                                Environment.NewLine + " Process Id: " + myCmdProcess.Id
                                + Environment.NewLine + "process.Handle: " +
                                myCmdProcess.Handle);
                */
                myCmdProcess.WaitForExit(60000);
                /*
                MessageBox.Show("After WaitForExit() cmd.exe process Exited: " +
                                Environment.NewLine +
                                "Process Name: " + myCmdProcess.ProcessName +
                                Environment.NewLine + " Process Id: " + myCmdProcess.Id
                                + Environment.NewLine + "process.Handle: " +
                                myCmdProcess.Handle);
                */
                myCmdProcess.Refresh();
                Process.LeaveDebugMode();
                //myCmdProcess.Dispose();
                /*
                MessageBox.Show("After LeaveDebugMode() cmd.exe process Exited: " +
                                Environment.NewLine);
                */
            }


            //process.Kill();
            // Waits for the process to complete task and exites automatically
            Thread.Sleep(millisecondsTimeout: 1000);

            // This works fine in Windows 7 Environment, and not in Windows 8
            // Try following code block
            // Check, if process is not comletey exited

            if (!myCmdProcess.HasExited)
            {
                //process.WaitForExit(2000); // Try to wait for exit 2 more seconds
                /*
                MessageBox.Show(" Process of cmd.exe was exited by WaitForExit(); Method " +
                                Environment.NewLine);
                */
                try
                {
                    // If not, then Kill the process
                    myCmdProcess.Kill();
                    //myCmdProcess.Dispose();
                    //if (!myCmdProcess.HasExited)
                    //{
                    //    myCmdProcess.Kill();
                    //}

                    MessageBox.Show(" Process of cmd.exe exited ( Killed ) successfully " +
                                    Environment.NewLine);
                }
                catch (System.ComponentModel.Win32Exception ex)
                {
                    MessageBox.Show(
                        " Exception: System.ComponentModel.Win32Exception " +
                        ex.ErrorCode + Environment.NewLine);
                }
                catch (NotSupportedException notSupporEx)
                {
                    MessageBox.Show(" Exception: NotSupportedException " +
                                    notSupporEx.Message +
                                    Environment.NewLine);
                }
                catch (InvalidOperationException invalidOperation)
                {
                    MessageBox.Show(
                        " Exception: InvalidOperationException " +
                        invalidOperation.Message + Environment.NewLine);
                    foreach (
                        var textFile in Directory.GetFiles(appPath + "\\png2text", "*.txt",
                            SearchOption.AllDirectories))
                    {
                        loggingInfo += textFile +
                                       " In Reading Text from generated text file by Tesseract " +
                                       Environment.NewLine;
                        strBldr.Append(File.ReadAllText(textFile));
                    }
                    // Delete text file after reading text here
                    Directory.GetFiles(appPath + "\\pdf2png").ToList().ForEach(File.Delete);
                    Directory.GetFiles(appPath + "\\png2text").ToList().ForEach(File.Delete);
                }
            }
        }
        catch (Exception exception)
        {
            MessageBox.Show(
                " Cought Exception in Generating image do{...}while{...} function " +
                Environment.NewLine + exception.Message + Environment.NewLine);
        }
    }
    // Delete png image here
    Directory.GetFiles(appPath + "\\pdf2png").ToList().ForEach(File.Delete);
    Thread.Sleep(millisecondsTimeout: 1000);
    // Read text from text file here
    foreach (var textFile in Directory.GetFiles(appPath + "\\png2text", "*.txt",
        SearchOption.AllDirectories))
    {
        loggingInfo += textFile +
                       " In Reading Text from generated text file by Tesseract " +
                       Environment.NewLine;
        strBldr.Append(File.ReadAllText(textFile));
    }
    // Delete text file after reading text here
    Directory.GetFiles(appPath + "\\png2text").ToList().ForEach(File.Delete);
} while (extractor.GetNextImage()); // Advance image enumeration... 

Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'

I needed a package from github that was written in typscript. I did a git pull of the most recent version from the master branch into the root of my main project. I then went into the directory and did an npm install so that the gulp commands would work that generates ES5 modules. Anyway, to make the long story short, my build process was trying to build files from this new folder so I had to move it out of my root. This was causing these same errors.

Copy and Paste a set range in the next empty row

The reason the code isn't working is because lastrow is measured from whatever sheet is currently active, and "A:A500" (or other number) is not a valid range reference.

Private Sub CommandButton1_Click()
    Dim lastrow As Long

    lastrow = Sheets("Summary Info").Range("A65536").End(xlUp).Row    ' or + 1
    Range("A3:E3").Copy Destination:=Sheets("Summary Info").Range("A" & lastrow)
End Sub

How to change TextBox's Background color?

In WinForms and WebForms you can do:

txtName.BackColor = Color.Aqua;

CSS: On hover show and hide different div's at the same time?

http://jsfiddle.net/MBLZx/

Here is the code

_x000D_
_x000D_
 .showme{ _x000D_
   display: none;_x000D_
 }_x000D_
 .showhim:hover .showme{_x000D_
   display : block;_x000D_
 }_x000D_
 .showhim:hover .ok{_x000D_
   display : none;_x000D_
 }
_x000D_
 <div class="showhim">_x000D_
     HOVER ME_x000D_
     <div class="showme">hai</div>_x000D_
     <div class="ok">ok</div>_x000D_
</div>_x000D_
_x000D_
   
_x000D_
_x000D_
_x000D_

How to resolve Unneccessary Stubbing exception

If you're using this style instead:

@Rule
public MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);

replace it with:

@Rule
public MockitoRule rule = MockitoJUnit.rule().silent();

Using FileSystemWatcher to monitor a directory

You did not supply the file handling code, but I assume you made the same mistake everyone does when first writing such a thing: the filewatcher event will be raised as soon as the file is created. However, it will take some time for the file to be finished. Take a file size of 1 GB for example. The file may be created by another program (Explorer.exe copying it from somewhere) but it will take minutes to finish that process. The event is raised at creation time and you need to wait for the file to be ready to be copied.

You can wait for a file to be ready by using this function in a loop.

Batch files: How to read a file?

Well theres a lot of different ways but if you only want to DISPLAY the text and not STORE it anywhere then you just use: findstr /v "randomtextthatnoonewilluse" filename.txt

Javascript dynamic array of strings

As far as I know, Javascript has dynamic arrays. You can add,delete and modify the elements on the fly.

var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.push(11);
document.writeln(myArray);  // Gives 1,2,3,4,5,6,7,8,9,10,11


var myArray = [1,2,3,4,5,6,7,8,9,10];
var popped = myArray.pop();
document.writeln(myArray);  // Gives 1,2,3,4,5,6,7,8,9

You can even add elements like

var myArray = new Array()
myArray[0] = 10
myArray[1] = 20
myArray[2] = 30

you can even change the values

myArray[2] = 40

Printing Order

If you want in the same order, this would suffice. Javascript prints the values in the order of key values. If you have inserted values in the array in monotonically increasing key values, then they will be printed in the same way unless you want to change the order.

Page Submission

If you are using JavaScript you don't even need to submit the values to the different page. You can even show the data on the same page by manipulating the DOM.

C# Error "The type initializer for ... threw an exception

I got this error when I modified an Nlog configuration file and didn't format the XML correctly.

Use 'import module' or 'from module import'?

Import Module - You don't need additional efforts to fetch another thing from module. It has disadvantages such as redundant typing

Module Import From - Less typing &More control over which items of a module can be accessed.To use a new item from the module you have to update your import statement.

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

nginx: send all requests to a single html page

This worked for me:

location / {
    try_files $uri $uri/ /base.html;
}

jQuery get values of checked checkboxes into array

Do not use "each". It is used for operations and changes in the same element. Use "map" to extract data from the element body and using it somewhere else.

Change the color of cells in one column when they don't match cells in another column

you could try this:

I have these two columns (column "A" and column "B"). I want to color them when the values between cells in the same row mismatch.

Follow these steps:

  1. Select the elements in column "A" (excluding A1);

  2. Click on "Conditional formatting -> New Rule -> Use a formula to determine which cells to format";

  3. Insert the following formula: =IF(A2<>B2;1;0);

  4. Select the format options and click "OK";

  5. Select the elements in column "B" (excluding B1) and repeat the steps from 2 to 4.

Exception thrown in catch and finally clause

Based on reading your answer and seeing how you likely came up with it, I believe you think an "exception-in-progress" has "precedence". Keep in mind:

When an new exception is thrown in a catch block or finally block that will propagate out of that block, then the current exception will be aborted (and forgotten) as the new exception is propagated outward. The new exception starts unwinding up the stack just like any other exception, aborting out of the current block (the catch or finally block) and subject to any applicable catch or finally blocks along the way.

Note that applicable catch or finally blocks includes:

When a new exception is thrown in a catch block, the new exception is still subject to that catch's finally block, if any.

Now retrace the execution remembering that, whenever you hit throw, you should abort tracing the current exception and start tracing the new exception.

PHP add elements to multidimensional array with array_push

As in the multi-dimensional array an entry is another array, specify the index of that value to array_push:

array_push($md_array['recipe_type'], $newdata);

How to calculate the sum of the datatable column in asp.net?

I think this solves

using System.Linq;


(datagridview1.DataSource as DataTable).AsEnumerable().Sum(c => c.Field<double>("valor"))

Definition of int64_t

int64_t is typedef you can find that in <stdint.h> in C

Convert array to JSON

The shortest way I know to generate valid json from array of integers is

let json = `[${cars}]`

for more general object/array use JSON.stringify(cars) (for object with circular references use this)

_x000D_
_x000D_
let cars = [1,2,3]; cars.push(4,5,6);

let json = `[${cars}]`;

console.log(json);
console.log(JSON.parse(json)); // json validation
_x000D_
_x000D_
_x000D_

Styling multi-line conditions in 'if' statements?

Pack your conditions into a list, then do smth. like:

if False not in Conditions:
    do_something

Laravel Eloquent: How to get only certain columns from joined tables

I know that this is an old question, but if you are building an API, as the author of the question does, use output transformers to perform such tasks.

Transofrmer is a layer between your actual database query result and a controller. It allows to easily control and modify what is going to be output to a user or an API consumer.

I recommend Fractal as a solid foundation of your output transformation layer. You can read the documentation here.

How to run functions in parallel?

This can be done elegantly with Ray, a system that allows you to easily parallelize and distribute your Python code.

To parallelize your example, you'd need to define your functions with the @ray.remote decorator, and then invoke them with .remote.

import ray

ray.init()

dir1 = 'C:\\folder1'
dir2 = 'C:\\folder2'
filename = 'test.txt'
addFiles = [25, 5, 15, 35, 45, 25, 5, 15, 35, 45]

# Define the functions. 
# You need to pass every global variable used by the function as an argument.
# This is needed because each remote function runs in a different process,
# and thus it does not have access to the global variables defined in 
# the current process.
@ray.remote
def func1(filename, addFiles, dir):
    # func1() code here...

@ray.remote
def func2(filename, addFiles, dir):
    # func2() code here...

# Start two tasks in the background and wait for them to finish.
ray.get([func1.remote(filename, addFiles, dir1), func2.remote(filename, addFiles, dir2)]) 

If you pass the same argument to both functions and the argument is large, a more efficient way to do this is using ray.put(). This avoids the large argument to be serialized twice and to create two memory copies of it:

largeData_id = ray.put(largeData)

ray.get([func1(largeData_id), func2(largeData_id)])

Important - If func1() and func2() return results, you need to rewrite the code as follows:

ret_id1 = func1.remote(filename, addFiles, dir1)
ret_id2 = func2.remote(filename, addFiles, dir2)
ret1, ret2 = ray.get([ret_id1, ret_id2])

There are a number of advantages of using Ray over the multiprocessing module. In particular, the same code will run on a single machine as well as on a cluster of machines. For more advantages of Ray see this related post.

Foreign key constraint may cause cycles or multiple cascade paths?

A typical situation with multiple cascasing paths will be this: A master table with two details, let's say "Master" and "Detail1" and "Detail2". Both details are cascade delete. So far no problems. But what if both details have a one-to-many-relation with some other table (say "SomeOtherTable"). SomeOtherTable has a Detail1ID-column AND a Detail2ID-column.

Master { ID, masterfields }

Detail1 { ID, MasterID, detail1fields }

Detail2 { ID, MasterID, detail2fields }

SomeOtherTable {ID, Detail1ID, Detail2ID, someothertablefields }

In other words: some of the records in SomeOtherTable are linked with Detail1-records and some of the records in SomeOtherTable are linked with Detail2 records. Even if it is guaranteed that SomeOtherTable-records never belong to both Details, it is now impossible to make SomeOhterTable's records cascade delete for both details, because there are multiple cascading paths from Master to SomeOtherTable (one via Detail1 and one via Detail2). Now you may already have understood this. Here is a possible solution:

Master { ID, masterfields }

DetailMain { ID, MasterID }

Detail1 { DetailMainID, detail1fields }

Detail2 { DetailMainID, detail2fields }

SomeOtherTable {ID, DetailMainID, someothertablefields }

All ID fields are key-fields and auto-increment. The crux lies in the DetailMainId fields of the Detail tables. These fields are both key and referential contraint. It is now possible to cascade delete everything by only deleting master-records. The downside is that for each detail1-record AND for each detail2 record, there must also be a DetailMain-record (which is actually created first to get the correct and unique id).

Conversion of a datetime2 data type to a datetime data type results out-of-range value

Check out the following two: 1) This field has no NULL value. For example:

 public DateTime MyDate { get; set; }

Replace to:

public DateTime MyDate { get; set; }=DateTime.Now;

2) New the database again. For example:

db=new MyDb();

How to add not null constraint to existing column in MySQL

Try this, you will know the difference between change and modify,

ALTER TABLE table_name CHANGE curr_column_name new_column_name new_column_datatype [constraints]

ALTER TABLE table_name MODIFY column_name new_column_datatype [constraints]
  • You can change name and datatype of the particular column using CHANGE.
  • You can modify the particular column datatype using MODIFY. You cannot change the name of the column using this statement.

Hope, I explained well in detail.

Run JavaScript code on window close or page refresh?

There is both window.onbeforeunload and window.onunload, which are used differently depending on the browser. You can assign them either by setting the window properties to functions, or using the .addEventListener:

window.onbeforeunload = function(){
   // Do something
}
// OR
window.addEventListener("beforeunload", function(e){
   // Do something
}, false);
   

Usually, onbeforeunload is used if you need to stop the user from leaving the page (ex. the user is working on some unsaved data, so he/she should save before leaving). onunload isn't supported by Opera, as far as I know, but you could always set both.

Why doesn't height: 100% work to expand divs to the screen height?

You will also need to set 100% height on the html element:

html { height:100%; }

Set opacity of background image without affecting child elements

I found a pretty good and simple tutorial about this issue. I think it works great (and though it supports IE, I just tell my clients to use other browsers):

CSS background transparency without affecting child elements, through RGBa and filters

From there you can add gradient support, etc.

Stripping non printable characters from a string in python

In Python 3,

def filter_nonprintable(text):
    import itertools
    # Use characters of control category
    nonprintable = itertools.chain(range(0x00,0x20),range(0x7f,0xa0))
    # Use translate to remove all non-printable characters
    return text.translate({character:None for character in nonprintable})

See this StackOverflow post on removing punctuation for how .translate() compares to regex & .replace()

The ranges can be generated via nonprintable = (ord(c) for c in (chr(i) for i in range(sys.maxunicode)) if unicodedata.category(c)=='Cc') using the Unicode character database categories as shown by @Ants Aasma.

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

Add this code to the beginning:

    Application.ScreenUpdating = False
     With ThisWorkbook
      Dim ws As Worksheet
       For Each ws In Worksheets: ws.Visible = True: Next ws
     End With

Add this code to the end:

    With ThisWorkbook
     Dim ws As Worksheet
      For Each ws In Worksheets: ws.Visible = False: Next ws
    End With
     Application.ScreenUpdating = True

Adjust Code at the end if you want more than the first sheet to be active and visible. Such as the following:

     Dim ws As Worksheet
      For Each ws In Worksheets
       If ws.Name = "_DataRecords" Then

         Else: ws.Visible = False
       End If
      Next ws

To ensure the new sheet is the one renamed, adjust your code similar to the following:

     Sheets(Me.cmbxSheetCopy.value).Copy After:=Sheets(Sheets.Count)
     Sheets(Me.cmbxSheetCopy.value & " (2)").Select
     Sheets(Me.cmbxSheetCopy.value & " (2)").Name = txtbxNewSheetName.value

This code is from my user form that allows me to copy a particular sheet (chosen from a dropdown box) with the formatting and formula's that I want to a new sheet and then rename new sheet with the user Input. Note that every time a sheet is copied it is automatically given the old sheet name with the designation of " (2)". Example "OldSheet" becomes "OldSheet (2)" after the copy and before the renaming. So you must select the Copied sheet with the programs naming before renaming.

How to search in a List of Java object

You can give a try to Apache Commons Collections.

There is a class CollectionUtils that allows you to select or filter items by custom Predicate.

Your code would be like this:

Predicate condition = new Predicate() {
   boolean evaluate(Object sample) {
        return ((Sample)sample).value3.equals("three");
   }
};
List result = CollectionUtils.select( list, condition );

Update:

In java8, using Lambdas and StreamAPI this should be:

List<Sample> result = list.stream()
     .filter(item -> item.value3.equals("three"))
     .collect(Collectors.toList());

much nicer!

How can I get the current screen orientation?

int orientation = this.getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
    // code for portrait mode
} else {
    // code for landscape mode
}

When the superclass of this is Context

Pseudo-terminal will not be allocated because stdin is not a terminal

I don't know where the hang comes from, but redirecting (or piping) commands into an interactive ssh is in general a recipe for problems. It is more robust to use the command-to-run-as-a-last-argument style and pass the script on the ssh command line:

ssh user@server 'DEP_ROOT="/home/matthewr/releases"
datestamp=$(date +%Y%m%d%H%M%S)
REL_DIR=$DEP_ROOT"/"$datestamp
if [ ! -d "$DEP_ROOT" ]; then
    echo "creating the root directory"
    mkdir $DEP_ROOT
fi
mkdir $REL_DIR'

(All in one giant '-delimited multiline command-line argument).

The pseudo-terminal message is because of your -t which asks ssh to try to make the environment it runs on the remote machine look like an actual terminal to the programs that run there. Your ssh client is refusing to do that because its own standard input is not a terminal, so it has no way to pass the special terminal APIs onwards from the remote machine to your actual terminal at the local end.

What were you trying to achieve with -t anyway?

What is the difference between ndarray and array in numpy?

numpy.array is a function that returns a numpy.ndarray. There is no object type numpy.array.

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

You're using an array of objects. Can you use a two dimensional array instead?

http://www.datatables.net/examples/data_sources/js_array.html

See this jsfiddle: http://jsfiddle.net/QhYse/

I used an array like this and it worked fine:

var data = [
    ["UpdateBootProfile","PASS","00:00:00",[]] ,
    ["NRB Boot","PASS","00:00:50.5000000",[{"TestName":"TOTAL_TURN_ON_TIME","Result":"PASS","Value":"50.5","LowerLimit":"NaN","UpperLimit":"NaN","ComparisonType":"nctLOG","Units":"SECONDS"}]] ,
    ["NvMgrCommit","PASS","00:00:00",[]] ,
    ["SyncNvToEFS","PASS","00:00:01.2500000",[]]
];

Edit to include array of objects

There's a possible solution from this question: jQuery DataTables fnrender with objects

This jsfiddle http://jsfiddle.net/j2C7j/ uses an array of objects. To not get the error I had to pad it with 3 blank values - less than optimal, I know. You may find a better way with fnRender, please post if you do.

var data = [
   ["","","", {"Name":"UpdateBootProfile","Result":"PASS","ExecutionTime":"00:00:00","Measurement":[]} ]

];

$(function() {
        var testsTable = $('#tests').dataTable({
                bJQueryUI: true,
                aaData: data,
                aoColumns: [
                        { mData: 'Name', "fnRender": function( oObj ) { return oObj.aData[3].Name}},
                        { mData: 'Result' ,"fnRender": function( oObj ) { return oObj.aData[3].Result }},
                        { mData: 'ExecutionTime',"fnRender": function( oObj ) { return oObj.aData[3].ExecutionTime } }
                ]
        });
});

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

This isn't the only reason for the error. I encountered it just now for a typo error in my coding, which I believe, set a value of an entity which was already saved.

X x2 = new X();
x.setXid(memberid); // Error happened here - x was a previous global entity I created earlier
Y.setX(x2);

I spotted the error by finding exactly which variable caused the error (in this case String xid). I used a catch around the whole block of code that saved the entity and printed the traces.

{
   code block that performed the operation
} catch (Exception e) {
   e.printStackTrace(); // put a break-point here and inspect the 'e'
   return ERROR;
}

Split data frame string column into multiple columns

Use stringr::str_split_fixed

library(stringr)
str_split_fixed(before$type, "_and_", 2)

How to set null to a GUID property

Is there a way to set my property as null or string.empty in order to restablish the field in the database as null.

No. Because it's non-nullable. If you want it to be nullable, you have to use Nullable<Guid> - if you didn't, there'd be no point in having Nullable<T> to start with. You've got a fundamental issue here - which you actually know, given your first paragraph. You've said, "I know if I want to achieve A, I must do B - but I want to achieve A without doing B." That's impossible by definition.

The closest you can get is to use one specific GUID to stand in for a null value - Guid.Empty (also available as default(Guid) where appropriate, e.g. for the default value of an optional parameter) being the obvious candidate, but one you've rejected for unspecified reasons.

JQuery add class to parent element

$(this.parentNode).addClass('newClass');

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

I have a similar issue, have you tried:

proxy.ClientCredentials.Windows.AllowedImpersonationLevel =   
          System.Security.Principal.TokenImpersonationLevel.Impersonation;

Histogram Matplotlib

If you don't want bars you can plot it like this:

import numpy as np
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

bins, edges = np.histogram(x, 50, normed=1)
left,right = edges[:-1],edges[1:]
X = np.array([left,right]).T.flatten()
Y = np.array([bins,bins]).T.flatten()

plt.plot(X,Y)
plt.show()

histogram

jquery <a> tag click event

<a href="javascript:void(0)" class="aaf" id="users_id">add as a friend</a>

on jquery

$('.aaf').on("click",function(){
  var usersid =  $(this).attr("id");
  //post code
})

//other method is to use the data attribute

<a href="javascript:void(0)" class="aaf" data-id="102" data-username="sample_username">add as a friend</a>

on jquery

$('.aaf').on("click",function(){
    var usersid =  $(this).data("id");
    var username = $(this).data("username");
})

How to use boolean datatype in C?

If you have a compiler that supports C99 you can

#include <stdbool.h>

Otherwise, you can define your own if you'd like. Depending on how you want to use it (and whether you want to be able to compile your code as C++), your implementation could be as simple as:

#define bool int
#define true 1
#define false 0

In my opinion, though, you may as well just use int and use zero to mean false and nonzero to mean true. That's how it's usually done in C.

Effects of the extern keyword on C functions

We have two files, foo.c and bar.c.

Here is foo.c

#include <stdio.h>

volatile unsigned int stop_now = 0;
extern void bar_function(void);

int main(void)
{
  while (1) {
     bar_function();
     stop_now = 1;
  }
  return 0;
}

Now, here is bar.c

#include <stdio.h>

extern volatile unsigned int stop_now;

void bar_function(void)
{
   if (! stop_now) {
      printf("Hello, world!\n");
      sleep(30);
   }
}

As you can see, we have no shared header between foo.c and bar.c , however bar.c needs something declared in foo.c when it's linked, and foo.c needs a function from bar.c when it's linked.

By using 'extern', you are telling the compiler that whatever follows it will be found (non-static) at link time; don't reserve anything for it in the current pass since it will be encountered later. Functions and variables are treated equally in this regard.

It's very useful if you need to share some global between modules and don't want to put / initialize it in a header.

Technically, every function in a library public header is 'extern', however labeling them as such has very little to no benefit, depending on the compiler. Most compilers can figure that out on their own. As you see, those functions are actually defined somewhere else.

In the above example, main() would print hello world only once, but continue to enter bar_function(). Also note, bar_function() is not going to return in this example (since it's just a simple example). Just imagine stop_now being modified when a signal is serviced (hence, volatile) if this doesn't seem practical enough.

Externs are very useful for things like signal handlers, a mutex that you don't want to put in a header or structure, etc. Most compilers will optimize to ensure that they don't reserve any memory for external objects, since they know they'll be reserving it in the module where the object is defined. However, again, there's little point in specifying it with modern compilers when prototyping public functions.

Hope that helps :)

Make child div stretch across width of page

you can pull it out of the flow by setting position:absolute on it, but you'll have different display issues to deal with. Or you can explicitly set the width to > 960.

How to convert Django Model object to dict with its fields and values?

Simplest way,

  1. If your query is Model.Objects.get():

    get() will return single instance so you can direct use __dict__ from your instance

    model_dict = Model.Objects.get().__dict__

  2. for filter()/all():

    all()/filter() will return list of instances so you can use values() to get list of objects.

    model_values = Model.Objects.all().values()

Excel VBA Check if directory exists error

You can replace WB_parentfolder with something like "C:\". For me WB_parentfolder is grabbing the location of the current workbook. file_des_folder is the new folder i want. This goes through and creates as many folders as you need.

        folder1 = Left(file_des_folder, InStr(Len(WB_parentfolder) + 1, file_loc, "\"))
        Do While folder1 <> file_des_folder
            folder1 = Left(file_des_folder, InStr(Len(folder1) + 1, file_loc, "\"))
            If Dir(file_des_folder, vbDirectory) = "" Then      'create folder if there is not one
                MkDir folder1
            End If
        Loop

How to have an auto incrementing version number (Visual Studio)?

Here's the quote on AssemblyInfo.cs from MSDN:

You can specify all the values or you can accept the default build number, revision number, or both by using an asterisk (). For example, [assembly:AssemblyVersion("2.3.25.1")] indicates 2 as the major version, 3 as the minor version, 25 as the build number, and 1 as the revision number. A version number such as [assembly:AssemblyVersion("1.2.")] specifies 1 as the major version, 2 as the minor version, and accepts the default build and revision numbers. A version number such as [assembly:AssemblyVersion("1.2.15.*")] specifies 1 as the major version, 2 as the minor version, 15 as the build number, and accepts the default revision number. The default build number increments daily. The default revision number is random

This effectively says, if you put a 1.1.* into assembly info, only build number will autoincrement, and it will happen not after every build, but daily. Revision number will change every build, but randomly, rather than in an incrementing fashion.

This is probably enough for most use cases. If that's not what you're looking for, you're stuck with having to write a script which will autoincrement version # on pre-build step

What do numbers using 0x notation mean?

In C and languages based on the C syntax, the prefix 0x means hexadecimal (base 16).

Thus, 0x400 = 4×(162) + 0×(161) + 0×(160) = 4×((24)2) = 22 × 28 = 210 = 1024, or one binary K.

And so 0x6400 = 0x4000 + 0x2400 = 0x19×0x400 = 25K

How do I link a JavaScript file to a HTML file?

Below you have some VALID html5 example document. The type attribute in script tag is not mandatory in HTML5.

You use jquery by $ charater. Put libraries (like jquery) in <head> tag - but your script put allways at the bottom of document (<body> tag) - due this you will be sure that all libraries and html document will be loaded when your script execution starts. You can also use src attribute in bottom script tag to include you script file instead of putting direct js code like above.

_x000D_
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="utf-8">_x000D_
    <title>Example</title>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
    <div>Im the content</div>_x000D_
_x000D_
    <script>_x000D_
        alert( $('div').text() ); // show message with div content_x000D_
    </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Send Email to multiple Recipients with MailMessage?

As suggested by Adam Miller in the comments, I'll add another solution.

The MailMessage(String from, String to) constructor accepts a comma separated list of addresses. So if you happen to have already a comma (',') separated list, the usage is as simple as:

MailMessage Msg = new MailMessage(fromMail, addresses);

In this particular case, we can replace the ';' for ',' and still make use of the constructor.

MailMessage Msg = new MailMessage(fromMail, addresses.replace(";", ","));

Whether you prefer this or the accepted answer it's up to you. Arguably the loop makes the intent clearer, but this is shorter and not obscure. But should you already have a comma separated list, I think this is the way to go.

How do I pass JavaScript values to Scriptlet in JSP?

I can provide two ways,

a.jsp,

<html>
    <script language="javascript" type="text/javascript">
        function call(){
            var name = "xyz";
            window.location.replace("a.jsp?name="+name);
        }
    </script>
    <input type="button" value="Get" onclick='call()'>
    <%
        String name=request.getParameter("name");
        if(name!=null){
            out.println(name);
        }
    %>
</html>

b.jsp,

<script>
    var v="xyz";
</script>
<% 
    String st="<script>document.writeln(v)</script>";
    out.println("value="+st); 
%>

How to get a complete list of ticker symbols from Yahoo Finance?

I may be able to help with a list of ticker symbols for (U.S. and non-U.S.) stocks and for ETFs.

Yahoo provides an Earnings Calendar that lists all the stocks that announce earnings for a given day. This includes non-US stocks.

For example, here is today's: http://biz.yahoo.com/research/earncal/20120710.html

the last part of the URL is the date (in YYYYMMDD format) for which you want the Earnings Calendar. You can loop through several days and scrape the Symbols of all stocks that reported earnings on those days.

There is no guarantee that yahoo has data for all stocks that report earnings, especially since some stocks no longer exist (bankruptcy, acquisition, etc.), but this is probably a decent starting point.

If you are familiar with R, you can use the qmao package to do this. (See this post) if you have trouble installing it.

ec <- getEarningsCalendar(from="2011-01-01", to="2012-07-01") #this may take a while
s <- unique(ec$Symbol)
length(s)
#[1] 12223
head(s, 20) #look at the first 20 Symbols
# [1] "CVGW"    "ANGO"    "CAMP"    "LNDC"    "MOS"     "NEOG"    "SONC"   
# [8] "TISI"    "SHLM"    "FDO"     "FC"      "JPST.PK" "RECN"    "RELL"   
#[15] "RT"      "UNF"     "WOR"     "WSCI"    "ZEP"     "AEHR"   

This will not include any ETFs, futures, options, bonds, forex or mutual funds.

You can get a list of ETFs from yahoo here: http://finance.yahoo.com/etf/browser/mkt That only shows the first 20. You need the URL of the "Show All" link at the bottom of that page. You can scrape the page to find out how many ETFs there are, then construct a URL.

L <- readLines("http://finance.yahoo.com/etf/browser/mkt")
# Sorry for the ugly regex
n <- gsub("^(\\w+)\\s?(.*)$", "\\1", 
          gsub("(.*)(Showing 1 - 20 of )(.*)", "\\3",  
               L[grep("Showing 1 - 20", L)]))
URL <- paste0("http://finance.yahoo.com/etf/browser/mkt?c=0&k=5&f=0&o=d&cs=1&ce=", n)
#http://finance.yahoo.com/etf/browser/mkt?c=0&k=5&f=0&o=d&cs=1&ce=1442

Now, you can extract the Tickers from the table on that page

library(XML)
tbl <- readHTMLTable(URL, stringsAsFactors=FALSE)
dat <- tbl[[tail(grep("Ticker", tbl), 1)]][-1, ]
colnames(dat) <- dat[1, ]
dat <- dat[-1, ]
etfs <- dat$Ticker # All ETF tickers from yahoo
length(etfs)
#[1] 1442
head(etfs)
#[1] "DGAZ" "TAGS" "GASX" "KOLD" "DWTI" "RTSA"

That's about all the help I can offer, but you could do something similar to get some of the futures they offer by scraping these pages (These are only U.S. futures)

http://finance.yahoo.com/indices?e=futures, http://finance.yahoo.com/futures?t=energy, http://finance.yahoo.com/futures?t=metals, http://finance.yahoo.com/futures?t=grains, http://finance.yahoo.com/futures?t=livestock, http://finance.yahoo.com/futures?t=softs, http://finance.yahoo.com/futures?t=indices,

And, for U.S. and non-U.S. indices, you could scrape these pages

http://finance.yahoo.com/intlindices?e=americas, http://finance.yahoo.com/intlindices?e=asia, http://finance.yahoo.com/intlindices?e=europe, http://finance.yahoo.com/intlindices?e=africa, http://finance.yahoo.com/indices?e=dow_jones, http://finance.yahoo.com/indices?e=new_york, http://finance.yahoo.com/indices?e=nasdaq, http://finance.yahoo.com/indices?e=sp, http://finance.yahoo.com/indices?e=other, http://finance.yahoo.com/indices?e=treasury, http://finance.yahoo.com/indices?e=commodities

How to check the exit status using an if statement

Every command that runs has an exit status.

That check is looking at the exit status of the command that finished most recently before that line runs.

If you want your script to exit when that test returns true (the previous command failed) then you put exit 1 (or whatever) inside that if block after the echo.

That being said if you are running the command and wanting to test its output using the following is often more straight-forward.

if some_command; then
    echo command returned true
else
    echo command returned some error
fi

Or to turn that around use ! for negation

if ! some_command; then
    echo command returned some error
else
    echo command returned true
fi

Note though that neither of those cares what the error code is. If you know you only care about a specific error code then you need to check $? manually.

C# List of objects, how do I get the sum of a property

using System.Linq;

...

double total = myList.Sum(item => item.Amount);

Spring Boot - inject map from application.yml

Below solution is a shorthand for @Andy Wilkinson's solution, except that it doesn't have to use a separate class or on a @Bean annotated method.

application.yml:

input:
  name: raja
  age: 12
  somedata:
    abcd: 1 
    bcbd: 2
    cdbd: 3

SomeComponent.java:

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "input")
class SomeComponent {

    @Value("${input.name}")
    private String name;

    @Value("${input.age}")
    private Integer age;

    private HashMap<String, Integer> somedata;

    public HashMap<String, Integer> getSomedata() {
        return somedata;
    }

    public void setSomedata(HashMap<String, Integer> somedata) {
        this.somedata = somedata;
    }

}

We can club both @Value annotation and @ConfigurationProperties, no issues. But getters and setters are important and @EnableConfigurationProperties is must to have the @ConfigurationProperties to work.

I tried this idea from groovy solution provided by @Szymon Stepniak, thought it will be useful for someone.

WCF gives an unsecured or incorrectly secured fault error

I've also had this problem from a service reference that was out of date, even with the server & client on the same machine. Running 'Update Service Reference' will generally fix it if this is the issue.

Difference between Constructor and ngOnInit

Constructor: The constructor method on an ES6 class (or TypeScript in this case) is a feature of a class itself, rather than an Angular feature. It’s out of Angular’s control when the constructor is invoked, which means that it’s not a suitable hook to let you know when Angular has finished initialising the component. JavaScript engine calls the constructor, not Angular directly. Which is why the ngOnInit (and $onInit in AngularJS) lifecycle hook was created. Bearing this in mind, there is a suitable scenario for using the constructor. This is when we want to utilise dependency injection - essentially for “wiring up” dependencies into the component.

As the constructor is initialised by the JavaScript engine, and TypeScript allows us to tell Angular what dependencies we require to be mapped against a specific property.

ngOnInit is purely there to give us a signal that Angular has finished initialising the component.

This phase includes the first pass at Change Detection against the properties that we may bind to the component itself - such as using an @Input() decorator.

Due to this, the @Input() properties are available inside ngOnInit, however are undefined inside the constructor, by design

How to call function that takes an argument in a Django template?

You cannot call a function that requires arguments in a template. Write a template tag or filter instead.

How to check if string input is a number?

try this! it worked for me even if I input negative numbers.

  def length(s):
    return len(s)

   s = input("Enter the String: ")
    try:
        if (type(int(s)))==int :
            print("You input an integer")

    except ValueError:      
        print("it is a string with length " + str(length(s)))   

VBA Macro to compare all cells of two Excel files

Do NOT loop through all cells!! There is a lot of overhead in communications between worksheets and VBA, for both reading and writing. Looping through all cells will be agonizingly slow. I'm talking hours.

Instead, load an entire sheet at once into a Variant array. In Excel 2003, this takes about 2 seconds (and 250 MB of RAM). Then you can loop through it in no time at all.

In Excel 2007 and later, sheets are about 1000 times larger (1048576 rows × 16384 columns = 17 billion cells, compared to 65536 rows × 256 columns = 17 million in Excel 2003). You will run into an "Out of memory" error if you try to load the whole sheet into a Variant; on my machine I can only load 32 million cells at once. So you have to limit yourself to the range you know has actual data in it, or load the sheet bit by bit, e.g. 30 columns at a time.

Option Explicit

Sub test()

    Dim varSheetA As Variant
    Dim varSheetB As Variant
    Dim strRangeToCheck As String
    Dim iRow As Long
    Dim iCol As Long

    strRangeToCheck = "A1:IV65536"
    ' If you know the data will only be in a smaller range, reduce the size of the ranges above.
    Debug.Print Now
    varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
    varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
    Debug.Print Now

    For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
        For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
            If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
                ' Cells are identical.
                ' Do nothing.
            Else
                ' Cells are different.
                ' Code goes here for whatever it is you want to do.
            End If
        Next iCol
    Next iRow

End Sub

To compare to a sheet in a different workbook, open that workbook and get the sheet as follows:

Set wbkA = Workbooks.Open(filename:="C:\MyBook.xls")
Set varSheetA = wbkA.Worksheets("Sheet1") ' or whatever sheet you need

How to set editor theme in IntelliJ Idea

For IntelliJ in Mac

View -> Quick Switch theme (^`)-> color schema

Calculate distance between two latitude-longitude points? (Haversine formula)

Here's another converted to Ruby code:

include Math
#Note: from/to = [lat, long]

def get_distance_in_km(from, to)
  radians = lambda { |deg| deg * Math.PI / 180 }
  radius = 6371 # Radius of the earth in kilometer
  dLat = radians[to[0]-from[0]]
  dLon = radians[to[1]-from[1]]

  cosines_product = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(radians[from[0]]) * Math.cos(radians[to[1]]) * Math.sin(dLon/2) * Math.sin(dLon/2)

  c = 2 * Math.atan2(Math.sqrt(cosines_product), Math.sqrt(1-cosines_product)) 
  return radius * c # Distance in kilometer
end

Model backing a DB Context has changed; Consider Code First Migrations

To solve this error write the the following code in Application_Start() Method in Global.asax.cs file

Database.SetInitializer<MyDbContext>(null);

How to check how many letters are in a string in java?

1) To answer your question:

  String s="Java";
  System.out.println(s.length()); 

Getting the error "Missing $ inserted" in LaTeX

I had this problem too. I solved it by removing the unnecessary blank line between equation tags. This gives the error:

\begin{equation}
P(\underline{\hat{X}} | \underline{Y}) = ...

\end{equation}

while this code compiles succesfully:

\begin{equation}
P(\underline{\hat{X}} | \underline{Y}) = ...
\end{equation}

How to replace url parameter with javascript/jquery?

UpdatE: Make it into a nice function for you: http://jsfiddle.net/wesbos/KH25r/1/

function swapOutSource(url, newSource) {
    params = url.split('&');
    var src = params[0].split('=');
    params.shift();
    src[1] = newSource;
    var newUrl = ( src.join('=') + params.join('&')); 
    return newUrl; 
}

Then go at it!

var newUrl = swapOutSource("http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100","http://link/to/new.jpg");


console.log(newUrl);

Suppress Scientific Notation in Numpy When Creating Array From Nested List

Python Force-suppress all exponential notation when printing numpy ndarrays, wrangle text justification, rounding and print options:

What follows is an explanation for what is going on, scroll to bottom for code demos.

Passing parameter suppress=True to function set_printoptions works only for numbers that fit in the default 8 character space allotted to it, like this:

import numpy as np
np.set_printoptions(suppress=True) #prevent numpy exponential 
                                   #notation on print, default False

#            tiny     med  large
a = np.array([1.01e-5, 22, 1.2345678e7])  #notice how index 2 is 8 
                                          #digits wide

print(a)    #prints [ 0.0000101   22.     12345678. ]

However if you pass in a number greater than 8 characters wide, exponential notation is imposed again, like this:

np.set_printoptions(suppress=True)

a = np.array([1.01e-5, 22, 1.2345678e10])    #notice how index 2 is 10
                                             #digits wide, too wide!

#exponential notation where we've told it not to!
print(a)    #prints [1.01000000e-005   2.20000000e+001   1.23456780e+10]

numpy has a choice between chopping your number in half thus misrepresenting it, or forcing exponential notation, it chooses the latter.

Here comes set_printoptions(formatter=...) to the rescue to specify options for printing and rounding. Tell set_printoptions to just print bare a bare float:

np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:f}'.format})

a = np.array([1.01e-5, 22, 1.2345678e30])  #notice how index 2 is 30
                                           #digits wide.  

#Ok good, no exponential notation in the large numbers:
print(a)  #prints [0.000010 22.000000 1234567799999999979944197226496.000000] 

We've force-suppressed the exponential notation, but it is not rounded or justified, so specify extra formatting options:

np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:0.2f}'.format})  #float, 2 units 
                                               #precision right, 0 on left

a = np.array([1.01e-5, 22, 1.2345678e30])   #notice how index 2 is 30
                                            #digits wide

print(a)  #prints [0.00 22.00 1234567799999999979944197226496.00]

The drawback for force-suppressing all exponential notion in ndarrays is that if your ndarray gets a huge float value near infinity in it, and you print it, you're going to get blasted in the face with a page full of numbers.

Full example Demo 1:

from pprint import pprint
import numpy as np
#chaotic python list of lists with very different numeric magnitudes
my_list = [[3.74, 5162, 13683628846.64, 12783387559.86, 1.81],
           [9.55, 116, 189688622.37, 260332262.0, 1.97],
           [2.2, 768, 6004865.13, 5759960.98, 1.21],
           [3.74, 4062, 3263822121.39, 3066869087.9, 1.93],
           [1.91, 474, 44555062.72, 44555062.72, 0.41],
           [5.8, 5006, 8254968918.1, 7446788272.74, 3.25],
           [4.5, 7887, 30078971595.46, 27814989471.31, 2.18],
           [7.03, 116, 66252511.46, 81109291.0, 1.56],
           [6.52, 116, 47674230.76, 57686991.0, 1.43],
           [1.85, 623, 3002631.96, 2899484.08, 0.64],
           [13.76, 1227, 1737874137.5, 1446511574.32, 4.32],
           [13.76, 1227, 1737874137.5, 1446511574.32, 4.32]]

#convert python list of lists to numpy ndarray called my_array
my_array = np.array(my_list)

#This is a little recursive helper function converts all nested 
#ndarrays to python list of lists so that pretty printer knows what to do.
def arrayToList(arr):
    if type(arr) == type(np.array):
        #If the passed type is an ndarray then convert it to a list and
        #recursively convert all nested types
        return arrayToList(arr.tolist())
    else:
        #if item isn't an ndarray leave it as is.
        return arr

#suppress exponential notation, define an appropriate float formatter
#specify stdout line width and let pretty print do the work
np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:16.3f}'.format}, linewidth=130)
pprint(arrayToList(my_array))

Prints:

array([[           3.740,         5162.000,  13683628846.640,  12783387559.860,            1.810],
       [           9.550,          116.000,    189688622.370,    260332262.000,            1.970],
       [           2.200,          768.000,      6004865.130,      5759960.980,            1.210],
       [           3.740,         4062.000,   3263822121.390,   3066869087.900,            1.930],
       [           1.910,          474.000,     44555062.720,     44555062.720,            0.410],
       [           5.800,         5006.000,   8254968918.100,   7446788272.740,            3.250],
       [           4.500,         7887.000,  30078971595.460,  27814989471.310,            2.180],
       [           7.030,          116.000,     66252511.460,     81109291.000,            1.560],
       [           6.520,          116.000,     47674230.760,     57686991.000,            1.430],
       [           1.850,          623.000,      3002631.960,      2899484.080,            0.640],
       [          13.760,         1227.000,   1737874137.500,   1446511574.320,            4.320],
       [          13.760,         1227.000,   1737874137.500,   1446511574.320,            4.320]])

Full example Demo 2:

import numpy as np  
#chaotic python list of lists with very different numeric magnitudes 

#            very tiny      medium size            large sized
#            numbers        numbers                numbers

my_list = [[0.000000000074, 5162, 13683628846.64, 1.01e10, 1.81], 
           [1.000000000055,  116, 189688622.37, 260332262.0, 1.97], 
           [0.010000000022,  768, 6004865.13,   -99e13, 1.21], 
           [1.000000000074, 4062, 3263822121.39, 3066869087.9, 1.93], 
           [2.91,            474, 44555062.72, 44555062.72, 0.41], 
           [5,              5006, 8254968918.1, 7446788272.74, 3.25], 
           [0.01,           7887, 30078971595.46, 27814989471.31, 2.18], 
           [7.03,            116, 66252511.46, 81109291.0, 1.56], 
           [6.52,            116, 47674230.76, 57686991.0, 1.43], 
           [1.85,            623, 3002631.96, 2899484.08, 0.64], 
           [13.76,          1227, 1737874137.5, 1446511574.32, 4.32], 
           [13.76,          1337, 1737874137.5, 1446511574.32, 4.32]] 
import sys 
#convert python list of lists to numpy ndarray called my_array 
my_array = np.array(my_list) 
#following two lines do the same thing, showing that np.savetxt can 
#correctly handle python lists of lists and numpy 2D ndarrays. 
np.savetxt(sys.stdout, my_list, '%19.2f') 
np.savetxt(sys.stdout, my_array, '%19.2f') 

Prints:

 0.00             5162.00      13683628846.64      10100000000.00              1.81
 1.00              116.00        189688622.37        260332262.00              1.97
 0.01              768.00          6004865.13 -990000000000000.00              1.21
 1.00             4062.00       3263822121.39       3066869087.90              1.93
 2.91              474.00         44555062.72         44555062.72              0.41
 5.00             5006.00       8254968918.10       7446788272.74              3.25
 0.01             7887.00      30078971595.46      27814989471.31              2.18
 7.03              116.00         66252511.46         81109291.00              1.56
 6.52              116.00         47674230.76         57686991.00              1.43
 1.85              623.00          3002631.96          2899484.08              0.64
13.76             1227.00       1737874137.50       1446511574.32              4.32
13.76             1337.00       1737874137.50       1446511574.32              4.32
 0.00             5162.00      13683628846.64      10100000000.00              1.81
 1.00              116.00        189688622.37        260332262.00              1.97
 0.01              768.00          6004865.13 -990000000000000.00              1.21
 1.00             4062.00       3263822121.39       3066869087.90              1.93
 2.91              474.00         44555062.72         44555062.72              0.41
 5.00             5006.00       8254968918.10       7446788272.74              3.25
 0.01             7887.00      30078971595.46      27814989471.31              2.18
 7.03              116.00         66252511.46         81109291.00              1.56
 6.52              116.00         47674230.76         57686991.00              1.43
 1.85              623.00          3002631.96          2899484.08              0.64
13.76             1227.00       1737874137.50       1446511574.32              4.32
13.76             1337.00       1737874137.50       1446511574.32              4.32

Notice that rounding is consistent at 2 units precision, and exponential notation is suppressed in both the very large e+x and very small e-x ranges.

Failed to find target with hash string 'android-25'

You can open the SDK standalone by going to installation directory, just right click on the SDK Manager.exe and click on run as Administrator. i hope it will help.

I would like to see a hash_map example in C++

hash_map is a non-standard extension. unordered_map is part of std::tr1, and will be moved into the std namespace for C++0x. http://en.wikipedia.org/wiki/Unordered_map_%28C%2B%2B%29

How to set ANDROID_HOME path in ubuntu?

In my case it works with a little change. Simply by putting :$PATH at the end.

# andorid paths
export ANDROID_HOME=$HOME/Android/Sdk
export PATH="$ANDROID_HOME/tools:$PATH"
export PATH="$ANDROID_HOME/platform-tools:$PATH"
export PATH="$ANDROID_HOME/emulator:$PATH"

java.lang.IllegalArgumentException: No converter found for return value of type

I saw the same error when the scope of the jackson-databind dependency had been set to test:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.9</version>
    <scope>test</scope>
</dependency>

Removing the <scope> line fixed the issue.

How do I format a string using a dictionary in python-3.x?

To unpack a dictionary into keyword arguments, use **. Also,, new-style formatting supports referring to attributes of objects and items of mappings:

'{0[latitude]} {0[longitude]}'.format(geopoint)
'The title is {0.title}s'.format(a) # the a from your first example

PHP: Read Specific Line From File

$myFile = "4-21-11.txt";
$fh = fopen($myFile, 'r');
while(!feof($fh))
{
    $data[] = fgets($fh);  
    //Do whatever you want with the data in here
    //This feeds the file into an array line by line
}
fclose($fh);

How can I find my php.ini on wordpress?

Create a file yourself php.ini anywhere in your root or wp-admin folder and add the necessary code to the file it should work

Recursively counting files in a Linux directory

You can use the command ncdu. It will recursively count how many files a Linux directory contains. Here is an example of output:

enter image description here

It has a progress bar, which is convenient if you have many files:

enter image description here

To install it on Ubuntu:

sudo apt-get install -y ncdu

Benchmark: I used https://archive.org/details/cv_corpus_v1.tar (380390 files, 11 GB) as the folder where one has to count the number of files.

  • find . -type f | wc -l: around 1m20s to complete
  • ncdu: around 1m20s to complete

Responsive background image in div full width

Here is one way of getting the design that you want.

Start with the following HTML:

<div class="container">
    <div class="row-fluid">
        <div class="span12">
            <div class="nav">nav area</div>
            <div class="bg-image">
                <img src="http://unplugged.ee/wp-content/uploads/2013/03/frank2.jpg">
                 <h1>This is centered text.</h1>
            </div>
            <div class="main">main area</div>
        </div>
    </div>
</div>

Note that the background image is now part of the regular flow of the document.

Apply the following CSS:

.bg-image {
    position: relative;
}
.bg-image img {
    display: block;
    width: 100%;
    max-width: 1200px; /* corresponds to max height of 450px */
    margin: 0 auto;
}
.bg-image h1 {
    position: absolute;
    text-align: center;
    bottom: 0;
    left: 0;
    right: 0;
    color: white;
}
.nav, .main {
    background-color: #f6f6f6;
    text-align: center;
}

How This Works

The image is set an regular flow content with a width of 100%, so it will adjust itself responsively to the width of the parent container. However, you want the height to be no more than 450px, which corresponds to the image width of 1200px, so set the maximum width of the image to 1200px. You can keep the image centered by using display: block and margin: 0 auto.

The text is painted over the image by using absolute positioning. In the simplest case, I stretch the h1 element to be the full width of the parent and use text-align: center to center the text. Use the top or bottom offsets to place the text where it is needed.

If your banner images are going to vary in aspect ratio, you will need to adjust the maximum width value for .bg-image img dynamically using jQuery/Javascript, but otherwise, this approach has a lot to offer.

See demo at: http://jsfiddle.net/audetwebdesign/EGgaN/

How to get a responsive button in bootstrap 3

For anyone who may be interested, another approach is using @media queries to scale the buttons on different viewport widths..

Demo: http://bootply.com/93706

What is the size of column of int(11) in mysql in bytes?

According to here, int(11) will take 4 bytes of space that is 32 bits of space with 2^(31) = 2147483648 max value and -2147483648min value. One bit is for sign.

Copy a table from one database to another in Postgres

Use pg_dump to dump table data, and then restore it with psql.

How do I clear a search box with an 'x' in bootstrap 3?

I tried to avoid too much custom CSS and after reading some other examples I merged the ideas there and got this solution:

<div class="form-group has-feedback has-clear">
    <input type="text" class="form-control" ng-model="ctrl.searchService.searchTerm" ng-change="ctrl.search()" placeholder="Suche"/>
    <a class="glyphicon glyphicon-remove-sign form-control-feedback form-control-clear" ng-click="ctrl.clearSearch()" style="pointer-events: auto; text-decoration: none;cursor: pointer;"></a>
</div>

As I don't use bootstrap's JavaScript, just the CSS together with Angular, I don't need the classes has-clear and form-control-clear, and I implemented the clear function in my AngularJS controller. With bootstrap's JavaScript this might be possible without own JavaScript.

Jenkins fails when running "service start jenkins"

Adding on to what has been already answered by Guna Sekaran. Jenkins need the user jenkins to be present in order to run the jenkins as a service.

To add user fire 'useradd jenkins' as root and fire 'passwd jenkins' as root before starting Jenkins as a service.

Make a dictionary in Python from input values

Take input from user:

input = int(input("enter a n value:"))

dict = {}

for i in range(input):

    name = input() 

    values = int(input()) 

    dict[name] = values
print(dict)

Is there a git-merge --dry-run option?

As a summary of existed answers, there are two way to check if there would be merge conflicts

git format-patch $(git merge-base branch1 branch2)..branch2 --stdout | git apply --3way --check -

Note, your current branch should be branch1 when you run above command

Another way:

git merge --no-commit branch2
# check the return code here
git merge --abort

How do I send a POST request with PHP?

The better way of sending GET or POST requests with PHP is as below:

<?php
    $r = new HttpRequest('http://example.com/form.php', HttpRequest::METH_POST);
    $r->setOptions(array('cookies' => array('lang' => 'de')));
    $r->addPostFields(array('user' => 'mike', 'pass' => 's3c|r3t'));

    try {
        echo $r->send()->getBody();
    } catch (HttpException $ex) {
        echo $ex;
    }
?>

The code is taken from official documentation here http://docs.php.net/manual/da/httprequest.send.php

Python date string to date object

Use time module to convert data.

Code snippet:

import time 
tring='20150103040500'
var = int(time.mktime(time.strptime(tring, '%Y%m%d%H%M%S')))
print var

How to create helper file full of functions in react native?

If you want to use class, you can do this.

Helper.js

  function x(){}

  function y(){}

  export default class Helper{

    static x(){ x(); }

    static y(){ y(); }

  }

App.js

import Helper from 'helper.js';

/****/

Helper.x

relative path to CSS file

Background

Absolute: The browser will always interpret / as the root of the hostname. For example, if my site was http://google.com/ and I specified /css/images.css then it would search for that at http://google.com/css/images.css. If your project root was actually at /myproject/ it would not find the css file. Therefore, you need to determine where your project folder root is relative to the hostname, and specify that in your href notation.

Relative: If you want to reference something you know is in the same path on the url - that is, if it is in the same folder, for example http://mysite.com/myUrlPath/index.html and http://mysite.com/myUrlPath/css/style.css, and you know that it will always be this way, you can go against convention and specify a relative path by not putting a leading / in front of your path, for example, css/style.css.

Filesystem Notations: Additionally, you can use standard filesystem notations like ... If you do http://google.com/images/../images/../images/myImage.png it would be the same as http://google.com/images/myImage.png. If you want to reference something that is one directory up from your file, use ../myFile.css.


Your Specific Case

In your case, you have two options:

  • <link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>
  • <link rel="stylesheet" type="text/css" href="css/styles.css"/>

The first will be more concrete and compatible if you move things around, however if you are planning to keep the file in the same location, and you are planning to remove the /ServletApp/ part of the URL, then the second solution is better.

PHP: How do I display the contents of a textfile on my page?

I had to use nl2br to display the carriage returns correctly and it worked for me:

<?php
echo nl2br(file_get_contents( "filename.php" )); // get the contents, and echo it out.
?>

How to use a wildcard in the classpath to add multiple jars?

If you mean that you have an environment variable named CLASSPATH, I'd say that's your mistake. I don't have such a thing on any machine with which I develop Java. CLASSPATH is so tied to a particular project that it's impossible to have a single, correct CLASSPATH that works for all.

I set CLASSPATH for each project using either an IDE or Ant. I do a lot of web development, so each WAR and EAR uses their own CLASSPATH.

It's ignored by IDEs and app servers. Why do you have it? I'd recommend deleting it.

How do I remove a key from a JavaScript object?

The delete operator allows you to remove a property from an object.

The following examples all do the same thing.

// Example 1
var key = "Cow";
delete thisIsObject[key]; 

// Example 2
delete thisIsObject["Cow"];

// Example 3
delete thisIsObject.Cow;

If you're interested, read Understanding Delete for an in-depth explanation.

How can I get the application's path in a .NET console application?

I have used

System.AppDomain.CurrentDomain.BaseDirectory

when I want to find a path relative to an applications folder. This works for both ASP.Net and winform applications. It also does not require any reference to System.Web assemblies.

CSS – why doesn’t percentage height work?

Without content, the height has no value to calculate the percentage of. The width, however, will take the percentage from the DOM, if no parent is specified. (Using your example) Placing the second div inside the first div, would have rendered a result...example below...

<div id="working">
  <div id="not-working"></div>
</div>

The second div would be 30% of the first div's height.

jQuery won't parse my JSON from AJAX query

{ title: "One", key: "1" }

Is not what you think. As an expression, it's an Object literal, but as a statement, it's:

{                // new block
    title:       // define a label called 'title' for goto statements
        "One",   // statement: the start of an expression which will be ignored
        key:     // ...er, what? you can't have a goto label in the middle of an expression
                 // ERROR

Unfortunately eval() does not give you a way to specify whether you are giving it a statement or an expression, and it tends to guess wrong.

The usual solution is indeed to wrap anything in parentheses before sending it to the eval() function. You say you've tried that on the server... clearly somehow that isn't getting through. It should be waterproof to say on the client end, whatever is receiving the XMLHttpRequest response:

eval('('+responseText+')');

instead of:

eval(responseText);

as long as the response is really an expression not a statement. (eg. it doesn't have multiple, semicolon-or-newline-separated clauses.)

NameError: name 'python' is not defined

It looks like you are trying to start the Python interpreter by running the command python.

However the interpreter is already started. It is interpreting python as a name of a variable, and that name is not defined.

Try this instead and you should hopefully see that your Python installation is working as expected:

print("Hello world!")

How to disable right-click context-menu in JavaScript

I have used this:

document.onkeydown = keyboardDown;
document.onkeyup = keyboardUp;
document.oncontextmenu = function(e){
 var evt = new Object({keyCode:93});
 stopEvent(e);
 keyboardUp(evt);
}
function stopEvent(event){
 if(event.preventDefault != undefined)
  event.preventDefault();
 if(event.stopPropagation != undefined)
  event.stopPropagation();
}
function keyboardDown(e){
 ...
}
function keyboardUp(e){
 ...
}

Then I catch e.keyCode property in those two last functions - if e.keyCode == 93, I know that the user either released the right mouse button or pressed/released the Context Menu key.

Hope it helps.

SQL Combine Two Columns in Select Statement

In MySQL you can use:

SELECT CONCAT(Address1, " ", Address2)
WHERE SOUNDEX(CONCAT(Address1, " ", Address2)) = SOUNDEX("Center St 3B")

The SOUNDEX function works similarly in most database systems, I can't think of the syntax for MSSQL at the minute, but it wouldn't be too far away from the above.

multi line comment vb.net in Visual studio 2010

The only way I could do it in VS 2010 IDE was to highlight the block of code and hit ctrl-E and then C

How to pass integer from one Activity to another?

In Activity A

private void startSwitcher() {
    int yourInt = 200;
    Intent myIntent = new Intent(A.this, B.class);
    intent.putExtra("yourIntName", yourInt);
    startActivity(myIntent);
}

in Activity B

int score = getIntent().getIntExtra("yourIntName", 0);

How to add multiple files to Git at the same time

Use the git add command, followed by a list of space-separated filenames. Include paths if in other directories, e.g. directory-name/file-name.

git add file-1 file-2 file-3

What is a reasonable length limit on person "Name" fields?

The average first name is about 6 letters. That leaves 43 for a last name. :) Seems like you could probably shorten it if you like.

The main question is how many rows do you think you will have? I don't think varchar(50) is going to kill you until you get several million rows.

Change background color of R plot

Old question but I have a much better way of doing this. Rather than using rect() use polygon. This allows you to keep everything in plot without using points. Also you don't have to mess with par at all. If you want to keep things automated make the coordinates of polygon a function of your data.

plot.new()
polygon(c(-min(df[,1])^2,-min(df[,1])^2,max(df[,1])^2,max(df[,1])^2),c(-min(df[,2])^2,max(df[,2])^2,max(df[,2])^2,-min(df[,2])^2), col="grey")
par(new=T)
plot(df)

getActivity() returns null in Fragment function

commit schedules the transaction, i.e. it doesn't happen straightaway but is scheduled as work on the main thread the next time the main thread is ready.

I'd suggest adding an

onAttach(Activity activity)

method to your Fragment and putting a break point on it and seeing when it is called relative to your call to asd(). You'll see that it is called after the method where you make the call to asd() exits. The onAttach call is where the Fragment is attached to its activity and from this point getActivity() will return non-null (nb there is also an onDetach() call).

Open File in Another Directory (Python)

import os
import os.path
import shutil

You find your current directory:

d = os.getcwd() #Gets the current working directory

Then you change one directory up:

os.chdir("..") #Go up one directory from working directory

Then you can get a tupple/list of all the directories, for one directory up:

o = [os.path.join(d,o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))] # Gets all directories in the folder as a tuple

Then you can search the tuple for the directory you want and open the file in that directory:

for item in o:
    if os.path.exists(item + '\\testfile.txt'):
    file = item + '\\testfile.txt'

Then you can do stuf with the full file path 'file'

How to install the JDK on Ubuntu Linux

Simply run:

sudo apt-get install default-jdk

Include PHP inside JavaScript (.js) files

Because the Javascript executes in the browser, on the client side, and PHP on the server side, what you need is AJAX - in essence, your script makes an HTTP request to a PHP script, passing any required parameters. The script calls your function, and outputs the result, which ultimately gets picked up by the Ajax call. Generally, you don't do this synchronously (waiting for the result) - the 'A' in AJAX stands for asynchronous!

Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?

Just my two cents to this very old question. I would highly recommend taking a look at ElasticSearch.

Elasticsearch is a search server based on Lucene. It provides a distributed, multitenant-capable full-text search engine with a RESTful web interface and schema-free JSON documents. Elasticsearch is developed in Java and is released as open source under the terms of the Apache License.

The advantages over other FTS (full text search) Engines are:

  • RESTful interface
  • Better scalability
  • Large community
  • Built by Lucene developers
  • Extensive documentation
  • There are many open source libraries available (including Django)

We are using this search engine at our project and very happy with it.

How to do a regular expression replace in MySQL?

My brute force method to get this to work was just:

  1. Dump the table - mysqldump -u user -p database table > dump.sql
  2. Find and replace a couple patterns - find /path/to/dump.sql -type f -exec sed -i 's/old_string/new_string/g' {} \;, There are obviously other perl regeular expressions you could perform on the file as well.
  3. Import the table - mysqlimport -u user -p database table < dump.sql

If you want to make sure the string isn't elsewhere in your dataset, run a few regular expressions to make sure they all occur in a similar environment. It's also not that tough to create a backup before you run a replace, in case you accidentally destroy something that loses depth of information.

How to add calendar events in Android?

i used the code below, it solves my problem to add event in default device calendar in ICS and also on version less that ICS

    if (Build.VERSION.SDK_INT >= 14) {
        Intent intent = new Intent(Intent.ACTION_INSERT)
        .setData(Events.CONTENT_URI)
        .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
        .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
        .putExtra(Events.TITLE, "Yoga")
        .putExtra(Events.DESCRIPTION, "Group class")
        .putExtra(Events.EVENT_LOCATION, "The gym")
        .putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY)
        .putExtra(Intent.EXTRA_EMAIL, "[email protected],[email protected]");
         startActivity(intent);
}

    else {
        Calendar cal = Calendar.getInstance();              
        Intent intent = new Intent(Intent.ACTION_EDIT);
        intent.setType("vnd.android.cursor.item/event");
        intent.putExtra("beginTime", cal.getTimeInMillis());
        intent.putExtra("allDay", true);
        intent.putExtra("rrule", "FREQ=YEARLY");
        intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
        intent.putExtra("title", "A Test Event from android app");
        startActivity(intent);
        }

Hope it would help.....

Enabling error display in PHP via htaccess only

This works for me (reference):

# PHP error handling for production servers
# Disable display of startup errors
php_flag display_startup_errors off

# Disable display of all other errors
php_flag display_errors off

# Disable HTML markup of errors
php_flag html_errors off

# Enable logging of errors
php_flag log_errors on

# Disable ignoring of repeat errors
php_flag ignore_repeated_errors off

# Disable ignoring of unique source errors
php_flag ignore_repeated_source off

# Enable logging of PHP memory leaks
php_flag report_memleaks on

# Preserve most recent error via php_errormsg
php_flag track_errors on

# Disable formatting of error reference links
php_value docref_root 0

# Disable formatting of error reference links
php_value docref_ext 0

# Specify path to PHP error log
php_value error_log /home/path/public_html/domain/PHP_errors.log

# Specify recording of all PHP errors
# [see footnote 3] # php_value error_reporting 999999999
php_value error_reporting -1

# Disable max error string length
php_value log_errors_max_len 0

# Protect error log by preventing public access
<Files PHP_errors.log>
 Order allow,deny
 Deny from all
 Satisfy All
</Files>

How to add number of days in postgresql datetime

This will give you the deadline :

select id,  
       title,
       created_at + interval '1' day * claim_window as deadline
from projects

Alternatively the function make_interval can be used:

select id,  
       title,
       created_at + make_interval(days => claim_window) as deadline
from projects

To get all projects where the deadline is over, use:

select *
from (
  select id, 
         created_at + interval '1' day * claim_window as deadline
  from projects
) t
where localtimestamp at time zone 'UTC' > deadline

is there a post render callback for Angular JS directive?

I got this working with the following directive:

app.directive('datatableSetup', function () {
    return { link: function (scope, elm, attrs) { elm.dataTable(); } }
});

And in the HTML:

<table class="table table-hover dataTable dataTable-columnfilter " datatable-setup="">

trouble shooting if the above doesnt work for you.

1) note that 'datatableSetup' is the equivalent of 'datatable-setup'. Angular changes the format into camel case.

2) make sure that app is defined before the directive. e.g. simple app definition and directive.

var app = angular.module('app', []);
app.directive('datatableSetup', function () {
    return { link: function (scope, elm, attrs) { elm.dataTable(); } }
});

What does $_ mean in PowerShell?

$_ is a variable created by the system usually inside block expressions that are referenced by cmdlets that are used with pipe such as Where-Object and ForEach-Object.

But it can be used also in other types of expressions, for example with Select-Object combined with expression properties. Get-ChildItem | Select-Object @{Name="Name";Expression={$_.Name}}. In this case the $_ represents the item being piped but multiple expressions can exist.

It can also be referenced by custom parameter validation, where a script block is used to validate a value. In this case the $_ represents the parameter value as received from the invocation.

The closest analogy to c# and java is the lamda expression. If you break down powershell to basics then everything is a script block including a script file a, functions and cmdlets. You can define your own parameters but in some occasions one is created by the system for you that represents the input item to process/evaluate. In those situations the automatic variable is $_.

AngularJS - convert dates in controller

i suggest in Javascript:

var item=1387843200000;
var date1=new Date(item);

and then date1 is a Date.

best way to get the key of a key/value javascript object

You would iterate inside the object with a for loop:

for(var i in foo){
  alert(i); // alerts key
  alert(foo[i]); //alerts key's value
}

Or

Object.keys(foo)
  .forEach(function eachKey(key) { 
    alert(key); // alerts key 
    alert(foo[key]); // alerts value
  });

SQL - HAVING vs. WHERE

  1. WHERE clause can be used with SELECT, INSERT, and UPDATE statements, whereas HAVING can be used only with SELECT statement.

  2. WHERE filters rows before aggregation (GROUP BY), whereas HAVING filter groups after aggregations are performed.

  3. Aggregate function cannot be used in WHERE clause unless it is in a subquery contained in HAVING clause, whereas aggregate functions can be used in HAVING clause.

Source

How to remove item from array by value?

The simplest solution is:

array - array for remove some element valueForRemove; valueForRemove - element for remove;

array.filter(arrayItem => !array.includes(valueForRemove));

More simple:

array.filter(arrayItem => arrayItem !== valueForRemove);

No pretty, but works:

array.filter(arrayItem => array.indexOf(arrayItem) != array.indexOf(valueForRemove))

No pretty, but works:

while(array.indexOf(valueForRemove) !== -1) {
  array.splice(array.indexOf(valueForRemove), 1)
}

P.S. The filter() method creates a new array with all elements that pass the test implemented by the provided function. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

How Do I Convert an Integer to a String in Excel VBA?

enter image description here

    Sub NumToText(ByRef sRng As String, Optional ByVal WS As Worksheet)
    '---Converting visible range form Numbers to Text
        Dim Temp As Double
        Dim vRng As Range
        Dim Cel As Object

        If WS Is Nothing Then Set WS = ActiveSheet
            Set vRng = WS.Range(sRng).SpecialCells(xlCellTypeVisible)
            For Each Cel In vRng
                If Not IsEmpty(Cel.Value) And IsNumeric(Cel.Value) Then
                    Temp = Cel.Value
                    Cel.ClearContents
                    Cel.NumberFormat = "@"
                    Cel.Value = CStr(Temp)
                End If
            Next Cel
    End Sub


    Sub Macro1()
        Call NumToText("A2:A100", ActiveSheet)
    End Sub

Reffer: MrExcel.com – Convert numbers to text with VBA

Git: "Corrupt loose object"

We just had the case here. It happened that the problem was the ownership of the corrupt file was root instead of our normal user. This was caused by a commit done on the server after someone has done a "sudo su --".

First, identify your corrupt file with:

$> git fsck --full

You should receive a answer like this one:

fatal: loose object 11b25a9d10b4144711bf616590e171a76a35c1f9 (stored in .git/objects/11/b25a9d10b4144711bf616590e171a76a35c1f9) is corrupt

Go in the folder where the corrupt file is and do a:

$> ls -la

Check the ownership of the corrupt file. If that's different, just go back to the root of your repo and do a:

$> sudo chown -R YOURCORRECTUSER:www-data .git/

Hope it helps!

Django Multiple Choice Field / Checkbox Select Multiple

The profile choices need to be setup as a ManyToManyField for this to work correctly.

So... your model should be like this:

class Choices(models.Model):
  description = models.CharField(max_length=300)

class Profile(models.Model):
  user = models.ForeignKey(User, blank=True, unique=True, verbose_name='user')
  choices = models.ManyToManyField(Choices)

Then, sync the database and load up Choices with the various options you want available.

Now, the ModelForm will build itself...

class ProfileForm(forms.ModelForm):
  Meta:
    model = Profile
    exclude = ['user']

And finally, the view:

if request.method=='POST':
  form = ProfileForm(request.POST)
  if form.is_valid():
    profile = form.save(commit=False)
    profile.user = request.user
    profile.save()
else:
  form = ProfileForm()

return render_to_response(template_name, {"profile_form": form}, context_instance=RequestContext(request))

It should be mentioned that you could setup a profile in a couple different ways, including inheritance. That said, this should work for you as well.

Good luck.

Using Mockito's generic "any()" method

You can use Mockito.isA() for that:

import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verify;

verify(bar).doStuff(isA(Foo[].class));

http://site.mockito.org/mockito/docs/current/org/mockito/Matchers.html#isA(java.lang.Class)

Sending GET request with Authentication headers using restTemplate

You're not missing anything. RestTemplate#exchange(..) is the appropriate method to use to set request headers.

Here's an example (with POST, but just change that to GET and use the entity you want).

Here's another example.

Note that with a GET, your request entity doesn't have to contain anything (unless your API expects it, but that would go against the HTTP spec). It can be an empty String.

How do you make websites with Java?

Also be advised, that while Java is in general very beginner friendly, getting into JavaEE, Servlets, Facelets, Eclipse integration, JSP and getting everything in Tomcat up and running is not. Certainly not the easiest way to build a website and probably way overkill for most things.

On top of that you may need to host your website yourself, because most webspace providers don't provide Servlet Containers. If you just want to check it out for fun, I would try Ruby or Python, which are much more cooler things to fiddle around with. But anyway, to provide at least something relevant to the question, here's a nice Servlet tutorial: link

Encrypt & Decrypt using PyCrypto AES 256

from Crypto import Random
from Crypto.Cipher import AES
import base64

BLOCK_SIZE=16
def trans(key):
     return md5.new(key).digest()

def encrypt(message, passphrase):
    passphrase = trans(passphrase)
    IV = Random.new().read(BLOCK_SIZE)
    aes = AES.new(passphrase, AES.MODE_CFB, IV)
    return base64.b64encode(IV + aes.encrypt(message))

def decrypt(encrypted, passphrase):
    passphrase = trans(passphrase)
    encrypted = base64.b64decode(encrypted)
    IV = encrypted[:BLOCK_SIZE]
    aes = AES.new(passphrase, AES.MODE_CFB, IV)
    return aes.decrypt(encrypted[BLOCK_SIZE:])

Removing leading zeroes from a field in a SQL statement

Here is the SQL scalar value function that removes leading zeros from string:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Vikas Patel
-- Create date: 01/31/2019
-- Description: Remove leading zeros from string
-- =============================================
CREATE FUNCTION dbo.funRemoveLeadingZeros 
(
    -- Add the parameters for the function here
    @Input varchar(max)
)
RETURNS varchar(max)
AS
BEGIN
    -- Declare the return variable here
    DECLARE @Result varchar(max)

    -- Add the T-SQL statements to compute the return value here
    SET @Result = @Input

    WHILE LEFT(@Result, 1) = '0'
    BEGIN
        SET @Result = SUBSTRING(@Result, 2, LEN(@Result) - 1)
    END

    -- Return the result of the function
    RETURN @Result

END
GO

QtCreator: No valid kits found

For QT 5.* if you face error at Kits, like No Valid Kits Found, go to Options->Build&Run-> (Kits tab) then you see a Manual category which should list Desktop as the default.

Just go to your OS Terminal and write sudo apt-get install qt5-default, go back to QT Creator and Start your New Project, and there you see the kit option Desktop included in the list.

Regular expressions in C: examples?

This is an example of using REG_EXTENDED. This regular expression

"^(-)?([0-9]+)((,|.)([0-9]+))?\n$"

Allows you to catch decimal numbers in Spanish system and international. :)

#include <regex.h>
#include <stdlib.h>
#include <stdio.h>
regex_t regex;
int reti;
char msgbuf[100];

int main(int argc, char const *argv[])
{
    while(1){
        fgets( msgbuf, 100, stdin );
        reti = regcomp(&regex, "^(-)?([0-9]+)((,|.)([0-9]+))?\n$", REG_EXTENDED);
        if (reti) {
            fprintf(stderr, "Could not compile regex\n");
            exit(1);
        }

        /* Execute regular expression */
        printf("%s\n", msgbuf);
        reti = regexec(&regex, msgbuf, 0, NULL, 0);
        if (!reti) {
            puts("Match");
        }
        else if (reti == REG_NOMATCH) {
            puts("No match");
        }
        else {
            regerror(reti, &regex, msgbuf, sizeof(msgbuf));
            fprintf(stderr, "Regex match failed: %s\n", msgbuf);
            exit(1);
        }

        /* Free memory allocated to the pattern buffer by regcomp() */
        regfree(&regex);
    }

}

How to configure socket connect timeout

This is like FlappySock's answer, but I added a callback to it because I didn't like the layout and how the Boolean was getting returned. In the comments of that answer from Nick Miller:

In my experience, if the end point can be reached, but there is no server on the endpoint able to receive the connection, then AsyncWaitHandle.WaitOne will be signaled, but the socket will remain unconnected

So to me, it seems relying on what is returned can be dangerous - I prefer to use socket.Connected. I set a nullable Boolean and update it in the callback function. I also found it doesn't always finish reporting the result before returning to the main function - I handle for that, too, and make it wait for the result using the timeout:

private static bool? areWeConnected = null;

private static bool checkSocket(string svrAddress, int port)
{
    IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(svrAddress), port);
    Socket socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

    int timeout = 5000; // int.Parse(ConfigurationManager.AppSettings["socketTimeout"].ToString());
    int ctr = 0;
    IAsyncResult ar = socket.BeginConnect(endPoint, Connect_Callback, socket);
    ar.AsyncWaitHandle.WaitOne( timeout, true );

    // Sometimes it returns here as null before it's done checking the connection
    // No idea why, since .WaitOne() should block that, but it does happen
    while (areWeConnected == null && ctr < timeout)
    {
        Thread.Sleep(100);
        ctr += 100;
    } // Given 100ms between checks, it allows 50 checks 
      // for a 5 second timeout before we give up and return false, below

    if (areWeConnected == true)
    {
        return true;
    }
    else
    {
        return false;
    }
}

private static void Connect_Callback(IAsyncResult ar)
{
    areWeConnected = null;
    try
    {
        Socket socket = (Socket)ar.AsyncState;
        areWeConnected = socket.Connected;
        socket.EndConnect(ar);
    }
    catch (Exception ex)
    {
      areWeConnected = false;
      // log exception 
    }
}

Related: How to check if I'm connected?

MySQL - DATE_ADD month interval

Well, for me this is the expected result; adding six months to Jan. 1st July.

mysql> SELECT DATE_ADD( '2011-01-01', INTERVAL 6 month );
+--------------------------------------------+
| DATE_ADD( '2011-01-01', INTERVAL 6 month ) |
+--------------------------------------------+
| 2011-07-01                                 | 
+--------------------------------------------+

Simple insecure two-way data "obfuscation"?

I combined what I found the best from several answers and comments.

  • Random initialization vector prepended to crypto text (@jbtule)
  • Use TransformFinalBlock() instead of MemoryStream (@RenniePet)
  • No pre-filled keys to avoid anyone copy & pasting a disaster
  • Proper dispose and using patterns

Code:

/// <summary>
/// Simple encryption/decryption using a random initialization vector
/// and prepending it to the crypto text.
/// </summary>
/// <remarks>Based on multiple answers in http://stackoverflow.com/questions/165808/simple-two-way-encryption-for-c-sharp </remarks>
public class SimpleAes : IDisposable
{
    /// <summary>
    ///     Initialization vector length in bytes.
    /// </summary>
    private const int IvBytes = 16;

    /// <summary>
    ///     Must be exactly 16, 24 or 32 bytes long.
    /// </summary>
    private static readonly byte[] Key = Convert.FromBase64String("FILL ME WITH 24 (2 pad chars), 32 OR 44 (1 pad char) RANDOM CHARS"); // Base64 has a blowup of four-thirds (33%)

    private readonly UTF8Encoding _encoder;
    private readonly ICryptoTransform _encryptor;
    private readonly RijndaelManaged _rijndael;

    public SimpleAes()
    {
        _rijndael = new RijndaelManaged {Key = Key};
        _rijndael.GenerateIV();
        _encryptor = _rijndael.CreateEncryptor();
        _encoder = new UTF8Encoding();
    }

    public string Decrypt(string encrypted)
    {
        return _encoder.GetString(Decrypt(Convert.FromBase64String(encrypted)));
    }

    public void Dispose()
    {
        _rijndael.Dispose();
        _encryptor.Dispose();
    }

    public string Encrypt(string unencrypted)
    {
        return Convert.ToBase64String(Encrypt(_encoder.GetBytes(unencrypted)));
    }

    private byte[] Decrypt(byte[] buffer)
    {
        // IV is prepended to cryptotext
        byte[] iv = buffer.Take(IvBytes).ToArray();
        using (ICryptoTransform decryptor = _rijndael.CreateDecryptor(_rijndael.Key, iv))
        {
            return decryptor.TransformFinalBlock(buffer, IvBytes, buffer.Length - IvBytes);
        }
    }

    private byte[] Encrypt(byte[] buffer)
    {
        // Prepend cryptotext with IV
        byte [] inputBuffer = _encryptor.TransformFinalBlock(buffer, 0, buffer.Length); 
        return _rijndael.IV.Concat(inputBuffer).ToArray();
    }
}

Update 2015-07-18: Fixed mistake in private Encrypt() method by comments of @bpsilver and @Evereq. IV was accidentally encrypted, is now prepended in clear text as expected by Decrypt().

How to play or open *.mp3 or *.wav sound file in c++ program?

Try with simple c++ code in VC++.

#include <windows.h>
#include <iostream>
#pragma comment(lib, "winmm.lib")

int main(int argc, char* argv[])
{
std::cout<<"Sound playing... enjoy....!!!";
PlaySound("C:\\temp\\sound_test.wav", NULL, SND_FILENAME); //SND_FILENAME or SND_LOOP
return 0;
}

Add padding on view programmatically

While padding programmatically, convert to density related values by converting pixel to Dp.

Convert python datetime to timestamp in milliseconds

For Python2.7 - modifying MYGz's answer to not strip milliseconds:

from datetime import datetime

d = datetime.strptime("20.12.2016 09:38:42,76", "%d.%m.%Y %H:%M:%S,%f").strftime('%s.%f')
d_in_ms = int(float(d)*1000)
print(d_in_ms)

print(datetime.fromtimestamp(float(d)))

Output:

1482248322760
2016-12-20 09:38:42.760000

How do you use a variable in a regular expression?

"ABABAB".replace(/B/g, "A");

As always: don't use regex unless you have to. For a simple string replace, the idiom is:

'ABABAB'.split('B').join('A')

Then you don't have to worry about the quoting issues mentioned in Gracenotes's answer.

How to inject a Map using the @Value Spring Annotation?

You can inject values into a Map from the properties file using the @Value annotation like this.

The property in the properties file.

propertyname={key1:'value1',key2:'value2',....}

In your code.

@Value("#{${propertyname}}")  private Map<String,String> propertyname;

Note the hashtag as part of the annotation.

The openssl extension is required for SSL/TLS protection

This issue occurs due to openssl and extension director so uncomment below extensions in php.ini file

extension=php_openssl.dll

extension_dir = "ext"

Its works on my machine.

Best way to require all files from a directory in ruby?

Dir.glob(File.join('path', '**', '*.rb'), &method(:require))

or alternatively, if you want to scope the files to load to specific folders:

Dir.glob(File.join('path', '{folder1,folder2}', '**', '*.rb'), &method(:require))

explanation:

Dir.glob takes a block as argument.

method(:require) will return the require method.

&method(:require) will convert the method to a bloc.

How to split data into 3 sets (train, validation and test)?

In the case of supervised learning, you may want to split both X and y (where X is your input and y the ground truth output). You just have to pay attention to shuffle X and y the same way before splitting.

Here, either X and y are in the same dataframe, so we shuffle them, separate them and apply the split for each (just like in chosen answer), or X and y are in two different dataframes, so we shuffle X, reorder y the same way as the shuffled X and apply the split to each.

# 1st case: df contains X and y (where y is the "target" column of df)
df_shuffled = df.sample(frac=1)
X_shuffled = df_shuffled.drop("target", axis = 1)
y_shuffled = df_shuffled["target"]

# 2nd case: X and y are two separated dataframes
X_shuffled = X.sample(frac=1)
y_shuffled = y[X_shuffled.index]

# We do the split as in the chosen answer
X_train, X_validation, X_test = np.split(X_shuffled, [int(0.6*len(X)),int(0.8*len(X))])
y_train, y_validation, y_test = np.split(y_shuffled, [int(0.6*len(X)),int(0.8*len(X))])

vbscript output to console

You only need to force cscript instead wscript. I always use this template. The function ForceConsole() will execute your vbs into cscript, also you have nice alias to print and scan text.

 Set oWSH = CreateObject("WScript.Shell")
 vbsInterpreter = "cscript.exe"

 Call ForceConsole()

 Function printf(txt)
    WScript.StdOut.WriteLine txt
 End Function

 Function printl(txt)
    WScript.StdOut.Write txt
 End Function

 Function scanf()
    scanf = LCase(WScript.StdIn.ReadLine)
 End Function

 Function wait(n)
    WScript.Sleep Int(n * 1000)
 End Function

 Function ForceConsole()
    If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
        oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) & WScript.ScriptFullName & Chr(34)
        WScript.Quit
    End If
 End Function

 Function cls()
    For i = 1 To 50
        printf ""
    Next
 End Function

 printf " _____ _ _           _____         _    _____         _     _   "
 printf "|  _  |_| |_ ___ ___|     |_ _ _ _| |  |   __|___ ___|_|___| |_ "
 printf "|     | | '_| . |   |   --| | | | . |  |__   |  _|  _| | . |  _|"
 printf "|__|__|_|_,_|___|_|_|_____|_____|___|  |_____|___|_| |_|  _|_|  "
 printf "                                                       |_|     v1.0"
 printl " Enter your name:"
 MyVar = scanf
 cls
 printf "Your name is: " & MyVar
 wait(5)

What does the 'b' character do in front of a string literal?

The b denotes a byte string.

Bytes are the actual data. Strings are an abstraction.

If you had multi-character string object and you took a single character, it would be a string, and it might be more than 1 byte in size depending on encoding.

If took 1 byte with a byte string, you'd get a single 8-bit value from 0-255 and it might not represent a complete character if those characters due to encoding were > 1 byte.

TBH I'd use strings unless I had some specific low level reason to use bytes.

How to set the JSTL variable value in javascript?

You have to use the normal string concatenation but you have to make sure the value is a Valid XML string, you will find a good practice to write XML in this source http://oreilly.com/pub/h/2127, or if you like you can use an API in javascript to write XML as helma for example.

How to add a tooltip to an svg graphic?

Can you use simply the SVG <title> element and the default browser rendering it conveys? (Note: this is not the same as the title attribute you can use on div/img/spans in html, it needs to be a child element named title)

_x000D_
_x000D_
rect {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  fill: #69c;_x000D_
  stroke: #069;_x000D_
  stroke-width: 5px;_x000D_
  opacity: 0.5_x000D_
}
_x000D_
<p>Mouseover the rect to see the tooltip on supporting browsers.</p>_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg">_x000D_
  <rect>_x000D_
    <title>Hello, World!</title>_x000D_
  </rect>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Alternatively, if you really want to show HTML in your SVG, you can embed HTML directly:

_x000D_
_x000D_
rect {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  fill: #69c;_x000D_
  stroke: #069;_x000D_
  stroke-width: 5px;_x000D_
  opacity: 0.5_x000D_
}_x000D_
_x000D_
foreignObject {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
svg div {_x000D_
  text-align: center;_x000D_
  line-height: 150px;_x000D_
}
_x000D_
<svg xmlns="http://www.w3.org/2000/svg">_x000D_
  <rect/>_x000D_
  <foreignObject>_x000D_
    <body xmlns="http://www.w3.org/1999/xhtml">_x000D_
      <div>_x000D_
        Hello, <b>World</b>!_x000D_
      </div>_x000D_
    </body>      _x000D_
  </foreignObject>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

…but then you'd need JS to turn the display on and off. As shown above, one way to make the label appear at the right spot is to wrap the rect and HTML in the same <g> that positions them both together.

To use JS to find where an SVG element is on screen, you can use getBoundingClientRect(), e.g. http://phrogz.net/svg/html_location_in_svg_in_html.xhtml

Can I add background color only for padding?

the answers said all the possible solutions

I have another one with BOX-SHADOW

here it is JSFIDDLE

and the code

nav {
    margin:0px auto;
    width:100%;
    height:50px;
    background-color:grey;
    float:left;
    padding:10px;
    border:2px solid red;
    box-shadow: 0 0 0 10px blue inset;
}

it also support in IE9, so It's better than gradient solution, add proper prefixes for more support

IE8 dont support it, what a shame !

Pass variables to AngularJS controller, best practice?

You could use ng-init in an outer div:

<div ng-init="param='value';">
    <div ng-controller="BasketController" >
        <label>param: {{value}}</label>
    </div>
</div>  

The parameter will then be available in your controller's scope:

function BasketController($scope) {
        console.log($scope.param);
}

How to fix: "HAX is not working and emulator runs in emulation mode"

geckob's solution works perfectly. Caution: The HAXM that you provide is used across all running devices. So if you are testing on a phone and Tablet at the same time and each has a requirement of 1G. Then make sure your HAXM alloted is atleast 2G.

Find something in column A then show the value of B for that row in Excel 2010

Assuming

source data range is A1:B100.
query cell is D1 (here you will input Police or Fire).
result cell is E1

Formula in E1 = VLOOKUP(D1, A1:B100, 2, FALSE)

HTML - Change\Update page contents without refreshing\reloading the page

jQuery will do the job. You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data. Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.

Random numbers with Math.random() in Java

If min = 5, and max = 10, and Math.random() returns (almost) 1.0, the generated number will be (almost) 15, which is clearly more than the chosen max.

Relatedly, this is why every random number API should let you specify min and max explicitly. You shouldn't have to write error-prone maths that are tangential to your problem domain.

Getting the button into the top right corner inside the div box

Just add position:absolute; top:0; right:0; to the CSS for your button.

 #button {
     line-height: 12px;
     width: 18px;
     font-size: 8pt;
     font-family: tahoma;
     margin-top: 1px;
     margin-right: 2px;
     position:absolute;
     top:0;
     right:0;
 }

jsFiddle example

What is Shelving in TFS?

Shelving is like your changes have been stored in the source control without affecting the existing changes. Means if you check in a file in source control it will modify the existing file but shelving is like storing your changes in source control but without modifying the actual changes.

Is there an equivalent to background-size: cover and contain for image elements?

Try setting both min-height and min-width, with display:block:

img {
    display:block;
    min-height:100%;
    min-width:100%;
}

(fiddle)

Provided your image's containing element is position:relative or position:absolute, the image will cover the container. However, it will not be centred.

You can easily centre the image if you know whether it will overflow horizontally (set margin-left:-50%) or vertically (set margin-top:-50%). It may be possible to use CSS media queries (and some mathematics) to figure that out.

Java enum - why use toString instead of name

Use name() when you want to make a comparison or use the hardcoded value for some internal use in your code.

Use toString() when you want to present information to a user (including a developper looking at a log). Never rely in your code on toString() giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString() return, then it was already broken.

From the javadoc (emphasis mine) :

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

how to create a logfile in php?

For printing log use this function, this will create log file in log folder. Create log folder if its not exists .

logger("Your msg in log ", "Filename you want ", "Data to be log string or array or object");


function logger($logMsg="logger", $filename="logger", $logData=""){     
            $log  = date("j.n.Y h:i:s")." || $logMsg : ".print_r($logData,1).PHP_EOL .                  
            "-------------------------".PHP_EOL;
            file_put_contents('./log/'.$filename.date("j.n.Y").'.log', $log, FILE_APPEND);                      
    }

Stop a youtube video with jquery?

1.include

<script type="text/javascript" src="http://www.youtube.com/player_api"></script>

2.add your youtube iframe.

<iframe id="player" src="http://www.youtube.com/embed/YOURID?rel=0&wmode=Opaque&enablejsapi=1" frameborder="0"></iframe>

3.magic time.

      <script>
            var player;
            function onYouTubePlayerAPIReady() {player = new YT.Player('player');}
            //so on jquery event or whatever call the play or stop on the video.
            //to play player.playVideo();
            //to stop player.stopVideo();
     </script>

What's the "Content-Length" field in HTTP header?

From here:

The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

   Content-Length    = "Content-Length" ":" 1*DIGIT

An example is

   Content-Length: 3495

Applications SHOULD use this field to indicate the transfer-length of the message-body, unless this is prohibited by the rules in section 4.4.

Any Content-Length greater than or equal to zero is a valid value. Section 4.4 describes how to determine the length of a message-body if a Content-Length is not given.

Note that the meaning of this field is significantly different from the corresponding definition in MIME, where it is an optional field used within the "message/external-body" content-type. In HTTP, it SHOULD be sent whenever the message's length can be determined prior to being transferred, unless this is prohibited by the rules in section 4.4.

My interpretation is that this means the length "on the wire", i.e. the length of the *encoded" content

SoapFault exception: Could not connect to host

In my case service address in wsdl is wrong.

My wsdl url is.

https://myweb.com:4460/xxx_webservices/services/ABC.ABC?wsdl

But service address in that xml result is.

<soap:address location="http://myweb.com:8080/xxx_webservices/services/ABC.ABC/"/>

I just save that xml to local file and change service address to.

<soap:address location="https://myweb.com:4460/xxx_webservices/services/ABC.ABC/"/>

Good luck.

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

Make it work, in values-v21 styles or theme xml needs to use this attribute:

<item name="android:windowTranslucentStatus">true</item>

That make the magic!

django: TypeError: 'tuple' object is not callable

There is comma missing in your tuple.

insert the comma between the tuples as shown:

pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))

Do the same for all

Converting int to bytes in Python 3

That's the way it was designed - and it makes sense because usually, you would call bytes on an iterable instead of a single integer:

>>> bytes([3])
b'\x03'

The docs state this, as well as the docstring for bytes:

 >>> help(bytes)
 ...
 bytes(int) -> bytes object of size given by the parameter initialized with null bytes

What does "hashable" mean in Python?

All the answers here have good working explanation of hashable objects in python, but I believe one needs to understand the term Hashing first.

Hashing is a concept in computer science which is used to create high performance, pseudo random access data structures where large amount of data is to be stored and accessed quickly.

For example, if you have 10,000 phone numbers, and you want to store them in an array (which is a sequential data structure that stores data in contiguous memory locations, and provides random access), but you might not have the required amount of contiguous memory locations.

So, you can instead use an array of size 100, and use a hash function to map a set of values to same indices, and these values can be stored in a linked list. This provides a performance similar to an array.

Now, a hash function can be as simple as dividing the number with the size of the array and taking the remainder as the index.

For more detail refer to https://en.wikipedia.org/wiki/Hash_function

Here is another good reference: http://interactivepython.org/runestone/static/pythonds/SortSearch/Hashing.html

How to determine if a list of polygon points are in clockwise order?

My C# / LINQ solution is based on the cross product advice of @charlesbretana is below. You can specify a reference normal for the winding. It should work as long as the curve is mostly in the plane defined by the up vector.

using System.Collections.Generic;
using System.Linq;
using System.Numerics;

namespace SolidworksAddinFramework.Geometry
{
    public static class PlanePolygon
    {
        /// <summary>
        /// Assumes that polygon is closed, ie first and last points are the same
        /// </summary>
       public static bool Orientation
           (this IEnumerable<Vector3> polygon, Vector3 up)
        {
            var sum = polygon
                .Buffer(2, 1) // from Interactive Extensions Nuget Pkg
                .Where(b => b.Count == 2)
                .Aggregate
                  ( Vector3.Zero
                  , (p, b) => p + Vector3.Cross(b[0], b[1])
                                  /b[0].Length()/b[1].Length());

            return Vector3.Dot(up, sum) > 0;

        } 

    }
}

with a unit test

namespace SolidworksAddinFramework.Spec.Geometry
{
    public class PlanePolygonSpec
    {
        [Fact]
        public void OrientationShouldWork()
        {

            var points = Sequences.LinSpace(0, Math.PI*2, 100)
                .Select(t => new Vector3((float) Math.Cos(t), (float) Math.Sin(t), 0))
                .ToList();

            points.Orientation(Vector3.UnitZ).Should().BeTrue();
            points.Reverse();
            points.Orientation(Vector3.UnitZ).Should().BeFalse();



        } 
    }
}

Generate Controller and Model

See all Available Controller : You can do PHP artisan list to view all commands

For help: PHP artisan help make:controller

php artisan make:controller MyControllerName

enter image description here

How do I extract text that lies between parentheses (round brackets)?

Use a Regular Expression:

string test = "(test)"; 
string word = Regex.Match(test, @"\((\w+)\)").Groups[1].Value;
Console.WriteLine(word);

Adding subscribers to a list using Mailchimp's API v3

If it helps anyone, here is what I got working in Python using the Python Requests library instead of CURL.

As explained by @staypuftman above, you will need your API Key and List ID from MailChimp and make sure your API Key suffix and URL prefix (i.e. us5) match.

Python:

#########################################################################################
# To add a single contact to MailChimp (using MailChimp v3.0 API), requires:
#   + MailChimp API Key
#   + MailChimp List Id for specific list
#   + MailChimp API URL for adding a single new contact
#
# Note: the API URL has a 3/4 character location subdomain at the front of the URL string. 
# It can vary depending on where you are in the world. To determine yours, check the last 
# 3/4 characters of your API key. The API URL location subdomain must match API Key 
# suffix e.g. us5, us13, us19 etc. but in this example, us5.
# (suggest you put the following 3 values in 'settings' or 'secrets' file)
#########################################################################################
MAILCHIMP_API_KEY = 'your-api-key-here-us5'
MAILCHIMP_LIST_ID = 'your-list-id-here'
MAILCHIMP_ADD_CONTACT_TO_LIST_URL = 'https://us5.api.mailchimp.com/3.0/lists/' + MAILCHIMP_LIST_ID + '/members/'

    # Create new contact data and convert into JSON as this is what MailChimp expects in the API
    # I've hardcoded some test data but use what you get from your form as appropriate
    new_contact_data_dict = {
        "email_address": "[email protected]",              # 'email_address' is a mandatory field
        "status": "subscribed",                           # 'status' is a mandatory field
        "merge_fields": {                                 # 'merge_fields' are optional:
            "FNAME": "John",                  
            "LNAME": "Smith"
        }
    }
    new_contact_data_json = json.dumps(new_contact_data_dict)

    # Create the new contact using MailChimp API using Python 'Requests' library
    req = requests.post(
        MAILCHIMP_ADD_CONTACT_TO_LIST_URL,
        data=new_contact_data_json,
        auth=('user', MAILCHIMP_API_KEY),
        headers={"content-type": "application/json"}
    )

    # debug info if required - .text and .json also list the 'merge_fields' names for use in contact JSON above
    # print req.status_code
    # print req.text
    # print req.json()

    if req.status_code == 200:
        # success - do anything you need to do
    else:
        # fail - do anything you need to do - but here is a useful debug message
        mailchimp_fail = 'MailChimp call failed calling this URL: {0}\n' \
                         'Returned this HTTP status code: {1}\n' \
                         'Returned this response text: {2}' \
                         .format(req.url, str(req.status_code), req.text)

Get table name by constraint name

ALL_CONSTRAINTS describes constraint definitions on tables accessible to the current user.

DBA_CONSTRAINTS describes all constraint definitions in the database.

USER_CONSTRAINTS describes constraint definitions on tables in the current user's schema

Select CONSTRAINT_NAME,CONSTRAINT_TYPE ,TABLE_NAME ,STATUS from 
USER_CONSTRAINTS;

How to add parameters to an external data query in Excel which can't be displayed graphically?

YES - solution is to save workbook in to XML file (eg. 'XML Spreadsheet 2003') and edit this file as text in notepad! use "SEARCH" function of notepad to find query text and change your data to "?".

save and open in excel, try refresh data and excel will be monit about parameters.

how to call javascript function in html.actionlink in asp.net mvc?

<a onclick="MyFunc()">blabla..</a>

There is nothing more in @Html.ActionLink that you could utilize in this case. And razor is evel by itself, drop it from where you can.

Why does Eclipse complain about @Override on interface methods?

Project specific settings may be enabled. Select your project Project > Properties > Java Compiler, uncheck the Enable project specific settings or change Jdk 1.6 and above not forgetting the corresponding JRE.
Incase it does not work, remove your project from eclipse, delete .settings folders, .project, .classpath files. clean and build the project, import it back into eclipse and then reset your Java compiler. Clean and build your projectand eclipse. It worked for me

How to replace specific values in a oracle database column?

In Oracle, there is the concept of schema name, so try using this

update schemname.tablename t
set t.columnname = replace(t.columnname, t.oldvalue, t.newvalue);

Get remote registry value

You can try using .net:

$Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer1)
$RegKey= $Reg.OpenSubKey("SOFTWARE\\Veritas\\NetBackup\\CurrentVersion")
$NetbackupVersion1 = $RegKey.GetValue("PackageVersion")

How to convert vector to array

std::vector<double> vec;
double* arr = vec.data();

How can I insert multiple rows into oracle with a sequence value?

This works:

insert into TABLE_NAME (COL1,COL2)
select my_seq.nextval, a
from
(SELECT 'SOME VALUE' as a FROM DUAL
 UNION ALL
 SELECT 'ANOTHER VALUE' FROM DUAL)

Changing image on hover with CSS/HTML

The problem is that you set the first image through 'src' attribute and on hover added to the image a background-image. try this:

in html use:

<img id="Library">

then in css:

#Library {
    height: 70px;
    width: 120px;
    background-image: url('LibraryTransparent.png');
}

#Library:hover {
    background-image: url('LibraryHoverTrans.png');
}

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

If you are receiving that error even after creating a new user and assigning them the database previledges, then the one last thing to look at is to check if the users have been assigned the preiveledges in the database.

To do this log into to your mysql(This is presumably its the application that has restricted access to the database but you as a root can be ablr to access your database table via mysql -u user -p)

commands to apply

mysql -u root -p 

password: (provide your database credentials)

on successful login

type

use mysql;

from this point check each users priveledges if it is enabled from the db table as follows

select User,Grant_priv,Host from db;

if the values of the Grant_priv col for the created user is N update that value to Y with the following command

UPDATE db SET Grant_priv = "Y" WHERE User= "your user";

with that now try accessing the app and making a transaction with the database.

What do 'lazy' and 'greedy' mean in the context of regular expressions?

try to understand the following behavior:

    var input = "0014.2";

Regex r1 = new Regex("\\d+.{0,1}\\d+");
Regex r2 = new Regex("\\d*.{0,1}\\d*");

Console.WriteLine(r1.Match(input).Value); // "0014.2"
Console.WriteLine(r2.Match(input).Value); // "0014.2"

input = " 0014.2";

Console.WriteLine(r1.Match(input).Value); // "0014.2"
Console.WriteLine(r2.Match(input).Value); // " 0014"

input = "  0014.2";

Console.WriteLine(r1.Match(input).Value); // "0014.2"
Console.WriteLine(r2.Match(input).Value); // ""

CSS background-image not working

<span class="btn-pTool">
         <a class="btn-pToolName" href="#"></a>
     </span>

Try to add display:block to .btn-pTool, and give it a width and height.

Also in your code both tbn-pTool and btn-pToolName have no text content, so that may result in them not being displayed at all.

You can try to force come content in them this way

.btn-pTool, .btn-pToolName {
    content: " ";
}