Programs & Examples On #Smartsvn

SmartSVN is a commercial cross-platform graphical Subversion client developed by WANdisco.

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

How to make promises work in IE11

If you want this type of code to run in IE11 (which does not support much of ES6 at all), then you need to get a 3rd party promise library (like Bluebird), include that library and change your coding to use ES5 coding structures (no arrow functions, no let, etc...) so you can live within the limits of what older browsers support.

Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.

Here's a version of your code written in ES5 syntax with the Bluebird promise library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>

<script>

'use strict';

var promise = new Promise(function(resolve) {
    setTimeout(function() {
        resolve("result");
    }, 1000);
});

promise.then(function(result) {
    alert("Fulfilled: " + result);
}, function(error) {
    alert("Rejected: " + error);
});

</script>

Finding second occurrence of a substring in a string in Java

You can write a function to return array of occurrence positions, Java has String.regionMatches function which is quite handy

public static ArrayList<Integer> occurrencesPos(String str, String substr) {
    final boolean ignoreCase = true;
    int substrLength = substr.length();
    int strLength = str.length();

    ArrayList<Integer> occurrenceArr = new ArrayList<Integer>();

    for(int i = 0; i < strLength - substrLength + 1; i++) {
        if(str.regionMatches(ignoreCase, i, substr, 0, substrLength))  {
            occurrenceArr.add(i);
        }
    }
    return occurrenceArr;
}

Photoshop text tool adds punctuation to the beginning of text

This is a paragraph option. Go to Window>Paragraph then a small window will pop up. You will have two buttons on the bottom. One with a arrow on the left of P and one on the right. Select the right one.

PHP Echo text Color

Try this

<?php 
echo '<i style="color:blue;font-size:30px;font-family:calibri ;">
      hello php color </i> ';
//we cannot use double quote after echo , it must be single quote.
?>

Get ASCII value at input word

char (with a lower-case c) is a numeric type. It already holds the ascii value of the char. Just cast it to an integer to display it as a numeric value rather than a textual value:

System.out.println("char " + ch + " has the following value : " + (int) ch);

How to create a batch file to run cmd as administrator

This Works for me in Windows 7 to 10 with parameters, when kick starting app or file from anywhere (including browser) and also when accessing file from anywhere. Replace (YOUR BATCH SCRIPT HERE anchor) with your code. This solution May Help :)

@echo off

call :isAdmin

if %errorlevel% == 0 (
    goto :run
) else (
    echo Requesting administrative privileges...
    goto :UACPrompt
)

exit /b

:isAdmin
    fsutil dirty query %systemdrive% >nul
exit /b

:run
  <YOUR BATCH SCRIPT HERE>
exit /b

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    echo UAC.ShellExecute "cmd.exe", "/c %~s0 %~1", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
exit /B

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

How to remove from a map while iterating it?

Assuming C++11, here is a one-liner loop body, if this is consistent with your programming style:

using Map = std::map<K,V>;
Map map;

// Erase members that satisfy needs_removing(itr)
for (Map::const_iterator itr = map.cbegin() ; itr != map.cend() ; )
  itr = needs_removing(itr) ? map.erase(itr) : std::next(itr);

A couple of other minor style changes:

  • Show declared type (Map::const_iterator) when possible/convenient, over using auto.
  • Use using for template types, to make ancillary types (Map::const_iterator) easier to read/maintain.

script to map network drive

Tomalak's answer worked great for me (+1)

I only needed to make alter it slightly for my purposes, and I didn't need a password - it's for corporate domain:

Option Explicit
Dim l: l = "Z:"
Dim s: s = "\\10.10.10.1\share"
Dim Network: Set Network = CreateObject("WScript.Network")
Dim CheckDrive: Set CheckDrive = Network.EnumNetworkDrives()
Dim DriveExists: DriveExists = False
Dim i

For i = 0 to CheckDrive.Count - 1
  If CheckDrive.Item(i) = l Then
    DriveExists = True
  End If
Next

If DriveExists = False Then
  Network.MapNetworkDrive l, s, False
Else
  MsgBox l + " Drive already mapped"
End If

Or if you want to disconnect the drive:

For i = 0 to CheckDrive.Count - 1
  If CheckDrive.Item(i) = l Then 
    WshNetwork.RemoveNetworkDrive CheckDrive.Item(i)
  End If
Next

Git Bash won't run my python files?

That command did not work for me, I used:

$ export PATH="$PATH:/c/Python27"

Then to make sure that git remembers the python path every time you open git type the following.

echo 'export PATH="$PATH:/c/Python27"' > .profile

Netbeans how to set command line arguments in Java

IF you are using MyEclipse and want to add args before run the program, Then do as follows: 1.0) Run -> Run Config 2.1) Click "Arguments" on the right panel 2.2)add your args in the "Program Args" box, separated by blank

Markdown and image alignment

Even cleaner would be to just put p#given img { float: right } in the style sheet, or in the <head> and wrapped in style tags. Then, just use the markdown ![Alt text](/path/to/img.jpg).

'uint32_t' does not name a type

You need to include iostream

#include <iostream>
using namespace std;

Run script with rc.local: script works, but not at boot

1 Do not recommend using root to run the apps such as node app.

Well you can do it but may catch more exceptions.

2 The rc.local normally runs as root user.

So if the your script should runs as another user such as www U should make sure the PATH and other environment is ok.

3 I find a easy way to run a service as a user:

sudo -u www -i /the/path/of/your/script

Please prefer the sudo manual~ -i [command] The -i (simulate initial login) option runs the shell specified by the password database entry of the target user as a loginshell...

How do I correctly detect orientation change using Phonegap on iOS?

here is what i did:

window.addEventListener('orientationchange', doOnOrientationChange);

function doOnOrientationChange()
{
      if (screen.height > screen.width) {
         console.log('portrait');
      } else {
         console.log('landscape');
      }
}

How to pass multiple parameters in a querystring

Try like this.It should work

Response.Redirect(String.Format("yourpage.aspx?strId={0}&strName={1}&strDate{2}", Server.UrlEncode(strId), Server.UrlEncode(strName),Server.UrlEncode(strDate)));

What does %s and %d mean in printf in the C language?

%(letter) denotes the format type of the replacement text. %s specifies a string, %d an integer, and %c a char.

Adobe Acrobat Pro make all pages the same dimension

You have to use the Print to a New PDF option using the PDF printer. Once in the dialog box, set the page scaling to 100% and set your page size. Once you do that, your new PDF will be uniform in page sizes.

How to switch text case in visual studio code

To have in Visual Studio Code what you can do in Sublime Text ( CTRL+K CTRL+U and CTRL+K CTRL+L ) you could do this:

  • Open "Keyboard Shortcuts" with click on "File -> Preferences -> Keyboard Shortcuts"
  • Click on "keybindings.json" link which appears under "Search keybindings" field
  • Between the [] brackets add:

    {
        "key": "ctrl+k ctrl+u",
        "command": "editor.action.transformToUppercase",
        "when": "editorTextFocus"
    },
    {
        "key": "ctrl+k ctrl+l",
        "command": "editor.action.transformToLowercase",
        "when": "editorTextFocus"
    }
    
  • Save and close "keybindings.json"


Another way:
Microsoft released "Sublime Text Keymap and Settings Importer", an extension which imports keybindings and settings from Sublime Text to VS Code. - https://marketplace.visualstudio.com/items?itemName=ms-vscode.sublime-keybindings

Styling input radio with css

Here is simple example of how you can do this.

Just replace the image file and you are done.

HTML Code

<input type="radio" id="r1" name="rr" />
<label for="r1"><span></span>Radio Button 1</label>
<p>
<input type="radio" id="r2" name="rr" />
<label for="r2"><span></span>Radio Button 2</label>

CSS

input[type="radio"] {
    display:none;
}

input[type="radio"] + label {
    color:#f2f2f2;
    font-family:Arial, sans-serif;
    font-size:14px;
}

input[type="radio"] + label span {
    display:inline-block;
    width:19px;
    height:19px;
    margin:-1px 4px 0 0;
    vertical-align:middle;
    background:url(check_radio_sheet.png) -38px top no-repeat;
    cursor:pointer;
}

input[type="radio"]:checked + label span {
    background:url(check_radio_sheet.png) -57px top no-repeat;
}

Working DEMO

Click in OK button inside an Alert (Selenium IDE)

Try Selenium 2.0b1. It has different core than the first version. It should support popup dialogs according to documentation:

Popup Dialogs

Starting with Selenium 2.0 beta 1, there is built in support for handling popup dialog boxes. After you’ve triggered and action that would open a popup, you can access the alert with the following:

Java

Alert alert = driver.switchTo().alert();

Ruby

driver.switch_to.alert

This will return the currently open alert object. With this object you can now accept, dismiss, read it’s contents or even type into a prompt. This interface works equally well on alerts, confirms, prompts. Refer to the JavaDocs for more information.

Git merge master into feature branch

In Eclipse -

1)Checkout master branch

Git Repositories ->Click on your repository -> click on Local ->double click master branch
->Click on yes for check out

2)Pull master branch

Right click on project ->click on Team -> Click on Pull

3)Checkout your feature branch(follow same steps mentioned in 1 point)

4)Merge master into feature

Git Repositories ->Click on your repository -> click on Local ->Right Click on your selected feature branch ->Click on merge ->Click on Local ->Click on Master ->Click on Merge.

5)Now you will get all changes of Master branch in feature branch. Remove conflict if any.

For conflict if any exists ,follow this -
Changes mentioned as Head(<<<<<< HEAD) is your change, Changes mentioned in branch(>>>>>>> branch) is other person change, you can update file accordingly.

Note - You need to do add to index for conflicts files

6)commit and push your changes in feature branch.

Right click on project ->click on Team -> Click on commit -> Commit and Push.

OR

Git Repositories ->Click on your repository -> click on Local ->Right Click on your selected feature branch ->Click on Push Branch ->Preview ->Push

How to make scipy.interpolate give an extrapolated result beyond the input range?

What about scipy.interpolate.splrep (with degree 1 and no smoothing):

>> tck = scipy.interpolate.splrep([1, 2, 3, 4, 5], [1, 4, 9, 16, 25], k=1, s=0)
>> scipy.interpolate.splev(6, tck)
34.0

It seems to do what you want, since 34 = 25 + (25 - 16).

How to check if object property exists with a variable holding the property name?

For own property :

var loan = { amount: 150 };
if(Object.prototype.hasOwnProperty.call(loan, "amount")) 
{ 
   //will execute
}

Note: using Object.prototype.hasOwnProperty is better than loan.hasOwnProperty(..), in case a custom hasOwnProperty is defined in the prototype chain (which is not the case here), like

var foo = {
      hasOwnProperty: function() {
        return false;
      },
      bar: 'Here be dragons'
    };

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

To include inherited properties in the finding use the in operator: (but you must place an object at the right side of 'in', primitive values will throw error, e.g. 'length' in 'home' will throw error, but 'length' in new String('home') won't)

const yoshi = { skulk: true };
const hattori = { sneak: true };
const kuma = { creep: true };
if ("skulk" in yoshi) 
    console.log("Yoshi can skulk");

if (!("sneak" in yoshi)) 
    console.log("Yoshi cannot sneak");

if (!("creep" in yoshi)) 
    console.log("Yoshi cannot creep");

Object.setPrototypeOf(yoshi, hattori);

if ("sneak" in yoshi)
    console.log("Yoshi can now sneak");
if (!("creep" in hattori))
    console.log("Hattori cannot creep");

Object.setPrototypeOf(hattori, kuma);

if ("creep" in hattori)
    console.log("Hattori can now creep");
if ("creep" in yoshi)
    console.log("Yoshi can also creep");

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

Note: One may be tempted to use typeof and [ ] property accessor as the following code which doesn't work always ...

var loan = { amount: 150 };

loan.installment = undefined;

if("installment" in loan) // correct
{
    // will execute
}

if(typeof loan["installment"] !== "undefined") // incorrect
{
    // will not execute
}

XML string to XML document

This code sample is taken from csharp-examples.net, written by Jan Slama:

To find nodes in an XML file you can use XPath expressions. Method XmlNode.Selec­tNodes returns a list of nodes selected by the XPath string. Method XmlNode.Selec­tSingleNode finds the first node that matches the XPath string.

XML:

<Names>
    <Name>
        <FirstName>John</FirstName>
        <LastName>Smith</LastName>
    </Name>
    <Name>
        <FirstName>James</FirstName>
        <LastName>White</LastName>
    </Name>
</Names>

CODE:

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"

XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
  string firstName = xn["FirstName"].InnerText;
  string lastName = xn["LastName"].InnerText;
  Console.WriteLine("Name: {0} {1}", firstName, lastName);
}

Inserting the same value multiple times when formatting a string

You can use advanced string formatting, available in Python 2.6 and Python 3.x:

incoming = 'arbit'
result = '{0} hello world {0} hello world {0}'.format(incoming)

How to set a default value with Html.TextBoxFor?

This should work for MVC3 & MVC4

 @Html.TextBoxFor(m => m.Age, new { @Value = "12" }) 

If you want it to be a hidden field

 @Html.TextBoxFor(m => m.Age, new { @Value = "12",@type="hidden" }) 

What is the difference between C++ and Visual C++?

C++ is a language and Visual C++ is a compiler for that language. Certainly, it (and every other compiler) introduces tiny modifications to the language, but the language recognized is mainly the same.

"Least Astonishment" and the Mutable Default Argument

This is not a design flaw. Anyone who trips over this is doing something wrong.

There are 3 cases I see where you might run into this problem:

  1. You intend to modify the argument as a side effect of the function. In this case it never makes sense to have a default argument. The only exception is when you're abusing the argument list to have function attributes, e.g. cache={}, and you wouldn't be expected to call the function with an actual argument at all.
  2. You intend to leave the argument unmodified, but you accidentally did modify it. That's a bug, fix it.
  3. You intend to modify the argument for use inside the function, but didn't expect the modification to be viewable outside of the function. In that case you need to make a copy of the argument, whether it was the default or not! Python is not a call-by-value language so it doesn't make the copy for you, you need to be explicit about it.

The example in the question could fall into category 1 or 3. It's odd that it both modifies the passed list and returns it; you should pick one or the other.

What does the "@" symbol do in Powershell?

PowerShell will actually treat any comma-separated list as an array:

"server1","server2"

So the @ is optional in those cases. However, for associative arrays, the @ is required:

@{"Key"="Value";"Key2"="Value2"}

Officially, @ is the "array operator." You can read more about it in the documentation that installed along with PowerShell, or in a book like "Windows PowerShell: TFM," which I co-authored.

Enable/Disable a dropdownbox in jquery

$("#chkdwn2").change(function() { 
    if (this.checked) $("#dropdown").prop("disabled",'disabled');
}) 

Create a directory if it does not exist and then create the files in that directory as well

Trying to make this as short and simple as possible. Creates directory if it doesn't exist, and then returns the desired file:

/** Creates parent directories if necessary. Then returns file */
private static File fileWithDirectoryAssurance(String directory, String filename) {
    File dir = new File(directory);
    if (!dir.exists()) dir.mkdirs();
    return new File(directory + "/" + filename);
}

What's the best way to detect a 'touch screen' device using JavaScript?

Right so there is a huge debate over detecting touch/non-touch devices. The number of window tablets and the size of tablets is increasing creating another set of headaches for us web developers.

I have used and tested blmstr's answer for a menu. The menu works like this: when the page loads the script detects if this is a touch or non touch device. Based on that the menu would work on hover (non-touch) or on click/tap (touch).

In most of the cases blmstr's scripts seemed to work just fine (specifically the 2018 one). BUT there was still that one device that would be detected as touch when it is not or vice versa.

For this reason I did a bit of digging and thanks to this article I replaced a few lines from blmstr's 4th script into this:

_x000D_
_x000D_
function is_touch_device4() {
    if ("ontouchstart" in window)
        return true;

    if (window.DocumentTouch && document instanceof DocumentTouch)
        return true;


    return window.matchMedia( "(pointer: coarse)" ).matches;
}

alert('Is touch device: '+is_touch_device4());
console.log('Is touch device: '+is_touch_device4());
_x000D_
_x000D_
_x000D_

Because of the lockdown have a limited supply of touch devices to test this one but so far the above works great.

I would appreceate if anyone with a desktop touch device (ex. surface tablet) can confirm if script works all right.

Now in terms of support the pointer: coarse media query seems to be supported. I kept the lines above since I had (for some reason) issues on mobile firefox but the lines above the media query do the trick.

Thanks

CSS :selected pseudo class similar to :checked, but for <select> elements

This worked for me :

select option {
   color: black;
}
select:not(:checked) {
   color: gray;
}

Google maps API V3 method fitBounds()

This happens because LatLngBounds() does not take two arbitrary points as parameters, but SW and NE points

use the .extend() method on an empty bounds object

var bounds = new google.maps.LatLngBounds();
bounds.extend(myPlace);
bounds.extend(Item_1);
map.fitBounds(bounds);

Demo at http://jsfiddle.net/gaby/22qte/

Is there a difference between "==" and "is"?

Your answer is correct. The is operator compares the identity of two objects. The == operator compares the values of two objects.

An object's identity never changes once it has been created; you may think of it as the object's address in memory.

You can control comparison behaviour of object values by defining a __cmp__ method or a rich comparison method like __eq__.

Creating an Instance of a Class with a variable in Python

Given your edit i assume you have the class name as a string and want to instantiate the class? Just use a dictionary as a dispatcher.

class Foo(object):
    pass

class Bar(object):
    pass

dispatch_dict = {"Foo": Foo, "Bar": Bar}
dispatch_dict["Foo"]() # returns an instance of Foo

Assign null to a SqlParameter

Try this:

SqlParameter[] parameters = new SqlParameter[1];    
SqlParameter planIndexParameter = new SqlParameter("@AgeIndex", SqlDbType.Int);

planIndexParameter.IsNullable = true; // Add this line

planIndexParameter.Value = (AgeItem.AgeIndex== null) ? DBNull.Value : AgeItem.AgeIndex== ;
parameters[0] = planIndexParameter;

Excel data validation with suggestions/autocomplete

This is a solution how to make autocomplete drop down list with VBA :


Firstly you need to insert a combo box into the worksheet and change its properties, and then running the VBA code to enable the autocomplete.

  1. Get into the worksheet which contains the drop down list you want it to be autocompleted.

  2. Before inserting the Combo box, you need to enable the Developer tab in the ribbon.

a). In Excel 2010 and 2013, click File > Options. And in the Options dialog box, click Customize Ribbon in the right pane, check the Developer box, then click the OK button.

b). In Outlook 2007, click Office button > Excel Options. In the Excel Options dialog box, click Popular in the right bar, then check the Show Developer tabin the Ribbon box, and finally click the OK button.

  1. Then click Developer > Insert > Combo Box under ActiveX Controls.

  2. Draw the combo box in current opened worksheet and right click it. Select Properties in the right-clicking menu.

  3. Turn off the Design Mode with clicking Developer > Design Mode.

  4. Right click on the current opened worksheet tab and click View Code.

  5. Make sure that the current worksheet code editor is opened, and then copy and paste the below VBA code into it.

Code borrowed from extendoffice.com

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Update by Extendoffice: 2018/9/21
    Dim xCombox As OLEObject
    Dim xStr As String
    Dim xWs As Worksheet
    Dim xArr



    Set xWs = Application.ActiveSheet
    On Error Resume Next
    Set xCombox = xWs.OLEObjects("TempCombo")
    With xCombox
        .ListFillRange = ""
        .LinkedCell = ""
        .Visible = False
    End With
    If Target.Validation.Type = 3 Then
        Target.Validation.InCellDropdown = False
        Cancel = True
        xStr = Target.Validation.Formula1
        xStr = Right(xStr, Len(xStr) - 1)
        If xStr = "" Then Exit Sub
        With xCombox
            .Visible = True
            .Left = Target.Left
            .Top = Target.Top
            .Width = Target.Width + 5
            .Height = Target.Height + 5
            .ListFillRange = xStr
            If .ListFillRange = "" Then
                xArr = Split(xStr, ",")
                Me.TempCombo.List = xArr
            End If
            .LinkedCell = Target.Address
        End With
        xCombox.Activate
        Me.TempCombo.DropDown
    End If
End Sub

Private Sub TempCombo_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    Select Case KeyCode
        Case 9
            Application.ActiveCell.Offset(0, 1).Activate
        Case 13
            Application.ActiveCell.Offset(1, 0).Activate
    End Select
End Sub
  1. Click File > Close and Return to Microsoft Excel to close the Microsoft Visual Basic for Application window.

  2. Now, just click the cell with drop down list, you can see the drop-down list is displayed as a combo box, then type the first letter into the box, the corresponding word will be completed automatically.

Note: This VBA code is not applied to merged cells.

Source : How To Autocomplete When Typing In Excel Drop Down List?

Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?

May be You are not registering the Controllers. Try below code:

Step 1. Write your own controller factory class ControllerFactory :DefaultControllerFactory by implementing defaultcontrollerfactory in models folder

  public class ControllerFactory :DefaultControllerFactory
    {
    protected override IController GetControllerInstance(RequestContext         requestContext, Type controllerType)
        {
            try
            {
                if (controllerType == null)
                    throw new ArgumentNullException("controllerType");

                if (!typeof(IController).IsAssignableFrom(controllerType))
                    throw new ArgumentException(string.Format(
                        "Type requested is not a controller: {0}",
                        controllerType.Name),
                        "controllerType");

                return MvcUnityContainer.Container.Resolve(controllerType) as IController;
            }
            catch
            {
                return null;
            }

        }
        public static class MvcUnityContainer
        {
            public static UnityContainer Container { get; set; }
        }
    }

Step 2:Regigster it in BootStrap: inBuildUnityContainer method

private static IUnityContainer BuildUnityContainer()
    {
      var container = new UnityContainer();

      // register all your components with the container here
      // it is NOT necessary to register your controllers

      // e.g. container.RegisterType<ITestService, TestService>();    
      //RegisterTypes(container);
      container = new UnityContainer();
      container.RegisterType<IProductRepository, ProductRepository>();


      MvcUnityContainer.Container = container;
      return container;
    }

Step 3: In Global Asax.

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
            Bootstrapper.Initialise();
            ControllerBuilder.Current.SetControllerFactory(typeof(ControllerFactory));

        }

And you are done

How can I check if character in a string is a letter? (Python)

This works:

any(c.isalpha() for c in 'string')

MongoDB: How to update multiple documents with a single command?

In the MongoDB Client, type:

db.Collection.updateMany({}, $set: {field1: 'field1', field2: 'field2'})

New in version 3.2

Params::

{}:  select all records updated

Keyword argument multi not taken

Extract substring using regexp in plain bash

If your string is

foo="US/Central - 10:26 PM (CST)"

then

echo "${foo}" | cut -d ' ' -f3

will do the job.

document.getElementByID is not a function

It's getElementById()

Note the lower-case d in Id.

Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server."

<add key="aspnet:MaxHttpCollectionKeys" value="100000"/ >

Add above key to Web.config or App.config to remove this error.

How can I view the Git history in Visual Studio Code?

You won't need a plugin to see commit history with Visual Studio Code 1.42 or more.

Timeline view

In this milestone, we've made progress on the new Timeline view, and have an early preview to share.
This is a unified view for visualizing time-series events (e.g. commits, saves, test runs, etc.) for a resource (file, folder, etc.).

To enable the Timeline view, you must be using the Insiders Edition (VSCode 1.44 March 2020) and then add the following setting:

"timeline.showView": true

https://media.githubusercontent.com/media/microsoft/vscode-docs/vnext/release-notes/images/1_42/timeline.png

Multi-Line Comments in Ruby?

Despite the existence of =begin and =end, the normal and a more correct way to comment is to use #'s on each line. If you read the source of any ruby library, you will see that this is the way multi-line comments are done in almost all cases.

Can I do Model->where('id', ARRAY) multiple where conditions?

If you need by several params:

$ids = [1,2,3,4];
$not_ids = [5,6,7,8];
DB::table('table')->whereIn('id', $ids)
                  ->whereNotIn('id', $not_ids)
                  ->where('status', 1)
                  ->get();

How to change color of Toolbar back button in Android?

I am using <style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar> theme in my android application and in NoActionBar theme, colorControlNormal property is used to change the color of navigation icon default Back button arrow in my toolbar

styles.xml

<style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
  <item name="colorControlNormal">@color/your_color</item> 
</style>

How to set custom header in Volley Request

If what you need is to post data instead of adding the info in the url.

public Request post(String url, String username, String password, 
      Listener listener, ErrorListener errorListener) {
  JSONObject params = new JSONObject();
  params.put("user", username);
  params.put("pass", password);
  Request req = new Request(
     Method.POST,
     url,
     params.toString(),
     listener,
     errorListener
  );

  return req;
}

If what you want to do is edit the headers in the request this is what you want to do:

// could be any class that implements Map
Map<String, String> mHeaders = new ArrayMap<String, String>();
mHeaders.put("user", USER);
mHeaders.put("pass", PASSWORD);
Request req = new Request(url, postBody, listener, errorListener) {
  public Map<String, String> getHeaders() {
    return mHeaders;
  }
}

Extracting specific columns from a data frame

This is the role of the subset() function:

> dat <- data.frame(A=c(1,2),B=c(3,4),C=c(5,6),D=c(7,7),E=c(8,8),F=c(9,9)) 
> subset(dat, select=c("A", "B"))
  A B
1 1 3
2 2 4

Windows batch file file download from a URL

Last I checked, there isn't a command line command to connect to a URL from the MS command line. Try wget for Windows:
http://gnuwin32.sourceforge.net/packages/wget.htm

or URL2File:
http://www.chami.com/free/url2file_wincon.html

In Linux, you can use "wget".

Alternatively, you can try VBScript. They are like command line programs, but they are scripts interpreted by the wscript.exe scripts host. Here is an example of downloading a file using VBS:
https://serverfault.com/questions/29707/download-file-from-vbscript

How to make android listview scrollable?

Practically its not good to do. But if you want to do like this, just make listview's height fixed to wrap_content.

android:layout_height="wrap_content"

Compiler error: memset was not declared in this scope

Whevever you get a problem like this just go to the man page for the function in question and it will tell you what header you are missing, e.g.

$ man memset

MEMSET(3)                BSD Library Functions Manual                MEMSET(3)

NAME
     memset -- fill a byte string with a byte value

LIBRARY
     Standard C Library (libc, -lc)

SYNOPSIS
     #include <string.h>

     void *
     memset(void *b, int c, size_t len);

Note that for C++ it's generally preferable to use the proper equivalent C++ headers, <cstring>/<cstdio>/<cstdlib>/etc, rather than C's <string.h>/<stdio.h>/<stdlib.h>/etc.

Open files in 'rt' and 'wt' modes

The 'r' is for reading, 'w' for writing and 'a' is for appending.

The 't' represents text mode as apposed to binary mode.

Several times here on SO I've seen people using rt and wt modes for reading and writing files.

Edit: Are you sure you saw rt and not rb?

These functions generally wrap the fopen function which is described here:

http://www.cplusplus.com/reference/cstdio/fopen/

As you can see it mentions the use of b to open the file in binary mode.

The document link you provided also makes reference to this b mode:

Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.

How to use font-awesome icons from node-modules

If you're using npm you could use Gulp.js a build tool to build your Font Awesome packages from SCSS or LESS. This example will compile the code from SCSS.

  1. Install Gulp.js v4 locally and CLI V2 globally.

  2. Install a plugin called gulp-sass using npm.

  3. Create a main.scss file in your public folder and use this code:

    $fa-font-path: "../webfonts";
    @import "fontawesome/fontawesome";
    @import "fontawesome/brands";
    @import "fontawesome/regular";
    @import "fontawesome/solid";
    @import "fontawesome/v4-shims";
    
  4. Create a gulpfile.js in your app directory and copy this.

    const { src, dest, series, parallel } = require('gulp');
    const sass = require('gulp-sass');
    const fs = require('fs');
    
    function copyFontAwesomeSCSS() {
       return src('node_modules/@fortawesome/fontawesome-free/scss/*.scss')
         .pipe(dest('public/scss/fontawesome'));
    }
    
    function copyFontAwesomeFonts() {
       return src('node_modules/@fortawesome/fontawesome-free/webfonts/*')
         .pipe(dest('public/dist/webfonts'));
     }
    
     function compileSCSS() { 
       return src('./public/scss/theme.scss')
         .pipe(sass()).pipe(dest('public/css'));
     }
    
     // Series completes tasks sequentially and parallel completes them asynchronously
     exports.build = parallel(
       copyFontAwesomeFonts,
       series(copyFontAwesomeSCSS, compileSCSS)
     );
    
  5. Run 'gulp build' in your command line and watch the magic.

What does HTTP/1.1 302 mean exactly?

For anyone who might be curious about the naming, I'm just going to add that it's probably called "Found" because the main resource(e.g., a private web page) the user intends to receive is not available at that moment(e.g., the user has not proved their identity yet), so instead the server has found a new resource that the user can receive(which is a login page in the most common use case).

Also it's "getting lost and found" in the hide-and-seek manner, meaning a lost resource under a 302 status is only lost temporarily, it is not supposed to be lost forever(unless a player has some bad intentions;)).

How to specify more spaces for the delimiter using cut?

Actually awk is exactly the tool you should be looking into:

ps axu | grep '[j]boss' | awk '{print $5}'

or you can ditch the grep altogether since awk knows about regular expressions:

ps axu | awk '/[j]boss/ {print $5}'

But if, for some bizarre reason, you really can't use awk, there are other simpler things you can do, like collapse all whitespace to a single space first:

ps axu | grep '[j]boss' | sed 's/\s\s*/ /g' | cut -d' ' -f5

That grep trick, by the way, is a neat way to only get the jboss processes and not the grep jboss one (ditto for the awk variant as well).

The grep process will have a literal grep [j]boss in its process command so will not be caught by the grep itself, which is looking for the character class [j] followed by boss.

This is a nifty way to avoid the | grep xyz | grep -v grep paradigm that some people use.

Pointer arithmetic for void pointer in C

Pointer arithmetic is not allowed on void* pointers.

How can I change my Cygwin home folder after installation?

Cygwin mount now support bind method which lets you mount a directory. Hence you can simply add the following line to /etc/fstab, then restart your shell:

c:/Users /home none bind 0 0

Convert Promise to Observable

If you are using RxJS 6.0.0:

import { from } from 'rxjs';
const observable = from(promise);

LINQ .Any VS .Exists - What's the difference?

See documentation

List.Exists (Object method - MSDN)

Determines whether the List(T) contains elements that match the conditions defined by the specified predicate.

This exists since .NET 2.0, so before LINQ. Meant to be used with the Predicate delegate, but lambda expressions are backward compatible. Also, just List has this (not even IList)

IEnumerable.Any (Extension method - MSDN)

Determines whether any element of a sequence satisfies a condition.

This is new in .NET 3.5 and uses Func(TSource, bool) as argument, so this was intended to be used with lambda expressions and LINQ.

In behaviour, these are identical.

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

select convert(varchar(11), transfer_date, 106)

got me my desired result of date formatted as 07 Mar 2018

My column transfer_date is a datetime type column and I am using SQL Server 2017 on azure

Android sample bluetooth code to send a simple string via bluetooth

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I check if file exists in Makefile so I can delete it?

Missing a semicolon

if [ -a myApp ];
then
  rm myApp
fi

However, I assume you are checking for existence before deletion to prevent an error message. If so, you can just use rm -f myApp which "forces" delete, i.e. doesn't error out if the file didn't exist.

Enable & Disable a Div and its elements in Javascript

The following selects all descendant elements and disables them:

$("#dcacl").find("*").prop("disabled", true);

But it only really makes sense to disable certain element types: inputs, buttons, etc., so you want a more specific selector:

$("#dcac1").find(":input").prop("disabled",true);
// noting that ":input" gives you the equivalent of
$("#dcac1").find("input,select,textarea,button").prop("disabled",true);

To re-enable you just set "disabled" to false.

I want to Disable them at loading the page and then by a click i can enable them

OK, so put the above code in a document ready handler, and setup an appropriate click handler:

$(document).ready(function() {
    var $dcac1kids = $("#dcac1").find(":input");
    $dcac1kids.prop("disabled",true);

    // not sure what you want to click on to re-enable
    $("selector for whatever you want to click").one("click",function() {
       $dcac1kids.prop("disabled",false);
    }
}

I've cached the results of the selector on the assumption that you're not adding more elements to the div between the page load and the click. And I've attached the click handler with .one() since you haven't specified a requirement to re-disable the elements so presumably the event only needs to be handled once. Of course you can change the .one() to .click() if appropriate.

Disabling the long-running-script message in Internet Explorer

In my case, while playing video, I needed to call a function everytime currentTime of video updates. So I used timeupdate event of video and I came to know that it was fired at least 4 times a second (depends on the browser you use, see this). So I changed it to call a function every second like this:

var currentIntTime = 0;

var someFunction = function() {
    currentIntTime++;
    // Do something here
} 
vidEl.on('timeupdate', function(){
    if(parseInt(vidEl.currentTime) > currentIntTime) {
        someFunction();
    }
});

This reduces calls to someFunc by at least 1/3 and it may help your browser to behave normally. It did for me !!!

Windows ignores JAVA_HOME: how to set JDK as default?

Just in case if you are using .BAT file as Windows Service, I would suggest to uninstall the Windows service and reinstall it again after changing the %JAVA_HOME% to point to the right Java version..

How to remove focus without setting focus to another control?

You do not need to clear focus, just add this code where you want to focus

 time_statusTV.setFocusable(true);
 time_statusTV.requestFocus();
 InputMethodManager imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);
 imm.showSoftInput( time_statusTV, 0);

ld cannot find an existing library

Installing libgl1-mesa-dev from the Ubuntu repo resolved this problem for me.

How to check if a registry value exists using C#?

public bool ValueExists(RegistryKey Key, string Value)
{
   try
   {
       return Key.GetValue(Value) != null;
   }
   catch
   {
       return false;
   }
}

This simple function will return true only if a value is found but it is not null, else will return false if the value exists but it is null or the value doesn't exists in the key.


USAGE for your question:

if (ValueExists(winLogonKey, "Start")
{
    // The values exists
}
else
{
    // The values does not exists
}

Twitter Bootstrap scrollable table rows and fixed header

Interesting question, I tried doing this by just doing a fixed position row, but this way seems to be a much better one. Source at bottom.

css

thead { display:block; background: green; margin:0px; cell-spacing:0px; left:0px; }
tbody { display:block; overflow:auto; height:100px; }
th { height:50px; width:80px; }
td { height:50px; width:80px; background:blue; margin:0px; cell-spacing:0px;}

html

<table>
    <thead>
        <tr><th>hey</th><th>ho</th></tr>
    </thead>
    <tbody>
        <tr><td>test</td><td>test</td></tr>
        <tr><td>test</td><td>test</td></tr>
        <tr><td>test</td><td>test</td></tr>
</tbody>

http://www.imaputz.com/cssStuff/bigFourVersion.html

Is there an equivalent of CSS max-width that works in HTML emails?

There is a trick you can do for Outlook 2007 using conditional html comments.
The code below will make sure that Outlook table is 800px wide, its not max-width but it works better than letting the table span across the entire window.

<!--[if gte mso 9]>
<style>
#tableForOutlook {
  width:800px;
}
</style>
<![endif]-->

<table style="width:98%;max-width:800px">
<!--[if gte mso 9]>
  <table id="tableForOutlook"><tr><td>
<![endif]-->
    <tr><td>
    [Your Content Goes Here]
    </td></tr>
<!--[if gte mso 9]>
  </td></tr></table>
<![endif]-->
<table>

How to grep (search) committed code in the Git history

Adding more to the answers already present. If you know the file in which you might have made do this:

git log --follow -p -S 'search-string' <file-path>

--follow: lists the history of a file

How to remove all debug logging calls before building the release version of an Android app?

I have used a LogUtils class like in the Google IO example application. I modified this to use an application specific DEBUG constant instead of BuildConfig.DEBUG because BuildConfig.DEBUG is unreliable. Then in my Classes I have the following.

import static my.app.util.LogUtils.makeLogTag;
import static my.app.util.LogUtils.LOGV;

public class MyActivity extends FragmentActivity {
  private static final String TAG = makeLogTag(MyActivity.class);

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LOGV(TAG, "my message");
  }
}

JavaScript "cannot read property "bar" of undefined

If an object's property may refer to some other object then you can test that for undefined before trying to use its properties:

if (thing && thing.foo)
   alert(thing.foo.bar);

I could update my answer to better reflect your situation if you show some actual code, but possibly something like this:

function someFunc(parameterName) {
   if (parameterName && parameterName.foo)
       alert(parameterName.foo.bar);
}

Using jquery to delete all elements with a given id

The cleanest way to do it is by using html5 selectors api, specifically querySelectorAll().

var contentToRemove = document.querySelectorAll("#myid");
$(contentToRemove).remove(); 

The querySelectorAll() function returns an array of dom elements matching a specific id. Once you have assigned the returned array to a var, then you can pass it as an argument to jquery remove().

Base64 decode snippet in C++

I use this:

class BinaryVector {
public:
    std::vector<char> bytes;

    uint64_t bit_count = 0;

public:
    /* Add a bit to the end */
    void push_back(bool bit);

    /* Return false if character is unrecognized */
    bool pushBase64Char(char b64_c);
};

void BinaryVector::push_back(bool bit)
{
    if (!bit_count || bit_count % 8 == 0) {
        bytes.push_back(bit << 7);
    }
    else {
        uint8_t next_bit = 8 - (bit_count % 8) - 1;
        bytes[bit_count / 8] |= bit << next_bit;
    }
    bit_count++;
}

/* Converts one Base64 character to 6 bits */
bool BinaryVector::pushBase64Char(char c)
{
    uint8_t d;

    // A to Z
    if (c > 0x40 && c < 0x5b) {
        d = c - 65;  // Base64 A is 0
    }
    // a to z
    else if (c > 0x60 && c < 0x7b) {
        d = c - 97 + 26;  // Base64 a is 26
    }
    // 0 to 9
    else if (c > 0x2F && c < 0x3a) {
        d = c - 48 + 52;  // Base64 0 is 52
    }
    else if (c == '+') {
        d = 0b111110;
    }
    else if (c == '/') {
        d = 0b111111;
    }
    else if (c == '=') {
        d = 0;
    }
    else {
        return false;
    }

    push_back(d & 0b100000);
    push_back(d & 0b010000);
    push_back(d & 0b001000);
    push_back(d & 0b000100);
    push_back(d & 0b000010);
    push_back(d & 0b000001);

    return true;
}

bool loadBase64(std::vector<char>& b64_bin, BinaryVector& vec)
{
    for (char& c : b64_bin) {
        if (!vec.pushBase64Char(c)) {
            return false;
        }
    }
    return true;
}

Use vec.bytes to access converted data.

@Autowired and static method

This builds upon @Pavel's answer, to solve the possibility of Spring context not being initialized when accessing from the static getBean method:

@Component
public class Spring {
  private static final Logger LOG = LoggerFactory.getLogger (Spring.class);

  private static Spring spring;

  @Autowired
  private ApplicationContext context;

  @PostConstruct
  public void registerInstance () {
    spring = this;
  }

  private Spring (ApplicationContext context) {
    this.context = context;
  }

  private static synchronized void initContext () {
    if (spring == null) {
      LOG.info ("Initializing Spring Context...");
      ApplicationContext context = new AnnotationConfigApplicationContext (io.zeniq.spring.BaseConfig.class);
      spring = new Spring (context);
    }
  }

  public static <T> T getBean(String name, Class<T> className) throws BeansException {
    initContext();
    return spring.context.getBean(name, className);
  }

  public static <T> T getBean(Class<T> className) throws BeansException {
    initContext();
    return spring.context.getBean(className);
  }

  public static AutowireCapableBeanFactory getBeanFactory() throws IllegalStateException {
    initContext();
    return spring.context.getAutowireCapableBeanFactory ();
  }
}

The important piece here is the initContext method. It ensures that the context will always get initialized. But, do note that initContext will be a point of contention in your code as it is synchronized. If your application is heavily parallelized (for eg: the backend of a high traffic site), this might not be a good solution for you.

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

How do I run a simple bit of code in a new thread?

BackgroundWorker seems to be best choice for you.

Here is my minimal example. After you click on the button the background worker will begin working in background thread and also report its progress simultaneously. It will also report after the work completes.

using System.ComponentModel;
...
    private void button1_Click(object sender, EventArgs e)
    {
        BackgroundWorker bw = new BackgroundWorker();

        // this allows our worker to report progress during work
        bw.WorkerReportsProgress = true;

        // what to do in the background thread
        bw.DoWork += new DoWorkEventHandler(
        delegate(object o, DoWorkEventArgs args)
        {
            BackgroundWorker b = o as BackgroundWorker;

            // do some simple processing for 10 seconds
            for (int i = 1; i <= 10; i++)
            {
                // report the progress in percent
                b.ReportProgress(i * 10);
                Thread.Sleep(1000);
            }

        });

        // what to do when progress changed (update the progress bar for example)
        bw.ProgressChanged += new ProgressChangedEventHandler(
        delegate(object o, ProgressChangedEventArgs args)
        {
            label1.Text = string.Format("{0}% Completed", args.ProgressPercentage);
        });

        // what to do when worker completes its task (notify the user)
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
        delegate(object o, RunWorkerCompletedEventArgs args)
        {
            label1.Text = "Finished!";
        });

        bw.RunWorkerAsync();
    }

Note:

  • I put everything in single method using C#'s anonymous method for simplicity but you can always pull them out to different methods.
  • It is safe to update GUI within ProgressChanged or RunWorkerCompleted handlers. However, updating GUI from DoWork will cause InvalidOperationException.

Getting "conflicting types for function" in C, why?

When you don't give a prototype for the function before using it, C assumes that it takes any number of parameters and returns an int. So when you first try to use do_something, that's the type of function the compiler is looking for. Doing this should produce a warning about an "implicit function declaration".

So in your case, when you actually do declare the function later on, C doesn't allow function overloading, so it gets pissy because to it you've declared two functions with different prototypes but with the same name.

Short answer: declare the function before trying to use it.

Android: Go back to previous activity

Are you wanting to take control of the back button behavior? You can override the back button (to go to a specific activity) via one of two methods.

For Android 1.6 and below:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        // do something on back.
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

Or if you are only supporting Android 2.0 or greater:

@Override
public void onBackPressed() {
    // do something on back.
    return;
}

For more details: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html

How to change the button text of <input type="file" />?

Only CSS & bootstrap class

        <div class="col-md-4 input-group">
            <input class="form-control" type="text"/>
            <div class="input-group-btn">
                <label for="files" class="btn btn-default">browse</label>
                <input id="files" type="file" class="btn btn-default"  style="visibility:hidden;"/>
            </div>
        </div>

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

I had this issue while working at the local Starbucks and I remembered that when I initially set up my database through Mongo Atlas. I set my IP address to be able to access the database. After looking through several threads, I changed my IP address on Atlas and the issue went away. Hope this helps someone.

Get full path without filename from path that includes filename

I used this and it works well:

string[] filePaths = Directory.GetFiles(Path.GetDirectoryName(dialog.FileName));

foreach (string file in filePaths)
{   
    if (comboBox1.SelectedItem.ToString() == "")
    {
        if (file.Contains("c"))
        {
            comboBox2.Items.Add(Path.GetFileName(file));
        }
    }
}

Where can I get a list of Ansible pre-defined variables?

ansible -m setup hostname

Only gets the facts gathered by the setup module.

Gilles Cornu posted a template trick to list all variables for a specific host.

Template (later called dump_variables):

HOSTVARS (ANSIBLE GATHERED, group_vars, host_vars) :

{{ hostvars[inventory_hostname] | to_yaml }}

PLAYBOOK VARS:

{{ vars | to_yaml }}

Playbook to use it:

- hosts: all
  tasks:
  - template:
      src: templates/dump_variables
      dest: /tmp/ansible_variables
  - fetch:
      src: /tmp/ansible_variables
      dest: "{{inventory_hostname}}_ansible_variables"

After that you have a dump of all variables on every host, and a copy of each text dump file on your local workstation in your tmp folder. If you don't want local copies, you can remove the fetch statement.

This includes gathered facts, host variables and group variables. Therefore you see ansible default variables like group_names, inventory_hostname, ansible_ssh_host and so on.

Update date + one year in mysql

For multiple interval types use a nested construction as in:

 UPDATE table SET date = DATE_ADD(DATE_ADD(date, INTERVAL 1 YEAR), INTERVAL 1 DAY)

For updating a given date in the column date to 1 year + 1 day

Best way to create a simple python web service

Raw CGI is kind of a pain, Django is kind of heavyweight. There are a number of simpler, lighter frameworks about, e.g. CherryPy. It's worth looking around a bit.

Writing a Python list of lists to a csv file

You could use pandas:

In [1]: import pandas as pd

In [2]: a = [[1.2,'abc',3],[1.2,'werew',4],[1.4,'qew',2]]

In [3]: my_df = pd.DataFrame(a)

In [4]: my_df.to_csv('my_csv.csv', index=False, header=False)

initialize a numpy array

Introduced in numpy 1.8:

numpy.full

Return a new array of given shape and type, filled with fill_value.

Examples:

>>> import numpy as np
>>> np.full((2, 2), np.inf)
array([[ inf,  inf],
       [ inf,  inf]])
>>> np.full((2, 2), 10)
array([[10, 10],
       [10, 10]])

Tests not running in Test Explorer

In my case it worked to update the MSTest nuget packages. Could reproduce this problem even on blank MSTest project and updating the packages worked.

How large should my recv buffer be when calling recv in the socket library

For streaming protocols such as TCP, you can pretty much set your buffer to any size. That said, common values that are powers of 2 such as 4096 or 8192 are recommended.

If there is more data then what your buffer, it will simply be saved in the kernel for your next call to recv.

Yes, you can keep growing your buffer. You can do a recv into the middle of the buffer starting at offset idx, you would do:

recv(socket, recv_buffer + idx, recv_buffer_size - idx, 0);

Cannot find the object because it does not exist or you do not have permissions. Error in SQL Server

Does the user you're executing this script under even see that table??

select top 1 * from products

Do you get any output for this??

If yes: does this user have the permission to modify the table, i.e. execute DDL scripts like ALTER TABLE etc.? Typically, regular users don't have this elevated permissions.

How to get the current loop index when using Iterator?

Use an int and increment it within your loop.

How to search in an array with preg_match?

Use preg_grep

$array = preg_grep(
    '/(my\n+string\n+)/i',
    array( 'file' , 'my string  => name', 'this')
);

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

To be highly positive you work with the actual email body (yet, still with the possibility you're not parsing the right part), you have to skip attachments, and focus on the plain or html part (depending on your needs) for further processing.

As the before-mentioned attachments can and very often are of text/plain or text/html part, this non-bullet-proof sample skips those by checking the content-disposition header:

b = email.message_from_string(a)
body = ""

if b.is_multipart():
    for part in b.walk():
        ctype = part.get_content_type()
        cdispo = str(part.get('Content-Disposition'))

        # skip any text/plain (txt) attachments
        if ctype == 'text/plain' and 'attachment' not in cdispo:
            body = part.get_payload(decode=True)  # decode
            break
# not multipart - i.e. plain text, no attachments, keeping fingers crossed
else:
    body = b.get_payload(decode=True)

BTW, walk() iterates marvelously on mime parts, and get_payload(decode=True) does the dirty work on decoding base64 etc. for you.

Some background - as I implied, the wonderful world of MIME emails presents a lot of pitfalls of "wrongly" finding the message body. In the simplest case it's in the sole "text/plain" part and get_payload() is very tempting, but we don't live in a simple world - it's often surrounded in multipart/alternative, related, mixed etc. content. Wikipedia describes it tightly - MIME, but considering all these cases below are valid - and common - one has to consider safety nets all around:

Very common - pretty much what you get in normal editor (Gmail,Outlook) sending formatted text with an attachment:

multipart/mixed
 |
 +- multipart/related
 |   |
 |   +- multipart/alternative
 |   |   |
 |   |   +- text/plain
 |   |   +- text/html
 |   |      
 |   +- image/png
 |
 +-- application/msexcel

Relatively simple - just alternative representation:

multipart/alternative
 |
 +- text/plain
 +- text/html

For good or bad, this structure is also valid:

multipart/alternative
 |
 +- text/plain
 +- multipart/related
      |
      +- text/html
      +- image/jpeg

Hope this helps a bit.

P.S. My point is don't approach email lightly - it bites when you least expect it :)

remove script tag from HTML content

function remove_script_tags($html){
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    $script = $dom->getElementsByTagName('script');

    $remove = [];
    foreach($script as $item){
        $remove[] = $item;
    }

    foreach ($remove as $item){
        $item->parentNode->removeChild($item);
    }

    $html = $dom->saveHTML();
    $html = preg_replace('/<!DOCTYPE.*?<html>.*?<body><p>/ims', '', $html);
    $html = str_replace('</p></body></html>', '', $html);
    return $html;
}

Dejan's answer was good, but saveHTML() adds unnecessary doctype and body tags, this should get rid of it. See https://3v4l.org/82FNP

How can I declare a global variable in Angular 2 / Typescript?

IMHO for Angular2 (v2.2.3) the best way is to add services that contain the global variable and inject them into components without the providers tag inside the @Component annotation. By this way you are able to share information between components.

A sample service that owns a global variable:

import { Injectable } from '@angular/core'

@Injectable()
export class SomeSharedService {
  public globalVar = '';
}

A sample component that updates the value of your global variable:

import { SomeSharedService } from '../services/index';

@Component({
  templateUrl: '...'
})
export class UpdatingComponent {

  constructor(private someSharedService: SomeSharedService) { }

  updateValue() {
    this.someSharedService.globalVar = 'updated value';
  }
}

A sample component that reads the value of your global variable:

import { SomeSharedService } from '../services/index';

@Component({
  templateUrl: '...'
})
export class ReadingComponent {

  constructor(private someSharedService: SomeSharedService) { }

  readValue() {
    let valueReadOut = this.someSharedService.globalVar;
    // do something with the value read out
  }
}

Note that providers: [ SomeSharedService ] should not be added to your @Component annotation. By not adding this line injection will always give you the same instance of SomeSharedService. If you add the line a freshly created instance is injected.

Highest Salary in each department

IF you want Department and highest salary, use

SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID

if you want more columns in employee and department, use

select  Department.Name , emp.Name, emp.Salary from Employee emp
inner join (select DeptID, max(salary) [salary] from employee group by DeptID) b
on emp.DeptID = b.DeptID and b.salary = emp.Salary
inner join Department on emp.DeptID = Department.id
order by Department.Name

if use salary in (select max(salary...)) like this, one person have same salary in another department then it will fail.

How to get distinct values from an array of objects in JavaScript?

My below code will show the unique array of ages as well as new array not having duplicate age

var data = [
  {"name": "Joe", "age": 17}, 
  {"name": "Bob", "age": 17}, 
  {"name": "Carl", "age": 35}
];

var unique = [];
var tempArr = [];
data.forEach((value, index) => {
    if (unique.indexOf(value.age) === -1) {
        unique.push(value.age);
    } else {
        tempArr.push(index);    
    }
});
tempArr.reverse();
tempArr.forEach(ele => {
    data.splice(ele, 1);
});
console.log('Unique Ages', unique);
console.log('Unique Array', data);```

IIS7 URL Redirection from root to sub directory

You need to download this from Microsoft: http://www.microsoft.com/en-us/download/details.aspx?id=7435.

The tool is called "Microsoft URL Rewrite Module 2.0 for IIS 7" and is described as follows by Microsoft: "URL Rewrite Module 2.0 provides a rule-based rewriting mechanism for changing requested URL’s before they get processed by web server and for modifying response content before it gets served to HTTP clients"

jQuery add image inside of div tag

Have you tried the following:

$('#theDiv').prepend('<img id="theImg" src="theImg.png" />')

CSS text-align: center; is not centering things

To make a inline-block element align center horizontally in its parent, add text-align:center to its parent.

How can I correctly format currency using jquery?

Expanding upon Melu's answer you can do this to functionalize the code and handle negative amounts.

Sample Output:
$5.23
-$5.23

function formatCurrency(total) {
    var neg = false;
    if(total < 0) {
        neg = true;
        total = Math.abs(total);
    }
    return (neg ? "-$" : '$') + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
}

How to check if field is null or empty in MySQL?

SELECT * FROM ( 
    SELECT  2 AS RTYPE,V.ID AS VTYPE, DATE_FORMAT(ENTDT, ''%d-%m-%Y'')  AS ENTDT,V.NAME AS VOUCHERTYPE,VOUCHERNO,ROUND(IF((DR_CR)>0,(DR_CR),0),0) AS DR ,ROUND(IF((DR_CR)<0,(DR_CR)*-1,0),2) AS CR ,ROUND((dr_cr),2) AS BALAMT, IF(d.narr IS NULL OR d.narr='''',t.narration,d.narr) AS NARRATION 
    FROM trans_m AS t JOIN trans_dtl AS d ON(t.ID=d.TRANSID)
    JOIN acc_head L ON(D.ACC_ID=L.ID) 
    JOIN VOUCHERTYPE_M AS V ON(T.VOUCHERTYPE=V.ID)  
    WHERE T.CMPID=',COMPANYID,' AND  d.ACC_ID=',LEDGERID ,' AND t.entdt>=''',FROMDATE ,''' AND t.entdt<=''',TODATE ,''' ',VTYPE,'
    ORDER BY CAST(ENTDT AS DATE)) AS ta

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

How do you count the elements of an array in java

You can declare an array of booleans with the same length of your array:

true: is used
false: is not used

and change the value of the same cell number to true. Then you can count how many cells are used by using a for loop.

Convert ArrayList to String array in Android

Well in general:

List<String> names = new ArrayList<String>();
names.add("john");
names.add("ann");

String[] namesArr = new String[names.size()];
for (int i = 0; i < names.size(); i++) {
    namesArr[i] = names.get(i);  
}

Or better yet, using built in:

List<String> names = new ArrayList<String>();
String[] namesArr = names.toArray(new String[names.size()]);

check if "it's a number" function in Oracle

Function for mobile number of length 10 digits and starting from 9,8,7 using regexp

create or replace FUNCTION VALIDATE_MOBILE_NUMBER
(   
   "MOBILE_NUMBER" IN varchar2
)
RETURN varchar2
IS
  v_result varchar2(10);

BEGIN
    CASE
    WHEN length(MOBILE_NUMBER) = 10 
    AND MOBILE_NUMBER IS NOT NULL
    AND REGEXP_LIKE(MOBILE_NUMBER, '^[0-9]+$')
    AND MOBILE_NUMBER Like '9%' OR MOBILE_NUMBER Like '8%' OR MOBILE_NUMBER Like '7%'
    then 
    v_result := 'valid';
    RETURN v_result;
      else 
      v_result := 'invalid';
       RETURN v_result;
       end case;
    END;

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

One solution for this can be found with find.

$ mkdir foo bar
$ touch foo/a.txt foo/Music.txt
$ find foo -type f ! -name '*Music*' -exec cp {} bar \;
$ ls bar
a.txt

Find has quite a few options, you can get pretty specific on what you include and exclude.

Edit: Adam in the comments noted that this is recursive. find options mindepth and maxdepth can be useful in controlling this.

Javascript window.open pass values using POST

Thank you php-b-grader. I improved the code, it is not necessary to use window.open(), the target is already specified in the form.

// Create a form
var mapForm = document.createElement("form");
mapForm.target = "_blank";    
mapForm.method = "POST";
mapForm.action = "abmCatalogs.ftl";

// Create an input
var mapInput = document.createElement("input");
mapInput.type = "text";
mapInput.name = "variable";
mapInput.value = "lalalalala";

// Add the input to the form
mapForm.appendChild(mapInput);

// Add the form to dom
document.body.appendChild(mapForm);

// Just submit
mapForm.submit();

for target options --> w3schools - Target

How to encrypt a large file in openssl using public key

Solution for safe and high secured encode anyone file in OpenSSL and command-line:

You should have ready some X.509 certificate for encrypt files in PEM format.

Encrypt file:

openssl smime -encrypt -binary -aes-256-cbc -in plainfile.zip -out encrypted.zip.enc -outform DER yourSslCertificate.pem

What is what:

  • smime - ssl command for S/MIME utility (smime(1))
  • -encrypt - chosen method for file process
  • -binary - use safe file process. Normally the input message is converted to "canonical" format as required by the S/MIME specification, this switch disable it. It is necessary for all binary files (like a images, sounds, ZIP archives).
  • -aes-256-cbc - chosen cipher AES in 256 bit for encryption (strong). If not specified 40 bit RC2 is used (very weak). (Supported ciphers)
  • -in plainfile.zip - input file name
  • -out encrypted.zip.enc - output file name
  • -outform DER - encode output file as binary. If is not specified, file is encoded by base64 and file size will be increased by 30%.
  • yourSslCertificate.pem - file name of your certificate's. That should be in PEM format.

That command can very effectively a strongly encrypt big files regardless of its format.
Known issue: Something wrong happens when you try encrypt huge file (>600MB). No error thrown, but encrypted file will be corrupted. Always verify each file! (or use PGP - that has bigger support for files encryption with public key)

Decrypt file:

openssl smime -decrypt -binary -in encrypted.zip.enc -inform DER -out decrypted.zip -inkey private.key -passin pass:your_password

What is what:

  • -inform DER - same as -outform above
  • -inkey private.key - file name of your private key. That should be in PEM format and can be encrypted by password.
  • -passin pass:your_password - your password for private key encrypt. (passphrase arguments)

make a phone call click on a button

I hope, this short code is useful for You,
   ## Java Code ##
 startActivity(new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+txtPhn.getText().toString())));



----------------------------------------------------------------------


Please check Manifest File,(for Uses permission)
## Manifest.xml ##
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dbm.pkg"
    android:versionCode="1"
    android:versionName="1.0">

    <!-- NOTE! Your uses-permission must be outside the "application" tag
               but within the "manifest" tag. -->
## uses-permission for Making Call ##
    <uses-permission android:name="android.permission.CALL_PHONE" />

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name">

        <!-- Insert your other stuff here -->

    </application>

    <uses-sdk android:minSdkVersion="9" />
</manifest> 

How (and why) to use display: table-cell (CSS)

It's even easier to use parent > child selector relationship so the inner div do not need to have their css classes to be defined explicitly:

_x000D_
_x000D_
.display-table {_x000D_
    display: table; _x000D_
}_x000D_
.display-table > div { _x000D_
    display: table-row; _x000D_
}_x000D_
.display-table > div > div { _x000D_
    display: table-cell;_x000D_
    padding: 5px;_x000D_
}
_x000D_
<div class="display-table">_x000D_
    <div>_x000D_
        <div>0, 0</div>_x000D_
        <div>0, 1</div>_x000D_
    </div>_x000D_
    <div>_x000D_
        <div>1, 0</div>_x000D_
        <div>1, 1</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is there a function to split a string in PL/SQL?

You could use a combination of SUBSTR and INSTR as follows :

Example string : field = 'DE124028#@$1048708#@$000#@$536967136#@$'

The seperator being #@$.

To get the '1048708' for example :

If the field is of fixed length ( 7 here ) :

substr(field,instr(field,'#@$',1,1)+3,7)

If the field is of variable length :

substr(field,instr(field,'#@$',1,1)+3,instr(field,'#@$',1,2) - (instr(field,'#@$',1,1)+3)) 

You should probably look into SUBSTR and INSTR functions for more flexibility.

Python: Importing urllib.quote

Use six:

from six.moves.urllib.parse import quote

six will simplify compatibility problems between Python 2 and Python 3, such as different import paths.

Start service in Android

Probably you don't have the service in your manifest, or it does not have an <intent-filter> that matches your action. Examining LogCat (via adb logcat, DDMS, or the DDMS perspective in Eclipse) should turn up some warnings that may help.

More likely, you should start the service via:

startService(new Intent(this, UpdaterServiceManager.class));

Make a link use POST instead of GET

Check this it will help you

$().redirect('test.php', {'a': 'value1', 'b': 'value2'});

How do I implement __getattribute__ without an infinite recursion error?

Python language reference:

In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.__getattribute__(self, name).

Meaning:

def __getattribute__(self,name):
    ...
        return self.__dict__[name]

You're calling for an attribute called __dict__. Because it's an attribute, __getattribute__ gets called in search for __dict__ which calls __getattribute__ which calls ... yada yada yada

return  object.__getattribute__(self, name)

Using the base classes __getattribute__ helps finding the real attribute.

Sorting HashMap by values

You don't, basically. A HashMap is fundamentally unordered. Any patterns you might see in the ordering should not be relied on.

There are sorted maps such as TreeMap, but they traditionally sort by key rather than value. It's relatively unusual to sort by value - especially as multiple keys can have the same value.

Can you give more context for what you're trying to do? If you're really only storing numbers (as strings) for the keys, perhaps a SortedSet such as TreeSet would work for you?

Alternatively, you could store two separate collections encapsulated in a single class to update both at the same time?

Convert JSON string to array of JSON objects in Javascript

Using jQuery:

var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');

jsonObj is your JSON object.

Excel: Can I create a Conditional Formula based on the Color of a Cell?

Unfortunately, there is not a direct way to do this with a single formula. However, there is a fairly simple workaround that exists.

On the Excel Ribbon, go to "Formulas" and click on "Name Manager". Select "New" and then enter "CellColor" as the "Name". Jump down to the "Refers to" part and enter the following:

=GET.CELL(63,OFFSET(INDIRECT("RC",FALSE),1,1))

Hit OK then close the "Name Manager" window.

Now, in cell A1 enter the following:

=IF(CellColor=3,"FQS",IF(CellColor=6,"SM",""))

This will return FQS for red and SM for yellow. For any other color the cell will remain blank.

***If the value in A1 doesn't update, hit 'F9' on your keyboard to force Excel to update the calculations at any point (or if the color in B2 ever changes).

Below is a reference for a list of cell fill colors (there are 56 available) if you ever want to expand things: http://www.smixe.com/excel-color-pallette.html

Cheers.

::Edit::

The formula used in Name Manager can be further simplified if it helps your understanding of how it works (the version that I included above is a lot more flexible and is easier to use in checking multiple cell references when copied around as it uses its own cell address as a reference point instead of specifically targeting cell B2).

Either way, if you'd like to simplify things, you can use this formula in Name Manager instead:

=GET.CELL(63,Sheet1!B2)

Calling functions in a DLL from C++

The following are the 5 steps required:

  1. declare the function pointer
  2. Load the library
  3. Get the procedure address
  4. assign it to function pointer
  5. call the function using function pointer

You can find the step by step VC++ IDE screen shot at http://www.softwareandfinance.com/Visual_CPP/DLLDynamicBinding.html

Here is the code snippet:

int main()
{
/***
__declspec(dllimport) bool GetWelcomeMessage(char *buf, int len); // used for static binding
 ***/
    typedef bool (*GW)(char *buf, int len);

    HMODULE hModule = LoadLibrary(TEXT("TestServer.DLL"));
    GW GetWelcomeMessage = (GW) GetProcAddress(hModule, "GetWelcomeMessage");

    char buf[128];
    if(GetWelcomeMessage(buf, 128) == true)
        std::cout << buf;
        return 0;
}

What is a .pid file and what does it contain?

The pid files contains the process id (a number) of a given program. For example, Apache HTTPD may write its main process number to a pid file - which is a regular text file, nothing more than that - and later use the information there contained to stop itself. You can also use that information to kill the process yourself, using cat filename.pid | xargs kill

Create component to specific module with Angular-CLI

I didn't find an answer that showed how to use the cli to generate a component inside a top level module folder, and also have the component automatically added the the module's declaration collection.

To create the module run this:

ng g module foo

To create the component inside the foo module folder and have it added to the foo.module.ts's declaration collection run this:

ng g component foo/fooList --module=foo.module.ts

And the cli will scaffold out the module and component like this:

enter image description here

--EDIT the new version of the angular cli behaves differently. 1.5.5 doesn't want a module file name so the command with v1.5.5 should be

ng g component foo/fooList --module=foo

Plugin with id 'com.google.gms.google-services' not found

I'm not sure about you, but I spent about 30 minutes troubleshooting the same issue here, until I realized that the line for app/build.gradle is:

apply plugin: 'com.google.gms.google-services'

and not:

apply plugin: 'com.google.gms:google-services'

Eg: I had copied that line from a tutorial, but when specifying the apply plugin namespace, no colon (:) is required. It's, in fact, a dot. (.).

Hey... it's easy to miss.

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

I had to disable explicit_defaults_for_timestamp from my.cnf.

Can comments be used in JSON?

DISCLAIMER: YOUR WARRANTY IS VOID

As has been pointed out, this hack takes advantage of the implementation of the spec. Not all JSON parsers will understand this sort of JSON. Streaming parsers in particular will choke.

It's an interesting curiosity, but you should really not be using it for anything at all. Below is the original answer.


I've found a little hack that allows you to place comments in a JSON file that will not affect the parsing, or alter the data being represented in any way.

It appears that when declaring an object literal you can specify two values with the same key, and the last one takes precedence. Believe it or not, it turns out that JSON parsers work the same way. So we can use this to create comments in the source JSON that will not be present in a parsed object representation.

({a: 1, a: 2});
// => Object {a: 2}
Object.keys(JSON.parse('{"a": 1, "a": 2}')).length; 
// => 1

If we apply this technique, your commented JSON file might look like this:

{
  "api_host" : "The hostname of your API server. You may also specify the port.",
  "api_host" : "hodorhodor.com",

  "retry_interval" : "The interval in seconds between retrying failed API calls",
  "retry_interval" : 10,

  "auth_token" : "The authentication token. It is available in your developer dashboard under 'Settings'",
  "auth_token" : "5ad0eb93697215bc0d48a7b69aa6fb8b",

  "favorite_numbers": "An array containing my all-time favorite numbers",
  "favorite_numbers": [19, 13, 53]
}

The above code is valid JSON. If you parse it, you'll get an object like this:

{
    "api_host": "hodorhodor.com",
    "retry_interval": 10,
    "auth_token": "5ad0eb93697215bc0d48a7b69aa6fb8b",
    "favorite_numbers": [19,13,53]
}

Which means there is no trace of the comments, and they won't have weird side-effects.

Happy hacking!

Find element in List<> that contains a value

hi body very late but i am writing

if(mylist.contains(value)){}

Convert a dta file to csv without Stata software

For those who have Stata (even though the asker does not) you can use this:

outsheet produces a tab-delimited file so you need to specify the comma option like below

outsheet [varlist] using file.csv , comma

also, if you want to remove labels (which are included by default

outsheet [varlist] using file.csv, comma nolabel

hat tip to:

http://www.ats.ucla.edu/stat/stata/faq/outsheet.htm

Ajax Upload image

Here is simple way using HTML5 and jQuery:

1) include two JS file

<script src="jslibs/jquery.js" type="text/javascript"></script>
<script src="jslibs/ajaxupload-min.js" type="text/javascript"></script>

2) include CSS to have cool buttons

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

3) create DIV or SPAN

<div class="demo" > </div>

4) write this code in your HTML page

$('.demo').ajaxupload({
    url:'upload.php'
});

5) create you upload.php file to have PHP code to upload data.

You can download required JS file from here Here is Example

Its too cool and too fast And easy too! :)

Using SUMIFS with multiple AND OR conditions

With the following, it is easy to link the Cell address...

=SUM(SUMIFS(FAGLL03!$I$4:$I$1048576,FAGLL03!$A$4:$A$1048576,">="&INDIRECT("A"&ROW()),FAGLL03!$A$4:$A$1048576,"<="&INDIRECT("B"&ROW()),FAGLL03!$Q$4:$Q$1048576,E$2))

Can use address / substitute / Column functions as required to use Cell addresses in full DYNAMIC.

How to avoid reverse engineering of an APK file?

 1. How can I completely avoid reverse engineering of an Android APK? Is this possible?

That is impossible

 2. How can I protect all the app's resources, assets and source code so that hackers can't hack the APK file in any way?

Developers can take steps such as using tools like ProGuard to obfuscate their code, but up until now, it has been quite difficult to completely prevent someone from decompiling an app.

It's a really great tool and can increase the difficulty of 'reversing' your code whilst shrinking your code's footprint.

Integrated ProGuard support: ProGuard is now packaged with the SDK Tools. Developers can now obfuscate their code as an integrated part of a release build.

 3. Is there a way to make hacking more tough or even impossible? What more can I do to protect the source code in my APK file?

While researching, I came to know about HoseDex2Jar. This tool will protect your code from decompiling, but it seems not to be possible to protect your code completely.

Some of helpful links, you can refer to them.

Add a Progress Bar in WebView

I have added few lines in your code and now its working fine with progress bar.

        getWindow().requestFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.main );
        // Makes Progress bar Visible
        getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);

        webview = (WebView) findViewById(R.id.webview);
        webview.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress)   
            {
                //Make the bar disappear after URL is loaded, and changes string to Loading...
                setTitle("Loading...");
                setProgress(progress * 100); //Make the bar disappear after URL is loaded
     
                // Return the app name after finish loading
                if(progress == 100)
                   setTitle(R.string.app_name);
                }
            });
        webview.setWebViewClient(new HelloWebViewClient());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl("http://www.google.com");

Wget output document and headers to STDOUT

This will not work:

wget -q -S -O - google.com 1>wget.txt 2>&1

since redirects are evaluated right to left, this sends html to wget.txt and the header to STDOUT:

wget -q -S -O - google.com 2>&1 1>wget.txt

Test if string is URL encoded in PHP

private static boolean isEncodedText(String val, String... encoding) throws UnsupportedEncodingException { String decodedText = URLDecoder.decode(val, TransformFetchConstants.DEFAULT_CHARSET);

    if(encoding != null && encoding.length > 0){
        decodedText = URLDecoder.decode(val, encoding[0]);
    }

    String encodedText =  URLEncoder.encode(decodedText);

    return encodedText.equalsIgnoreCase(val) || !decodedText.equalsIgnoreCase(val);

}

How to find an available port?

This works for me on Java 6

    ServerSocket serverSocket = new ServerSocket(0);
    System.out.println("listening on port " + serverSocket.getLocalPort());

How can I set the color of a selected row in DataGrid

As an extention to @Seb Kade's answer, you can fully control the colours of the selected and unselected rows using the following Style:

<Style TargetType="{x:Type DataGridRow}">
    <Style.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black" />
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="Black" />
    </Style.Resources>
</Style>

You can of course enter whichever colours you prefer. This Style will also work for other collection items such as ListBoxItems (if you replace TargetType="{x:Type DataGridRow}" with TargetType="{x:Type ListBoxItem}" for instance).

Return index of greatest value in an array

If you create a copy of the array and sort it descending, the first element of the copy will be the largest. Than you can find its index in the original array.

var sorted = [...arr].sort((a,b) => b - a)
arr.indexOf(sorted[0])

Time complexity is O(n) for the copy, O(n*log(n)) for sorting and O(n) for the indexOf.

If you need to do it faster, Ry's answer is O(n).

Powershell script to locate specific file/file name?

From a powershell prompt, use the gci cmdlet (alias for Get-ChildItem) and -filter option:

gci -recurse -filter "hosts"

This will return an exact match to filename "hosts".


SteveMustafa points out with current versions of powershell you can use the -File switch to give the following to recursively search for only files named "hosts" (and not directories or other miscellaneous file-system entities):

gci -recurse -filter "hosts" -File 


The commands may print many red error messages like "Access to the path 'C:\Windows\Prefetch' is denied.".

If you want to avoid the error messages then set the -ErrorAction to be silent.

gci -recurse -filter "hosts" -File -ErrorAction SilentlyContinue


An additional helper is that you can set the root to search from using -Path. The resulting command to search explicitly search from, for example, the root of the C drive would be

gci -Recurse -Filter "hosts" -File -ErrorAction SilentlyContinue -Path "C:\"

Android WebView not loading URL

Use the following things on your webview

webview.setWebChromeClient(new WebChromeClient());

then implement the required methods for WebChromeClient class.

How do you close/hide the Android soft keyboard using Java?

I created a layout partially from xml and partially from a custom layout engine, which is all handled in-code. The only thing that worked for me was to keep track of whether or not the keyboard was open, and use the keyboard toggle method as follows:

public class MyActivity extends Activity
{
    /** This maintains true if the keyboard is open. Otherwise, it is false. */
    private boolean isKeyboardOpen = false;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater;
        inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView = inflater.inflate(context.getResources().getIdentifier("main", "layout", getPackageName()), null);

        setContentView(contentView);
        contentView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() 
        {
            public void onGlobalLayout() 
            {
                Rect r = new Rect();
                contentView.getWindowVisibleDisplayFrame(r);
                int heightDiff = contentView.getRootView().getHeight() - (r.bottom - r.top);
                if (heightDiff > 100) 
                    isKeyboardVisible = true;
                else
                    isKeyboardVisible = false;
             });
         }
    }

    public void closeKeyboardIfOpen()
    {
        InputMethodManager imm;
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (isKeyboardVisible)
            imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    }   
}

How to create own dynamic type or dynamic object in C#?

dynamic MyDynamic = new System.Dynamic.ExpandoObject();
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.Number = 12;
MyDynamic.MyMethod = new Func<int>(() => 
{ 
    return 55; 
});
Console.WriteLine(MyDynamic.MyMethod());

Read more about ExpandoObject class and for more samples: Represents an object whose members can be dynamically added and removed at run time.

Select All Rows Using Entity Framework

Entity Framework has one beautiful thing for it, like :

var users = context.Users; 

This will select all rows in Table User, then you can use your .ToList() etc.


For newbies to Entity Framework, it is like :

PortalEntities context = new PortalEntities();
var users = context.Users;

This will select all rows in Table User

How to uninstall Golang?

I'm using Ubuntu. I spent a whole morning fixing this, tried all different solutions, when I type go version, it's still there, really annoying... Finally this worked for me, hope this will help!

sudo apt-get remove golang-go
sudo apt-get remove --auto-remove golang-go

Inserting a value into all possible locations in a list

Simplest is use list[i:i]

    a = [1,2, 3, 4]
    a[2:2] = [10]

Print a to check insertion

    print a
    [1, 2, 10, 3, 4]

How to get the current branch name in Git?

As of version 2.22 of git you could just use:

git branch --show-current

As per man page:

Print the name of the current branch. In detached HEAD state, nothing is printed.

How to initialise memory with new operator in C++?

If the memory you are allocating is a class with a constructor that does something useful, the operator new will call that constructor and leave your object initialized.

But if you're allocating a POD or something that doesn't have a constructor that initializes the object's state, then you cannot allocate memory and initialize that memory with operator new in one operation. However, you have several options:

  1. Use a stack variable instead. You can allocate and default-initialize in one step, like this:

     int vals[100] = {0}; // first element is a matter of style
    
  2. use memset(). Note that if the object you are allocating is not a POD, memsetting it is a bad idea. One specific example is if you memset a class that has virtual functions, you will blow away the vtable and leave your object in an unusable state.

  3. Many operating systems have calls that do what you want - allocate on a heap and initialize the data to something. A Windows example would be VirtualAlloc().

  4. This is usually the best option. Avoid having to manage the memory yourself at all. You can use STL containers to do just about anything you would do with raw memory, including allocating and initializing all in one fell swoop:

     std::vector<int> myInts(100, 0); // creates a vector of 100 ints, all set to zero
    

How is Docker different from a virtual machine?

There are many answers which explain more detailed on the differences, but here is my very brief explanation.

One important difference is that VMs use a separate kernel to run the OS. That's the reason it is heavy and takes time to boot, consuming more system resources.

In Docker, the containers share the kernel with the host; hence it is lightweight and can start and stop quickly.

In Virtualization, the resources are allocated in the beginning of set up and hence the resources are not fully utilized when the virtual machine is idle during many of the times. In Docker, the containers are not allocated with fixed amount of hardware resources and is free to use the resources depending on the requirements and hence it is highly scalable.

Docker uses UNION File system .. Docker uses a copy-on-write technology to reduce the memory space consumed by containers. Read more here

converting a base 64 string to an image and saving it

Here is what I ended up going with.

    private void SaveByteArrayAsImage(string fullOutputPath, string base64String)
    {
        byte[] bytes = Convert.FromBase64String(base64String);

        Image image;
        using (MemoryStream ms = new MemoryStream(bytes))
        {
            image = Image.FromStream(ms);
        }

        image.Save(fullOutputPath, System.Drawing.Imaging.ImageFormat.Png);
    }

How to append to New Line in Node.js

It looks like you're running this on Windows (given your H://log.txt file path).

Try using \r\n instead of just \n.

Honestly, \n is fine; you're probably viewing the log file in notepad or something else that doesn't render non-Windows newlines. Try opening it in a different viewer/editor (e.g. Wordpad).

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

You could also group functions in one main file together with the main function looking like this:

function [varargout] = main( subfun, varargin )
[varargout{1:nargout}] = feval( subfun, varargin{:} ); 

% paste your subfunctions below ....
function str=subfun1
str='hello'

Then calling subfun1 would look like this: str=main('subfun1')

cannot convert data (type interface {}) to type string: need type assertion

Type Assertion

This is known as type assertion in golang, and it is a common practice.

Here is the explanation from a tour of go:

A type assertion provides access to an interface value's underlying concrete value.

t := i.(T)

This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.

If i does not hold a T, the statement will trigger a panic.

To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.

t, ok := i.(T)

If i holds a T, then t will be the underlying value and ok will be true.

If not, ok will be false and t will be the zero value of type T, and no panic occurs.

NOTE: value i should be interface type.

Pitfalls

Even if i is an interface type, []i is not interface type. As a result, in order to convert []i to its value type, we have to do it individually:

// var items []i
for _, item := range items {
    value, ok := item.(T)
    dosomethingWith(value)
}

Performance

As for performance, it can be slower than direct access to the actual value as show in this stackoverflow answer.

Update Query with INNER JOIN between tables in 2 different databases on 1 server

UPDATE table1 a
 inner join  table2 b on (a.kol1=a.b.kol1...)
SET a.kol1=b.kol1
WHERE 
a.kol1='' ...

for me until the syntax worked -MySQL

returning a Void object

It is possible to create instances of Void if you change the security manager, so something like this:

static Void getVoid() throws SecurityException, InstantiationException,
        IllegalAccessException, InvocationTargetException {
    class BadSecurityManager extends SecurityManager {
    
        @Override
        public void checkPermission(Permission perm) { }
    
        @Override
        public void checkPackageAccess(String pkg) { }

    }
    System.setSecurityManager(badManager = new BadSecurityManager());
    Constructor<?> constructor = Void.class.getDeclaredConstructors()[0];
    if(!constructor.isAccessible()) {
        constructor.setAccessible(true);
    }
    return (Void) constructor.newInstance();
}

Obviously this is not all that practical or safe; however, it will return an instance of Void if you are able to change the security manager.

Can't find android device using "adb devices" command

I was having this problem. It turns out my fix was to change the USB cable I was connecting with. I switched back to using the cable that came with the phone and it worked.

Using Samsung Galaxy Player and Samsung micro USB.

Yes. This is incredibly dumb.

Invalid hook call. Hooks can only be called inside of the body of a function component

For me , the error was calling the function useState outside the function default exported

Creating PHP class instance with a string

have a look at example 3 from http://www.php.net/manual/en/language.oop5.basic.php

$className = 'Foo';
$instance = new $className(); // Foo()

Jackson - Deserialize using generic class

Example of not very good, but simple decision (not only for Jackson, also for Spring RestTemplate, etc.):

Set<MyClass> res = new HashSet<>();
objectMapper.readValue(json, res.getClass());

how to specify local modules as npm package dependencies

I couldn't find a neat way in the end so I went for create a directory called local_modules and then added this bashscript to the package.json in scripts->preinstall

#!/bin/sh
for i in $(find ./local_modules -type d -maxdepth 1) ; do
    packageJson="${i}/package.json"
    if [ -f "${packageJson}" ]; then
        echo "installing ${i}..."
        npm install "${i}"
    fi
done

Java String - See if a string contains only numbers and not letters

This code is already written. If you don't mind the (extremely) minor performance hit--which is probably no worse than doing a regex match--use Integer.parseInt() or Double.parseDouble(). That'll tell you right away if a String is only numbers (or is a number, as appropriate). If you need to handle longer strings of numbers, both BigInteger and BigDecimal sport constructors that accept Strings. Any of these will throw a NumberFormatException if you try to pass it a non-number (integral or decimal, based on the one you choose, of course). Alternately, depending on your requirements, just iterate the characters in the String and check Character.isDigit() and/or Character.isLetter().

How to set a JVM TimeZone Properly

You can also set the default time zone in your code by using following code.

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

To Yours

 TimeZone.setDefault(TimeZone.getTimeZone("Europe/Sofia"));

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

Npm Error - No matching version found for

Try removing package-lock.json file first

CSS transition shorthand with multiple properties?

By having the .5s delay on transitioning the opacity property, the element will be completely transparent (and thus invisible) the whole time its height is transitioning. So the only thing you will actually see is the opacity changing. So you will get the same effect as leaving the height property out of the transition :

"transition: opacity .5s .5s;"

Is that what you're wanting? If not, and you're wanting to see the height transition, you can't have an opacity of zero during the whole time that it's transitioning.

Launch custom android application from android browser

Please see my comment here: Make a link in the Android browser start up my app?

We strongly discourage people from using their own schemes, unless they are defining a new world-wide internet scheme.

Bash: Echoing a echo command with a variable in bash

The immediate problem is you have is with quoting: by using double quotes ("..."), your variable references are instantly expanded, which is probably not what you want.

Use single quotes instead - strings inside single quotes are not expanded or interpreted in any way by the shell.

(If you want selective expansion inside a string - i.e., expand some variable references, but not others - do use double quotes, but prefix the $ of references you do not want expanded with \; e.g., \$var).

However, you're better off using a single here-doc[ument], which allows you to create multi-line stdin input on the spot, bracketed by two instances of a self-chosen delimiter, the opening one prefixed by <<, and the closing one on a line by itself - starting at the very first column; search for Here Documents in man bash or at http://www.gnu.org/software/bash/manual/html_node/Redirections.html.

If you quote the here-doc delimiter (EOF in the code below), variable references are also not expanded. As @chepner points out, you're free to choose the method of quoting in this case: enclose the delimiter in single quotes or double quotes, or even simply arbitrarily escape one character in the delimiter with \:

echo "creating new script file."

cat <<'EOF'  > "$servfile"
#!/bin/bash
read -p "Please enter a service: " ser
servicetest=`getsebool -a | grep ${ser}` 
if [ $servicetest > /dev/null ]; then 
  echo "we are now going to work with ${ser}"
else
  exit 1
fi
EOF

As @BruceK notes, you can prefix your here-doc delimiter with - (applied to this example: <<-"EOF") in order to have leading tabs stripped, allowing for indentation that makes the actual content of the here-doc easier to discern. Note, however, that this only works with actual tab characters, not leading spaces.

Employing this technique combined with the afterthoughts regarding the script's content below, we get (again, note that actual tab chars. must be used to lead each here-doc content line for them to get stripped):

cat <<-'EOF' > "$servfile"
    #!/bin/bash
    read -p "Please enter a service name: " ser
    if [[ -n $(getsebool -a | grep "${ser}") ]]; then 
      echo "We are now going to work with ${ser}."
    else
      exit 1
    fi
EOF

Finally, note that in bash even normal single- or double-quoted strings can span multiple lines, but you won't get the benefits of tab-stripping or line-block scoping, as everything inside the quotes becomes part of the string.

Thus, note how in the following #!/bin/bash has to follow the opening ' immediately in order to become the first line of output:

echo '#!/bin/bash
read -p "Please enter a service: " ser
servicetest=$(getsebool -a | grep "${ser}")
if [[ -n $servicetest ]]; then 
  echo "we are now going to work with ${ser}"
else
  exit 1
fi' > "$servfile"

Afterthoughts regarding the contents of your script:

  • The syntax $(...) is preferred over `...` for command substitution nowadays.
  • You should double-quote ${ser} in the grep command, as the command will likely break if the value contains embedded spaces (alternatively, make sure that the valued read contains no spaces or other shell metacharacters).
  • Use [[ -n $servicetest ]] to test whether $servicetest is empty (or perform the command substitution directly inside the conditional) - [[ ... ]] - the preferred form in bash - protects you from breaking the conditional if the $servicetest happens to have embedded spaces; there's NEVER a need to suppress stdout output inside a conditional (whether [ ... ] or [[ ... ]], as no stdout output is passed through; thus, the > /dev/null is redundant (that said, with a command substitution inside a conditional, stderr output IS passed through).

Using parameters in batch files at Windows command line

Batch Files automatically pass the text after the program so long as their are variables to assign them to. They are passed in order they are sent; e.g. %1 will be the first string sent after the program is called, etc.

If you have Hello.bat and the contents are:

@echo off
echo.Hello, %1 thanks for running this batch file (%2)
pause

and you invoke the batch in command via

hello.bat APerson241 %date%

you should receive this message back:

Hello, APerson241 thanks for running this batch file (01/11/2013)

How to build x86 and/or x64 on Windows from command line with CMAKE?

try use CMAKE_GENERATOR_PLATFORM

e.g.

// x86
cmake -DCMAKE_GENERATOR_PLATFORM=x86 . 

// x64
cmake -DCMAKE_GENERATOR_PLATFORM=x64 . 

Android fastboot waiting for devices

The shortest answer is first run the fastboot command (in my ubuntu case i.e. ./fastboot-linux oem unlock) (here i'm using ubuntu 12.04 and rooting nexus4) then power on your device in fastboot mode (in nexus 4 by pressing vol-down-key and power button)

How to insert &nbsp; in XSLT

Use the entity code &#160; instead.

&nbsp; is a HTML "character entity reference". There is no named entity for non-breaking space in XML, so you use the code &#160;.

Wikipedia includes a list of XML and HTML entities, and you can see that there are only 5 "predefined entities" in XML, but HTML has over 200. I'll also point over to Creating a space (&nbsp;) in XSL which has excellent answers.

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

In case of a JSP/Servlet webapplication, you just need to drop 3rd party JAR files in /WEB-INF/lib folder. If the project is a Dynamic Web Project, then Eclipse will automatically take care about setting the buildpath right as well. You do not need to fiddle with Eclipse buildpath. Don't forget to undo it all.

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

Calculating frames per second in a game

store a start time and increment your framecounter once per loop? every few seconds you could just print framecount/(Now - starttime) and then reinitialize them.

edit: oops. double-ninja'ed

PHP split alternative?

If you want to split a string into words, you can use explode() or str_word_count().

Press enter in textbox to and execute button command

Since everybody covered the KeyDown answers, how about using the IsDefault on the button?

You can read this tip for a quick howto and what it does: http://www.codeproject.com/Tips/665886/Button-Tip-IsDefault-IsCancel-and-other-usability

Here's an example from the article linked:

<Button IsDefault = "true" 
        Click     = "SaveClicked"
        Content   = "Save"  ... />
'''

Hexadecimal string to byte array in C

    In main()
    {
printf("enter string :\n");
    fgets(buf, 200, stdin);
unsigned char str_len = strlen(buf);
k=0;
unsigned char bytearray[100];
     for(j=0;j<str_len-1;j=j+2)
        { bytearray[k++]=converttohex(&buffer[j]);   
                printf(" %02X",bytearray[k-1]);
        }

    }

    Use this 

    int converttohex(char * val)
        {
        unsigned char temp = toupper(*val);
        unsigned char fin=0;
        if(temp>64)
        temp=10+(temp-65);

        else
        temp=temp-48;

        fin=(temp<<4)&0xf0;

        temp = toupper(*(val+1));

            if(temp>64)
            temp=10+(temp-65);

            else
            temp=temp-48;

        fin=fin|(temp & 0x0f);


           return fin;
        }

Determine if variable is defined in Python

'a' in vars() or 'a' in globals()

if you want to be pedantic, you can check the builtins too
'a' in vars(__builtins__)

Redirect from asp.net web api post action

Sure:

public HttpResponseMessage Post()
{
    // ... do the job

    // now redirect
    var response = Request.CreateResponse(HttpStatusCode.Moved);
    response.Headers.Location = new Uri("http://www.abcmvc.com");
    return response;
}

Simple CSS: Text won't center in a button

padding: 0px solves the horizontal centering

whereas,

setting line-height equal to or less than the height of the button solves the vertical alignment.

How to find which version of TensorFlow is installed in my system?

I installed the Tensorflow 0.12rc from source, and the following command gives me the version info:

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

The following figure shows the output:

enter image description here

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

How to make an embedded video not autoplay

I had the same problem and came across this post. Nothing worked. After randomly playing around, I found that <embed ........ play="false"> stopped it from playing automatically. I now have the problem that I can't get a controller to appear, so can't start the movie! :S

Hash Map in Python

Python dictionary is a built-in type that supports key-value pairs.

streetno = {"1": "Sachin Tendulkar", "2": "Dravid", "3": "Sehwag", "4": "Laxman", "5": "Kohli"}

as well as using the dict keyword:

streetno = dict({"1": "Sachin Tendulkar", "2": "Dravid"}) 

or:

streetno = {}
streetno["1"] = "Sachin Tendulkar" 

Change the background color of a row in a JTable

This is basically as simple as repainting the table. I haven't found a way to selectively repaint just one row/column/cell however.

In this example, clicking on the button changes the background color for a row and then calls repaint.

public class TableTest {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final Color[] rowColors = new Color[] {
                randomColor(), randomColor(), randomColor()
        };
        final JTable table = new JTable(3, 3);
        table.setDefaultRenderer(Object.class, new TableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table,
                    Object value, boolean isSelected, boolean hasFocus,
                    int row, int column) {
                JPanel pane = new JPanel();
                pane.setBackground(rowColors[row]);
                return pane;
            }
        });
        frame.setLayout(new BorderLayout());

        JButton btn = new JButton("Change row2's color");
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                rowColors[1] = randomColor();
                table.repaint();
            }
        });

        frame.add(table, BorderLayout.NORTH);
        frame.add(btn, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }

    private static Color randomColor() {
        Random rnd = new Random();
        return new Color(rnd.nextInt(256),
                rnd.nextInt(256), rnd.nextInt(256));
    }
}

How to hide the soft keyboard from inside a fragment?

Use this static method, from anywhere (Activity / Fragment) you like.

public static void hideKeyboard(Activity activity) {
    try{
        InputMethodManager inputManager = (InputMethodManager) activity
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        View currentFocusedView = activity.getCurrentFocus();
        if (currentFocusedView != null) {
            inputManager.hideSoftInputFromWindow(currentFocusedView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}

If you want to use for fragment just call hideKeyboard(((Activity) getActivity())).

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

I came here with the same Error, though one with a different origin.

It is caused by unsupported float index in 1.12.0 and newer numpy versions even if the code should be considered as valid.

An int type is expected, not a np.float64

Solution: Try to install numpy 1.11.0

sudo pip install -U numpy==1.11.0.

Vertically aligning a checkbox

Its not a perfect solution, but a good workaround.

You need to assign your elements to behave as table with display: table-cell

Solution: Demo

HTML:

<ul>        
    <li>
        <div><input type="checkbox" value="1" name="test[]" id="myid1"></div>
        <div><label for="myid1">label1</label></div>
    </li>
    <li>
        <div><input type="checkbox" value="2" name="test[]" id="myid2"></div>
        <div><label for="myid2">label2</label></div>
    </li>
</ul>

CSS:

li div { display: table-cell; vertical-align: middle; }

JPA: unidirectional many-to-one and cascading delete

Relationships in JPA are always unidirectional, unless you associate the parent with the child in both directions. Cascading REMOVE operations from the parent to the child will require a relation from the parent to the child (not just the opposite).

You'll therefore need to do this:

  • Either, change the unidirectional @ManyToOne relationship to a bi-directional @ManyToOne, or a unidirectional @OneToMany. You can then cascade REMOVE operations so that EntityManager.remove will remove the parent and the children. You can also specify orphanRemoval as true, to delete any orphaned children when the child entity in the parent collection is set to null, i.e. remove the child when it is not present in any parent's collection.
  • Or, specify the foreign key constraint in the child table as ON DELETE CASCADE. You'll need to invoke EntityManager.clear() after calling EntityManager.remove(parent) as the persistence context needs to be refreshed - the child entities are not supposed to exist in the persistence context after they've been deleted in the database.

Confusion: @NotNull vs. @Column(nullable = false) with JPA and Hibernate

The JPA @Column Annotation

The nullable attribute of the @Column annotation has two purposes:

  • it's used by the schema generation tool
  • it's used by Hibernate during flushing the Persistence Context

Schema Generation Tool

The HBM2DDL schema generation tool translates the @Column(nullable = false) entity attribute to a NOT NULL constraint for the associated table column when generating the CREATE TABLE statement.

As I explained in the Hibernate User Guide, it's better to use a tool like Flyway instead of relying on the HBM2DDL mechanism for generating the database schema.

Persistence Context Flush

When flushing the Persistence Context, Hibernate ORM also uses the @Column(nullable = false) entity attribute:

new Nullability( session ).checkNullability( values, persister, true );

If the validation fails, Hibernate will throw a PropertyValueException, and prevents the INSERT or UPDATE statement to be executed needesly:

if ( !nullability[i] && value == null ) {
    //check basic level one nullablilty
    throw new PropertyValueException(
            "not-null property references a null or transient value",
            persister.getEntityName(),
            persister.getPropertyNames()[i]
        );    
}

The Bean Validation @NotNull Annotation

The @NotNull annotation is defined by Bean Validation and, just like Hibernate ORM is the most popular JPA implementation, the most popular Bean Validation implementation is the Hibernate Validator framework.

When using Hibernate Validator along with Hibernate ORM, Hibernate Validator will throw a ConstraintViolation when validating the entity.

What is a good game engine that uses Lua?

I can second the previous posters enthusiasm for the Gideros Lua game engine, whilst focusing currently on Mobile (iOS and Android - Windows phone 8 is in the works), desktop support for Mac, PC (possibly Linux) is also planned for the not too distant future.

Google for "Gideros Mobile"

MySQL Where DateTime is greater than today

I guess you looking for CURDATE() or NOW() .

  SELECT name, datum 
  FROM tasks 
  WHERE datum >= CURDATE()

LooK the rsult of NOW and CURDATE

   NOW()                    CURDATE()        
   2008-11-11 12:45:34      2008-11-11       

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

XmlWriter to Write to a String Instead of to a File

You need to create a StringWriter, and pass that to the XmlWriter.

The string overload of the XmlWriter.Create is for a filename.

E.g.

using (var sw = new StringWriter()) {
  using (var xw = XmlWriter.Create(sw)) {
    // Build Xml with xw.


  }
  return sw.ToString();
}