Programs & Examples On #Submit button

An HTML tag typically found at the end of a FORM section that, when clicked, sends the form data to the server.

How to set text color in submit button?

_x000D_
_x000D_
.button_x000D_
{_x000D_
    font-size: 13px;_x000D_
    color:green;_x000D_
}
_x000D_
<input type="submit" value="Fetch" class="button"/>
_x000D_
_x000D_
_x000D_

Multiple submit buttons on HTML form – designate one button as default

My suggestion is don't fight this behaviour. You can effectively alter the order using floats. For example:

<p id="buttons">
<input type="submit" name="next" value="Next">
<input type="submit" name="prev" value="Previous">
</p>

with:

#buttons { overflow: hidden; }
#buttons input { float: right; }

will effectively reverse the order and thus the "Next" button will be the value triggered by hitting enter.

This kind of technique will cover many circumstances without having to resort to more hacky JavaScript methods.

Run php function on button click

No Problem You can use onClick() function easily without using any other interference of language,

<?php
echo '<br><Button onclick="document.getElementById(';?>'modal-wrapper2'<?php echo ').style.display=';?>'block'<?php echo '" name="comment" style="width:100px; color: white;background-color: black;border-radius: 10px; padding: 4px;">Show</button>';
?>

CSS selector for disabled input type="submit"

Does that work in IE6?

No, IE6 does not support attribute selectors at all, cf. CSS Compatibility and Internet Explorer.

You might find How to workaround: IE6 does not support CSS “attribute” selectors worth the read.


EDIT
If you are to ignore IE6, you could do (CSS2.1):

input[type=submit][disabled=disabled],
button[disabled=disabled] {
    ...
}

CSS3 (IE9+):

input[type=submit]:disabled,
button:disabled {
    ...
}

You can substitute [disabled=disabled] (attribute value) with [disabled] (attribute presence).

How do I use an image as a submit button?

Just remove the border and add a background image in css

Example:

_x000D_
_x000D_
$("#form").on('submit', function() {_x000D_
   alert($("#submit-icon").val());_x000D_
});
_x000D_
#submit-icon {_x000D_
  background-image: url("https://pixabay.com/static/uploads/photo/2016/10/18/21/22/california-1751455__340.jpg"); /* Change url to wanted image */_x000D_
  background-size: cover;_x000D_
  border: none;_x000D_
  width: 32px;_x000D_
  height: 32px;_x000D_
  cursor: pointer;_x000D_
  color: transparent;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form id="form">_x000D_
  <input type="submit" id="submit-icon" value="test">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Multiple submit buttons in an HTML form

From https://html.spec.whatwg.org/multipage/forms.html#implicit-submission

A form element's default button is the first submit button in tree order whose form owner is that form element.

If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form)...

Having the next input be type="submit" and changing the previous input to type="button" should give the desired default behavior.

<form>
   <input type="text" name="field1" /> <!-- put your cursor in this field and press Enter -->

   <input type="button" name="prev" value="Previous Page" /> <!-- This is the button that will submit -->
   <input type="submit" name="next" value="Next Page" /> <!-- But this is the button that I WANT to submit -->
</form>

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

Here's a variation I had to solve that's worth sharing: for each unique string in columnA I wanted to find the most common associated string in columnB.

df.groupby('columnA').agg({'columnB': lambda x: x.mode().any()}).reset_index()

The .any() picks one if there's a tie for the mode. (Note that using .any() on a Series of ints returns a boolean rather than picking one of them.)

For the original question, the corresponding approach simplifies to

df.groupby('columnA').columnB.agg('max').reset_index().

How to get the URL of the current page in C#

Just sharing as this was my solution thanks to Canavar's post.

If you have something like this:

"http://localhost:1234/Default.aspx?un=asdf&somethingelse=fdsa"

or like this:

"https://www.something.com/index.html?a=123&b=4567"

and you only want the part that a user would type in then this will work:

String strPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
String strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");

which would result in these:

"http://localhost:1234/"
"https://www.something.com/"

How to use RANK() in SQL Server

To answer your question title, "How to use Rank() in SQL Server," this is how it works:

I will use this set of data as an example:

create table #tmp
(
  column1 varchar(3),
  column2 varchar(5),
  column3 datetime,
  column4 int
)

insert into #tmp values ('AAA', 'SKA', '2013-02-01 00:00:00', 10)
insert into #tmp values ('AAA', 'SKA', '2013-01-31 00:00:00', 15)
insert into #tmp values ('AAA', 'SKB', '2013-01-31 00:00:00', 20)
insert into #tmp values ('AAA', 'SKB', '2013-01-15 00:00:00', 5)
insert into #tmp values ('AAA', 'SKC', '2013-02-01 00:00:00', 25)

You have a partition which basically specifies grouping.

In this example, if you partition by column2, the rank function will create ranks for groups of column2 values. There will be different ranks for rows where column2 = 'SKA' than rows where column2 = 'SKB' and so on.

The ranks are decided like this: The rank for every record is one plus the number of ranks that come before it in its partition. The rank will only increment when one of the fields you selected (other than the partitioned field(s)) is different than the ones that come before it. If all of the selected fields are the same, then the ranks will tie and both will be assigned the value, one.

Knowing this, if we only wanted to select one value from each group in column two, we could use this query:

with cte as 
(
  select *, 
  rank() over (partition by column2 
             order by column3) rnk
  from t

) select * from cte where rnk = 1 order by column3;

Result:

COLUMN1 | COLUMN2   | COLUMN3                           |COLUMN4 | RNK
------------------------------------------------------------------------------
AAA     | SKB   | January, 15 2013 00:00:00+0000    |5   | 1
AAA     | SKA   | January, 31 2013 00:00:00+0000    |15  | 1
AAA     | SKC   | February, 01 2013 00:00:00+0000   |25  | 1

SQL DEMO

Mocking Extension Methods with Moq

So if you are using Moq, and want to mock the result of an Extension method, then you can use SetupReturnsDefault<ReturnTypeOfExtensionMethod>(new ConcreteInstanceToReturn()) on the instance of the mock class that has the extension method you are trying to mock.

It is not perfect, but for unit testing purposes it works well.

Collapsing Sidebar with Bootstrap

Via Angular: using ng-class of Angular, we can hide and show the side bar.

http://jsfiddle.net/DVE4f/359/

<div class="container" style="width:100%" ng-app ng-controller="AppCtrl">
<div class="row">
    <div ng-class="showgraphSidebar ? 'col-xs-3' : 'hidden'" id="colPush" >
        Sidebar
    </div>
    <div ng-class="showgraphSidebar ? 'col-xs-9' : 'col-xs-12'"  id="colMain"  >
        <button  ng-click='toggle()' >Sidebar Toggle</a>
    </div>    
  </div>
</div>

.

function AppCtrl($scope) {
    $scope.showgraphSidebar = false;
    $scope.toggle = function() {
        $scope.showgraphSidebar = !$scope.showgraphSidebar;
    }
}

Python 3 print without parenthesis

The AHK script is a great idea. Just for those interested I needed to change it a little bit to work for me:

SetTitleMatchMode,2         ;;; allows for a partial search 
#IfWinActive, .py           ;;; scope limiter to only python files
:b*:print ::print(){Left}   ;;; I forget what b* does
#IfWinActive                ;;; remove the scope limitation

Convert UTC date time to local date time

Add the time zone at the end, in this case 'UTC':

theDate = new Date( Date.parse('6/29/2011 4:52:48 PM UTC'));

after that, use toLocale()* function families to display the date in the correct locale

theDate.toLocaleString();  // "6/29/2011, 9:52:48 AM"
theDate.toLocaleTimeString();  // "9:52:48 AM"
theDate.toLocaleDateString();  // "6/29/2011"

Add a border outside of a UIView (instead of inside)

For a Swift implementation, you can add this as a UIView extension.

extension UIView {

    struct Constants {
        static let ExternalBorderName = "externalBorder"
    }

    func addExternalBorder(borderWidth: CGFloat = 2.0, borderColor: UIColor = UIColor.whiteColor()) -> CALayer {
        let externalBorder = CALayer()
        externalBorder.frame = CGRectMake(-borderWidth, -borderWidth, frame.size.width + 2 * borderWidth, frame.size.height + 2 * borderWidth)
        externalBorder.borderColor = borderColor.CGColor
        externalBorder.borderWidth = borderWidth
        externalBorder.name = Constants.ExternalBorderName

        layer.insertSublayer(externalBorder, atIndex: 0)
        layer.masksToBounds = false

        return externalBorder
    }

    func removeExternalBorders() {
        layer.sublayers?.filter() { $0.name == Constants.ExternalBorderName }.forEach() {
            $0.removeFromSuperlayer()
        }
    }

    func removeExternalBorder(externalBorder: CALayer) {
        guard externalBorder.name == Constants.ExternalBorderName else { return }
        externalBorder.removeFromSuperlayer()
    }

}

Auto expand a textarea using jQuery

People seem to have very over worked solutions...

This is how I do it:

  $('textarea').keyup(function()
  {
    var 
    $this  = $(this),
    height = parseInt($this.css('line-height'),     10),
    padTop = parseInt($this.css('padding-top'),     10),
    padBot = parseInt($this.css('padding-bottom'),  10);

    $this.height(0);

    var 
    scroll = $this.prop('scrollHeight'),
    lines  = (scroll  - padTop - padBot) / height;

    $this.height(height * lines);
  });

This will work with long lines, as well as line breaks.. grows and shrinks..

Update cordova plugins in one command

Go to your cordova project directory then write

npm outdated

npm will be display your outdated plugins, if any plugin outdated then write this command

npm update

Console Preview

:first-child not working as expected

The element cannot directly inherit from <body> tag. You can try to put it in a <dir style="padding-left:0px;"></dir> tag.

How do you create optional arguments in php?

If you don't know how many attributes need to be processed, you can use the variadic argument list token(...) introduced in PHP 5.6 (see full documentation here).

Syntax:

function <functionName> ([<type> ]...<$paramName>) {}

For example:

function someVariadricFunc(...$arguments) {
  foreach ($arguments as $arg) {
    // do some stuff with $arg...
  }
}

someVariadricFunc();           // an empty array going to be passed
someVariadricFunc('apple');    // provides a one-element array
someVariadricFunc('apple', 'pear', 'orange', 'banana');

As you can see, this token basically turns all parameters to an array, which you can process in any way you like.

PHP Warning: Division by zero

You need to wrap your form processing code in a conditional so it doesn't run when you first open the page. Something like so:

if($_POST['num1'] > 0 && $_POST['num2'] > 0 && $_POST['num3'] > 0 && $_POST['num4'] > 0){

  $itemQty = $_POST['num1'];
  $itemCost = $_POST['num2'];
  $itemSale = $_POST['num3'];
  $shipMat = $_POST['num4'];

  $diffPrice = $itemSale - $itemCost;
  $actual = ($diffPrice - $shipMat) * $itemQty;
  $diffPricePercent = (($actual * 100) / $itemCost) / $itemQty ;
}

How to call a web service from jQuery

You can make an AJAX request like any other requests:

$.ajax( {
type:'Get',
url:'http://mysite.com/mywebservice',
success:function(data) {
 alert(data);
}

})

Defining array with multiple types in TypeScript

If you're treating it as a tuple (see section 3.3.3 of the language spec), then:

var t:[number, string] = [1, "message"]

or

interface NumberStringTuple extends Array<string|number>{0:number; 1:string}
var t:NumberStringTuple = [1, "message"];

Get the records of last month in SQL server

SELECT * FROM Member WHERE month(date_created) = month(NOW() - INTERVAL 1 MONTH);

Get list of a class' instance methods

$ irb --simple-prompt

class TestClass
  def method1
  end

  def method2
  end

  def method3
  end
end

tc_list = TestClass.instance_methods(false)
#[:method1, :method2, :method3]
puts tc_list
#method1
#method2
#method3

Serializing/deserializing with memory stream

BinaryFormatter may produce invalid output in some specific cases. For example it will omit unpaired surrogate characters. It may also have problems with values of interface types. Read this documentation page including community content.

If you find your error to be persistent you may want to consider using XML serializer like DataContractSerializer or XmlSerializer.

Hibernate: failed to lazily initialize a collection of role, no session or session was closed

for me it worked the approach that I used in eclipselink as well. Just call the size() of the collection that should be loaded before using it as parameter to pages.

for (Entity e : entityListKeeper.getEntityList()) {
    e.getListLazyLoadedEntity().size();
}

Here entityListKeeper has List of Entity that has list of LazyLoadedEntity. If you have just therelation Entity has list of LazyLoadedEntity then the solution is:

getListLazyLoadedEntity().size();

Vlookup referring to table data in a different sheet

This lookup only features exact matches. If you have an extra space in one of the columns or something similar it will not recognize it.

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

It took me few hours to solved this because all off the settings that I found here about this error were the same but it still didn't work. The problem was tha I had a folder in my web service from which the file should be send to WinCE device, after converting that folder to an application with Classic.NetAppPool it started to work.

How can I add a column that doesn't allow nulls in a Postgresql database?

Specifying a default value would also work, assuming a default value is appropriate.

How to convert buffered image to image and vice-versa?

BufferedImage is a subclass of Image. You don't need to do any conversion.

GIT clone repo across local file system in windows

Either enter absolute paths or relative paths.

For example the first one below uses absolute paths :

(this is from inside the folder which contains the repository and the backup as subfolders. also remember that the backup folder is not modified if it already contains anything. and if it is not present, a new folder will be created )

~/git$ git clone --no-hardlinks ~/git/git_test1/   ~/git/bkp_repos/

The following uses relative paths :

~/git$ git clone --no-hardlinks git_test1/   bkp_repos2/

Where do I find some good examples for DDD?

Check out Project Silk. Not only does it demonstrate DDD but other cutting edge patterns. This is an excellent resource for any Web Developer. A full overview of the project can be found on MSDN.

Subtract 1 day with PHP

 date('Y-m-d',(strtotime ( '-1 day' , strtotime ( $date) ) ));

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

Laravel is there a way to add values to a request array

You can add parameters to the request from a middleware by doing:

public function handle($request, Closure $next)
{
    $request->route()->setParameter('foo', 'bar');
    return $next($request);
}

How to log request and response body with Retrofit-Android?

call.request().toString();

Screenshot request which is being sent to server: enter image description here

Python 3 string.join() equivalent?

There are method join for string objects:

".".join(("a","b","c"))

How to include static library in makefile

Make sure that the -L option appears ahead of the -l option; the order of options in linker command lines does matter, especially with static libraries. The -L option specifies a directory to be searched for libraries (static or shared). The -lname option specifies a library which is with libmine.a (static) or libmine.so (shared on most variants of Unix, but Mac OS X uses .dylib and HP-UX used to use .sl). Conventionally, a static library will be in a file libmine.a. This is convention, not mandatory, but if the name is not in the libmine.a format, you cannot use the -lmine notation to find it; you must list it explicitly on the compiler (linker) command line.

The -L./libmine option says "there is a sub-directory called libmine which can be searched to find libraries". I can see three possibilities:

  1. You have such a sub-directory containing libmine.a, in which case you also need to add -lmine to the linker line (after the object files that reference the library).
  2. You have a file libmine that is a static archive, in which case you simply list it as a file ./libmine with no -L in front.
  3. You have a file libmine.a in the current directory that you want to pick up. You can either write ./libmine.a or -L . -lmine and both should find the library.

How can I revert a single file to a previous version?

Extracted from here: http://git.661346.n2.nabble.com/Revert-a-single-commit-in-a-single-file-td6064050.html

 git revert <commit> 
 git reset 
 git add <path> 
 git commit ... 
 git reset --hard # making sure you didn't have uncommited changes earlier 

It worked very fine to me.

How to connect to LocalDB in Visual Studio Server Explorer?

The following works with Visual Studio 2017 Community Edition on Windows 10 using SQLServer Express 2016.

Open a PowerShell check what it is called using SqlLocalDB.exe info and whether it is Running with SqlLocalDB.exe info NAME. Here's what it looks like on my machine:

> SqlLocalDB.exe info
MSSQLLocalDB
> SqlLocalDB.exe info MSSQLLocalDB
Name:               mssqllocaldb
Version:            13.0.1601.5
Shared name:
Owner:              DESKTOP-I4H3E09\simon
Auto-create:        Yes
State:              Running
Last start time:    4/12/2017 8:24:36 AM
Instance pipe name: np:\\.\pipe\LOCALDB#EFC58609\tsql\query
>

If it isn't running then you need to start it with SqlLocalDB.exe start MSSQLLocalDB. When it is running you see the Instance pipe name: which starts with np:\\. Copy that named pipe string. Within VS2017 open the view Server Explorer and create a new connection of type Microsoft SQL Server (SqlClient) (don't be fooled by the other file types you want the full fat connection type) and set the Server name: to be the instance pipe name you copied from PowerShell.

I also set the Connect to database to be the same database that was in the connection string that was working in my Dotnet Core / Entity Framework Core project which was set up using dotnet ef database update.

You can login and create a database using the sqlcmd and the named pipe string:

sqlcmd -S np:\\.\pipe\LOCALDB#EFC58609\tsql\query 1> create database EFGetStarted.ConsoleApp.NewDb; 2> GO

There are instructions on how to create a user for your application at https://docs.microsoft.com/en-us/sql/tools/sqllocaldb-utility

How can I create a text box for a note in markdown?

Here's a simple latex-based example.

---
header-includes:
    - \usepackage[most]{tcolorbox}
    - \definecolor{light-yellow}{rgb}{1, 0.95, 0.7}
    - \newtcolorbox{myquote}{colback=light-yellow,grow to right by=-10mm,grow to left by=-10mm, boxrule=0pt,boxsep=0pt,breakable}
    - \newcommand{\todo}[1]{\begin{myquote} \textbf{TODO:} \emph{#1} \end{myquote}}
---

blah blah

\todo{something}

blah

which results in: enter image description here

Unfortunately because this is latex, you can no-longer include markdown inside the TODO box (which is not a huge problem, usually), and it won't work when converting to formats other than PDF (e.g. html).

C#: How to access an Excel cell?

If you are trying to automate Excel, you probably shouldn't be opening a Word document and using the Word automation ;)

Check this out, it should get you started,

http://www.codeproject.com/KB/office/package.aspx

And here is some code. It is taken from some of my code and has a lot of stuff deleted, so it doesn't do anything and may not compile or work exactly, but it should get you going. It is oriented toward reading, but should point you in the right direction.

Microsoft.Office.Interop.Excel.Worksheet sheet = newWorkbook.ActiveSheet;

if ( sheet != null )
{
    Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
    if ( range != null )
    {
        int nRows = usedRange.Rows.Count;
        int nCols = usedRange.Columns.Count;
        foreach ( Microsoft.Office.Interop.Excel.Range row in usedRange.Rows )
        {
            string value = row.Cells[0].FormattedValue as string;
        }
    }
 }

You can also do

Microsoft.Office.Interop.Excel.Sheets sheets = newWorkbook.ExcelSheets;

if ( sheets != null )
{
     foreach ( Microsoft.Office.Interop.Excel.Worksheet sheet in sheets )
     {
          // Do Stuff
     }
}

And if you need to insert rows/columns

// Inserts a new row at the beginning of the sheet
Microsoft.Office.Interop.Excel.Range a1 = sheet.get_Range( "A1", Type.Missing );
a1.EntireRow.Insert( Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing );

How to convert text column to datetime in SQL

Use convert with style 101.

select convert(datetime, Remarks, 101)

If your column is really text you need to convert to varchar before converting to datetime

select convert(datetime, convert(varchar(30), Remarks), 101)

Should methods in a Java interface be declared with or without a public access modifier?

The public modifier should be omitted in Java interfaces (in my opinion).

Since it does not add any extra information, it just draws attention away from the important stuff.

Most style-guides will recommend that you leave it out, but of course, the most important thing is to be consistent across your codebase, and especially for each interface. The following example could easily confuse someone, who is not 100% fluent in Java:

public interface Foo{
  public void MakeFoo();
  void PerformBar();
}

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).*$/

this the simple way to use it while validate atleast 1 uppercase 1 lowercase and 1 number

and this is the example while I use in express validation

check('password')
    .notEmpty()
    .withMessage('Password cannot be null')
    .bail()
    .isLength({ min: 6 })
    .withMessage('Password must be at least 6 characters')
    .bail()
    .matches(/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).*$/)
    .withMessage(
      'Must have atleast 1 uppercase, 1 lowercase letter and 1 number'
    ),

Emulator in Android Studio doesn't start

I had the same issue in Android Studio 2.3.3 on Mac OS X 10.12.6 and the issue was caused by Android Studio using an old version of HAXM (6.0.3 when it should have been 6.2.1):

$ kextstat | grep intel
  148    0 0xffffff7f8342c000 0x14000    0x14000    com.intel.kext.intelhaxm (6.0.3) 50449AFC-F7C6-38A0-B820-233E8A050FD6 <7 5 4 3 1>

Removing and reintalling HAXM from within Android Studio according to the instructions didn't work: https://software.intel.com/en-us/android/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-mac-os-x

Instead, download the HAXM installer manually or if that link expires, find it under https://software.intel.com/en-us/android/tools under Intel® Hardware Accelerated Execution Manager (Intel® HAXM).

After running the installer, it now shows that the current version of HAXM is installed:

$ kextstat | grep intel
  169    0 0xffffff7f83472000 0x1d000    0x1d000    com.intel.kext.intelhaxm (6.2.1) 7B6ABC56-699C-3449-A0EC-BEB36C154E3C <7 5 4 3 1>

After upgrading HAXM manually, I'm able to launch x86_64 emulators.


Old answer, which might work instead (note that this didn't work for me for x86_64 images):

Create a new device:

Tools->Android->AVD Manager

+ Create Virtual Device

Tablet -> Nexus 7 -> Next

The Recommended tab should be highlighted.

Even though I had the API Level 25 SDK installed, it showed:

Nougat Download 25 x86 Android 7.1.1 (Google APIs)

So I clicked Download link which seems to have repaired the API Level 25 SDK. I finished creating my new device and it ran fine.

Unfortunately I had already deleted my old device, so if this works for someone else, please leave a comment here to let us know if your original device worked afterwards, thanks!

Where am I? - Get country

Actually I just found out that there is even one more way of getting a country code, using the getSimCountryIso() method of TelephoneManager:

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();

Since it is the sim code it also should not change when traveling to other countries.

Bootstrap dropdown sub menu missing

Comment to Skelly's really helpful workaround: in Bootstrap-sass 3.3.6, utilities.scss, line 19: .pull-left has float:left !important. Since that, I recommend to use !important in his CSS as well:

.dropdown-submenu.pull-left {
    float:none !important;
}

Git clone without .git directory

since you only want the files, you don't need to treat it as a git repo.

rsync -rlp --exclude '.git' user@host:path/to/git/repo/ .

and this only works with local path and remote ssh/rsync path, it may not work if the remote server only provides git:// or https:// access.

Windows CMD command for accessing usb?

You can access the USB drive by its drive letter. To know the drive letter you can run this command:

C:\>wmic logicaldisk where drivetype=2 get deviceid, volumename, description

From here you will get the drive letter (Device ID) of your USB drive.

For example if its F: then run the following command in command prompt to see its contents:

C:\> F:

F:\> dir

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I've gotten same problem. The servers logs showed:

DEBUG: <-- origin: null

I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine

How to update record using Entity Framework 6?

For .net core

context.Customer.Add(customer);
context.Entry(customer).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
context.SaveChanges();

Converting XDocument to XmlDocument and vice versa

There is a discussion on http://blogs.msdn.com/marcelolr/archive/2009/03/13/fast-way-to-convert-xmldocument-into-xdocument.aspx

It seems that reading an XDocument via an XmlNodeReader is the fastest method. See the blog for more details.

htons() function in socket programing

htons is host-to-network short

This means it works on 16-bit short integers. i.e. 2 bytes.

This function swaps the endianness of a short.

Your number starts out at:

0001 0011 1000 1001 = 5001

When the endianness is changed, it swaps the two bytes:

1000 1001 0001 0011 = 35091

python pandas dataframe to dictionary

in some versions the code below might not work

mydict = dict(zip(df.id, df.value))

so make it explicit

id_=df.id.values
value=df.value.values
mydict=dict(zip(id_,value))

Note i used id_ because the word id is reserved word

C# Listbox Item Double Click Event

I know this question is quite old, but I was looking for a solution to this problem too. The accepted solution is for WinForms not WPF which I think many who come here are looking for.

For anyone looking for a WPF solution, here is a great approach (via Oskar's answer here):

private void myListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    DependencyObject obj = (DependencyObject)e.OriginalSource;

    while (obj != null && obj != myListBox)
    {
        if (obj.GetType() == typeof(ListBoxItem))
        {
             // Do something
             break;
         }
         obj = VisualTreeHelper.GetParent(obj);
    }
}

Basically, you walk up the VisualTree until you've either found a parent item that is a ListBoxItem, or you ascend up to the actual ListBox (and therefore did not click a ListBoxItem).

Task continuation on UI thread

Call the continuation with TaskScheduler.FromCurrentSynchronizationContext():

    Task UITask= task.ContinueWith(() =>
    {
     this.TextBlock1.Text = "Complete"; 
    }, TaskScheduler.FromCurrentSynchronizationContext());

This is suitable only if the current execution context is on the UI thread.

How to configure Visual Studio to use Beyond Compare

VS2013 on 64-bit Windows 7 requires these settings: Tools | Options | Source Control | Jazz Source Control

CHECK THE CHECKBOX Use an external compare tool ... (easy to miss this)

2-Way Compare Location of Executable: C:\Program Files (x86)\Beyond Compare 3\BCompare.exe

3-Way Conflict Compare Location of Executable: C:\Program Files (x86)\Beyond Compare 3\BCompare.exe

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

If your dump file doesn't have DEFINER, make sure these lines below are also removed if they're there, or commented-out with --:

At the start:

-- SET @@SESSION.SQL_LOG_BIN= 0;
-- SET @@GLOBAL.GTID_PURGED=/*!80000 '+'*/ '';

At the end:

-- SET @@SESSION.SQL_LOG_BIN = @MYSQLDUMP_TEMP_LOG_BIN;

R barplot Y-axis scale too short

barplot(data)

enter image description here

barplot(data, yaxp=c(0, max(data), 5))

enter image description here

yaxp=c(minY-axis, maxY-axis, Interval)

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

Let me add an example here:

I'm trying to build Alluxio on windows platform and got the same issue, it's because the pom.xml contains below step:

      <plugin>
        <artifactId>exec-maven-plugin</artifactId>
        <groupId>org.codehaus.mojo</groupId>
        <inherited>false</inherited>
        <executions>
          <execution>
            <id>Check that there are no Windows line endings</id>
            <phase>compile</phase>
            <goals>
              <goal>exec</goal>
            </goals>
            <configuration>
              <executable>${build.path}/style/check_no_windows_line_endings.sh</executable>
            </configuration>
          </execution>
        </executions>
      </plugin>

The .sh file is not executable on windows so the error throws.

Comment it out if you do want build Alluxio on windows.

Javascript - Regex to validate date format

If you want to validate your date(YYYY-MM-DD) along with the comparison it will be use full for you...

    function validateDate()
    {
     var newDate = new Date();
     var presentDate = newDate.getDate();
     var presentMonth = newDate.getMonth();
     var presentYear = newDate.getFullYear();
     var dateOfBirthVal = document.forms[0].dateOfBirth.value;
    if (dateOfBirthVal == null) 
    return false;
    var validatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/;
    dateValues = dateOfBirthVal.match(validatePattern);
    if (dateValues == null) 
    {
        alert("Date of birth should be null and it should in the format of yyyy-mm-dd")
    return false;
        }
    var birthYear = dateValues[1];        
    birthMonth = dateValues[3];
    birthDate=  dateValues[5];
    if ((birthMonth < 1) || (birthMonth > 12)) 
    {
        alert("Invalid date")
    return false;
        }
    else if ((birthDate < 1) || (birthDate> 31)) 
    {
        alert("Invalid date")
    return false;
        }
    else if ((birthMonth==4 || birthMonth==6 || birthMonth==9 || birthMonth==11) && birthDate ==31) 
    {
        alert("Invalid date")
    return false;
        }
    else if (birthMonth == 2){ 
    var isleap = (birthYear % 4 == 0 && (birthYear % 100 != 0 || birthYear % 400 == 0));
    if (birthDate> 29 || (birthDate ==29 && !isleap)) 
    {
        alert("Invalid date")
    return false;
        }
    }
    else if((birthYear>presentYear)||(birthYear+70<presentYear))
        {
        alert("Invalid date")
        return false;
        }
    else if(birthYear==presentYear)
        {
        if(birthMonth>presentMonth+1)
            {
            alert("Invalid date")
            return false;
            }
        else if(birthMonth==presentMonth+1)
            {
            if(birthDate>presentDate)
                {
                alert("Invalid date")
                return false;
                }
            }
        }
return true;
    }

How to find first element of array matching a boolean condition in JavaScript?

As of ES 2015, Array.prototype.find() provides for this exact functionality.

For browsers that do not support this feature, the Mozilla Developer Network has provided a polyfill (pasted below):

if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this === null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

Check if current date is between two dates Oracle SQL

You don't need to apply to_date() to sysdate. It is already there:

select 1
from dual 
WHERE sysdate BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND TO_DATE('20/06/2014', 'DD/MM/YYYY');

If you are concerned about the time component on the date, then use trunc():

select 1
from dual 
WHERE trunc(sysdate) BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND
                             TO_DATE('20/06/2014', 'DD/MM/YYYY');

What's the UIScrollView contentInset property for?

While jball's answer is an excellent description of content insets, it doesn't answer the question of when to use it. I'll borrow from his diagrams:

  _|?_cW_?_|_?_
   |       | 
---------------
   |content| ?
 ? |content| contentInset.top
cH |content|
 ? |content| contentInset.bottom
   |content| ?
---------------
   |content|    
-------------?-

That's what you get when you do it, but the usefulness of it only shows when you scroll:

  _|?_cW_?_|_?_
   |content| ? content is still visible
---------------
   |content| ?
 ? |content| contentInset.top
cH |content|
 ? |content| contentInset.bottom
   |content| ?
---------------
  _|_______|___ 
             ?

That top row of content will still be visible because it's still inside the frame of the scroll view. One way to think of the top offset is "how much to shift the content down the scroll view when we're scrolled all the way to the top"

To see a place where this is actually used, look at the build-in Photos app on the iphone. The Navigation bar and status bar are transparent, and the contents of the scroll view are visible underneath. That's because the scroll view's frame extends out that far. But if it wasn't for the content inset, you would never be able to have the top of the content clear that transparent navigation bar when you go all the way to the top.

How do I empty an array in JavaScript?

Use below if you need to empty Angular 2+ FormArray.

public emptyFormArray(formArray:FormArray) {
    for (let i = formArray.controls.length - 1; i >= 0; i--) {
        formArray.removeAt(i);
    }
}

How to import existing Git repository into another?

I think you can do this using 'git mv' and 'git pull'.

I'm a fair git noob - so be careful with your main repository - but I just tried this in a temp dir and it seems to work.

First - rename the structure of XXX to match how you want it to look when it's within YYY:

cd XXX
mkdir tmp
git mv ZZZ tmp/ZZZ
git mv tmp ZZZ

Now XXX looks like this:

XXX
 |- ZZZ
     |- ZZZ

Now use 'git pull' to fetch the changes across:

cd ../YYY
git pull ../XXX

Now YYY looks like this:

YYY
 |- ZZZ
     |- ZZZ
 |- (other folders that already were in YYY)

Splitting a Java String by the pipe symbol using split("|")

test.split("\\|",999);

Specifing a limit or max will be accurate for examples like: "boo|||a" or "||boo|" or " |||"

But test.split("\\|"); will return different length strings arrays for the same examples.

use reference: link

What design patterns are used in Spring framework?

There are loads of different design patterns used, but there are a few obvious ones:

  • Proxy - used heavily in AOP, and remoting.

  • Singleton - beans defined in spring config files are singletons by default.

  • Template method - used extensively to deal with boilerplate repeated code (such as closing connections cleanly, etc..). For example JdbcTemplate, JmsTemplate, JpaTemplate.


Update following comments: For MVC, you might want to read the MVC Reference

Some obvious patterns in use in MVC:

  • Model View Controller :-) . The advantage with Spring MVC is that your controllers are POJOs as opposed to being servlets. This makes for easier testing of controllers. One thing to note is that the controller is only required to return a logical view name, and the view selection is left to a separate ViewResolver. This makes it easier to reuse controllers for different view technologies.

  • Front Controller. Spring provides DispatcherServlet to ensure an incoming request gets dispatched to your controllers.

  • View Helper - Spring has a number of custom JSP tags, and velocity macros, to assist in separating code from presentation in views.

How to open local files in Swagger-UI

I had that issue and here is much simpler solution:

  • Make a dir (eg: swagger-ui) in your public dir (static path: no route is required) and copy dist from swagger-ui into that directory and open localhost/swagger-ui
  • You will see swagger-ui with default petstore example
  • Replace default petstore url in dist/index.html with your localhost/api-docs or to make it more generalized, replace with this:

    location.protocol+'//' + location.hostname+(location.port ? ':' + location.port: '') + "/api-docs";

  • Hit again localhost/swagger-ui

Voila! You local swagger implementation is ready

How to "add existing frameworks" in Xcode 4?

In Project

  1. Select the project navigator
  2. Click on Build Phases
  3. Click on link binary with libraries
  4. Click on + Button and add your Frameworks

Update Item to Revision vs Revert to Revision

The text from the Tortoise reference:

Update item to revision Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent.

If you want to undo an earlier change permanently, use Revert to this revision instead.

Revert to this revision Revert to an earlier revision. If you have made several changes, and then decide that you really want to go back to how things were in revision N, this is the command you need. The changes are undone in your working copy so this operation does not affect the repository until you commit the changes. Note that this will undo all changes made after the selected revision, replacing the file/folder with the earlier version.

If your working copy is in an unmodified state, after you perform this action your working copy will show as modified. If you already have local changes, this command will merge the undo changes into your working copy.

What is happening internally is that Subversion performs a reverse merge of all the changes made after the selected revision, undoing the effect of those previous commits.

If after performing this action you decide that you want to undo the undo and get your working copy back to its previous unmodified state, you should use TortoiseSVN ? Revert from within Windows Explorer, which will discard the local modifications made by this reverse merge action.

If you simply want to see what a file or folder looked like at an earlier revision, use Update to revision or Save revision as... instead.

character count using jquery

For length including white-space:

$("#id").val().length

For length without white-space:

$("#id").val().replace(/ /g,'').length

For removing only beginning and trailing white-space:

$.trim($("#test").val()).length

For example, the string " t e s t " would evaluate as:

//" t e s t "
$("#id").val(); 

//Example 1
$("#id").val().length; //Returns 9
//Example 2
$("#id").val().replace(/ /g,'').length; //Returns 4
//Example 3
$.trim($("#test").val()).length; //Returns 7

Here is a demo using all of them.

Detect browser or tab closing

window.addEventListener("beforeunload", function (e) {
 var confirmationMessage = "tab close";

 (e || window.event).returnValue = confirmationMessage;     //Gecko + IE
 sendkeylog(confirmationMessage);
 return confirmationMessage;                                //Webkit, Safari, Chrome etc.
}); 

Initializing a member array in constructor initializer

Workaround:

template<class T, size_t N>
struct simple_array { // like std::array in C++0x
   T arr[N];
};


class C : private simple_array<int, 3> 
{
      static simple_array<int, 3> myarr() {
           simple_array<int, 3> arr = {1,2,3};
           return arr;
      }
public:
      C() : simple_array<int, 3>(myarr()) {}
};

How to set the default value of an attribute on a Laravel model

You should set default values in migrations:

$table->tinyInteger('role')->default(1);

Synchronously waiting for an async operation, and why does Wait() freeze the program here

The await inside your asynchronous method is trying to come back to the UI thread.

Since the UI thread is busy waiting for the entire task to complete, you have a deadlock.

Moving the async call to Task.Run() solves the issue.
Because the async call is now running on a thread pool thread, it doesn't try to come back to the UI thread, and everything therefore works.

Alternatively, you could call StartAsTask().ConfigureAwait(false) before awaiting the inner operation to make it come back to the thread pool rather than the UI thread, avoiding the deadlock entirely.

numpy max vs amax vs maximum

np.max is just an alias for np.amax. This function only works on a single input array and finds the value of maximum element in that entire array (returning a scalar). Alternatively, it takes an axis argument and will find the maximum value along an axis of the input array (returning a new array).

>>> a = np.array([[0, 1, 6],
                  [2, 4, 1]])
>>> np.max(a)
6
>>> np.max(a, axis=0) # max of each column
array([2, 4, 6])

The default behaviour of np.maximum is to take two arrays and compute their element-wise maximum. Here, 'compatible' means that one array can be broadcast to the other. For example:

>>> b = np.array([3, 6, 1])
>>> c = np.array([4, 2, 9])
>>> np.maximum(b, c)
array([4, 6, 9])

But np.maximum is also a universal function which means that it has other features and methods which come in useful when working with multidimensional arrays. For example you can compute the cumulative maximum over an array (or a particular axis of the array):

>>> d = np.array([2, 0, 3, -4, -2, 7, 9])
>>> np.maximum.accumulate(d)
array([2, 2, 3, 3, 3, 7, 9])

This is not possible with np.max.

You can make np.maximum imitate np.max to a certain extent when using np.maximum.reduce:

>>> np.maximum.reduce(d)
9
>>> np.max(d)
9

Basic testing suggests the two approaches are comparable in performance; and they should be, as np.max() actually calls np.maximum.reduce to do the computation.

Convert Object to JSON string

Convert JavaScript object to json data

$("form").submit(function(event){
  event.preventDefault();
  var formData = $("form").serializeArray(); // Create array of object
  var jsonConvertedData = JSON.stringify(formData);  // Convert to json
  consol.log(jsonConvertedData);
});

You can validate json data using http://jsonlint.com

Is right click a Javascript event?

Yes, oncontextmenu is probably the best alternative but be aware that it triggers on mouse down whereas click will trigger on mouse up.

Other related questions were asking about double right click - which apparently isn't supported except through manual timer checking. One reason you might want to be able to have right double click is if you need/want to support left-handed mouse input (button reversal). The browser implementations seem to make a lot of assumptions about how we should be using the available input devices.

Excluding files/directories from Gulp task

Gulp uses micromatch under the hood for matching globs, so if you want to exclude any of the .min.js files, you can achieve the same by using an extended globbing feature like this:

src("'js/**/!(*.min).js")

Basically what it says is: grab everything at any level inside of js that doesn't end with *.min.js

PHP str_replace replace spaces with underscores

Try this instead:

$journalName = preg_replace('/\s+/', '_', $journalName);

Explanation: you are most likely seeing whitespace, not just plain spaces (there is a difference).

How do I concatenate two strings in Java?

import com.google.common.base.Joiner;

String delimiter = "";
Joiner.on(delimiter).join(Lists.newArrayList("Your number is ", 47, "!"));

This may be overkill to answer the op's question, but it is good to know about for more complex join operations. This stackoverflow question ranks highly in general google searches in this area, so good to know.

How to do a non-greedy match in grep?

I know that its a bit of a dead post but I just noticed that this works. It removed both clean-up and cleanup from my output.

> grep -v -e 'clean\-\?up'
> grep --version grep (GNU grep) 2.20

How to install Anaconda on RaspBerry Pi 3 Model B

On Raspberry Pi 3 Model B - Installation of Miniconda (bundled with Python 3)

Go and get the latest version of miniconda for Raspberry Pi - made for armv7l processor and bundled with Python 3 (eg.: uname -m)

wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
md5sum Miniconda3-latest-Linux-armv7l.sh
bash Miniconda3-latest-Linux-armv7l.sh

After installation, source your updated .bashrc file with source ~/.bashrc. Then enter the command python --version, which should give you:

Python 3.4.3 :: Continuum Analytics, Inc.

Remove all git files from a directory?

Unlike other source control systems like SVN or CVS, git stores all of its metadata in a single directory, rather than in every subdirectory of the project. So just delete .git from the root (or use a script like git-export) and you should be fine.

How to get the current date and time

java.lang.System.currentTimeMillis(); will return the datetime since the epoch

set pythonpath before import statements

This will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are doing is generally correct.

set.py:

import sys
sys.path.append("/tmp/TEST")

loop.py

import sys
import time
while True:
  print sys.path
  time.sleep(1)

run: python loop.py &

This will run loop.py, connected to your STDOUT, and it will continue to run in the background. You can then run python set.py. Each has a different set of environment variables. Observe that the output from loop.py does not change because set.py does not change loop.py's environment.

A note on importing

Python imports are dynamic, like the rest of the language. There is no static linking going on. The import is an executable line, just like sys.path.append....

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

How to programmatically click a button in WPF?

WPF takes a slightly different approach than WinForms here. Instead of having the automation of a object built into the API, they have a separate class for each object that is responsible for automating it. In this case you need the ButtonAutomationPeer to accomplish this task.

ButtonAutomationPeer peer = new ButtonAutomationPeer(someButton);
IInvokeProvider invokeProv = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
invokeProv.Invoke();

Here is a blog post on the subject.

Note: IInvokeProvider interface is defined in the UIAutomationProvider assembly.

Is it possible to make abstract classes in Python?

In your code snippet, you could also resolve this by providing an implementation for the __new__ method in the subclass, likewise:

def G(F):
    def __new__(cls):
        # do something here

But this is a hack and I advise you against it, unless you know what you are doing. For nearly all cases I advise you to use the abc module, that others before me have suggested.

Also when you create a new (base) class, make it subclass object, like this: class MyBaseClass(object):. I don't know if it is that much significant anymore, but it helps retain style consistency on your code

How to check db2 version

In z/OS while on version 10, use of CURRENT APPLICATION COMPATIBILITY is not allowed. You will have to resort to:

SELECT GETVARIABLE('SYSIBM.VERSION') AS VERSION,
       GETVARIABLE('SYSIBM.NEWFUN')  AS COMPATIBILITY
FROM SYSIBM.SYSDUMMY1;

Here is a link to all the variables available: https://www.ibm.com/support/knowledgecenter/SSEPEK_12.0.0/sqlref/src/tpc/db2z_refs2builtinsessionvars.html#db2z_refs2builtinsessionvars

"Series objects are mutable and cannot be hashed" error

gene_name = no_headers.iloc[1:,[1]]

This creates a DataFrame because you passed a list of columns (single, but still a list). When you later do this:

gene_name[x]

you now have a Series object with a single value. You can't hash the Series.

The solution is to create Series from the start.

gene_type = no_headers.iloc[1:,0]
gene_name = no_headers.iloc[1:,1]
disease_name = no_headers.iloc[1:,2]

Also, where you have orph_dict[gene_name[x]] =+ 1, I'm guessing that's a typo and you really mean orph_dict[gene_name[x]] += 1 to increment the counter.

How to restart service using command prompt?

You can use sc start [service] to start a service and sc stop [service] to stop it. With some services net start [service] is doing the same.

But if you want to use it in the same batch, be aware that sc stop won't wait for the service to be stopped. In this case you have to use net stop [service] followed by net start [service]. This will be executed synchronously.

Getting Serial Port Information

None of the answers here satisfies my needs.

The answer from Muno is wrong because it lists ONLY the USB ports.

The answer from code4life is wrong because it lists all EXCEPT the USB ports. (Nevertheless it has 44 up-votes!!!)

I have an EPSON printer simulation port on my computer which is not listed by any of the answers here. So I had to write my own solution. Additionally I want to display more information than just the caption string. I also need to separate the port name from the description.

My code has been tested on Windows XP, Windows 7 and Windows 10.

The Port Name (like "COM1") must be read from the registry because WMI does not give this information for all COM ports (EPSON).

If you use my code you do not need SerialPort.GetPortNames() anymore. My function returns the same ports, but with additional details. Why did Microsoft not implement such a function into the framework??

using System.Management;
using Microsoft.Win32;

using (ManagementClass i_Entity = new ManagementClass("Win32_PnPEntity"))
{
    foreach (ManagementObject i_Inst in i_Entity.GetInstances())
    {
        Object o_Guid = i_Inst.GetPropertyValue("ClassGuid");
        if (o_Guid == null || o_Guid.ToString().ToUpper() != "{4D36E978-E325-11CE-BFC1-08002BE10318}")
            continue; // Skip all devices except device class "PORTS"

        String s_Caption  = i_Inst.GetPropertyValue("Caption")     .ToString();
        String s_Manufact = i_Inst.GetPropertyValue("Manufacturer").ToString();
        String s_DeviceID = i_Inst.GetPropertyValue("PnpDeviceID") .ToString();
        String s_RegPath  = "HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Enum\\" + s_DeviceID + "\\Device Parameters";
        String s_PortName = Registry.GetValue(s_RegPath, "PortName", "").ToString();

        int s32_Pos = s_Caption.IndexOf(" (COM");
        if (s32_Pos > 0) // remove COM port from description
            s_Caption = s_Caption.Substring(0, s32_Pos);

        Console.WriteLine("Port Name:    " + s_PortName);
        Console.WriteLine("Description:  " + s_Caption);
        Console.WriteLine("Manufacturer: " + s_Manufact);
        Console.WriteLine("Device ID:    " + s_DeviceID);
        Console.WriteLine("-----------------------------------");
    }
}

I tested the code with a lot of COM ports. This is the Console output:

Port Name:    COM29
Description:  CDC Interface (Virtual COM Port) for USB Debug
Manufacturer: GHI Electronics, LLC
Device ID:    USB\VID_1B9F&PID_F003&MI_01\6&3009671A&0&0001
-----------------------------------
Port Name:    COM28
Description:  Teensy USB Serial
Manufacturer: PJRC.COM, LLC.
Device ID:    USB\VID_16C0&PID_0483\1256310
-----------------------------------
Port Name:    COM25
Description:  USB-SERIAL CH340
Manufacturer: wch.cn
Device ID:    USB\VID_1A86&PID_7523\5&2499667D&0&3
-----------------------------------
Port Name:    COM26
Description:  Prolific USB-to-Serial Comm Port
Manufacturer: Prolific
Device ID:    USB\VID_067B&PID_2303\5&2499667D&0&4
-----------------------------------
Port Name:    COM1
Description:  Comunications Port
Manufacturer: (Standard port types)
Device ID:    ACPI\PNP0501\1
-----------------------------------
Port Name:    COM999
Description:  EPSON TM Virtual Port Driver
Manufacturer: EPSON
Device ID:    ROOT\PORTS\0000
-----------------------------------
Port Name:    COM20
Description:  EPSON COM Emulation USB Port
Manufacturer: EPSON
Device ID:    ROOT\PORTS\0001
-----------------------------------
Port Name:    COM8
Description:  Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID:    BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&000F\8&3ADBDF90&0&001DA568988B_C00000000
-----------------------------------
Port Name:    COM9
Description:  Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID:    BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0000\8&3ADBDF90&0&000000000000_00000002
-----------------------------------
Port Name:    COM30
Description:  Arduino Uno
Manufacturer: Arduino LLC (www.arduino.cc)
Device ID:    USB\VID_2341&PID_0001\74132343530351F03132
-----------------------------------

COM1 is a COM port on the mainboard.

COM 8 and 9 are Buetooth COM ports.

COM 25 and 26 are USB to RS232 adapters.

COM 28 and 29 and 30 are Arduino-like boards.

COM 20 and 999 are EPSON ports.

How to write header row with csv.DictWriter?

Another way to do this would be to add before adding lines in your output, the following line :

output.writerow(dict(zip(dr.fieldnames, dr.fieldnames)))

The zip would return a list of doublet containing the same value. This list could be used to initiate a dictionary.

How to reset (clear) form through JavaScript?

,reset() method does not clear the default values and checkbox field and there are many more issues.

In order to completely reset check the below link -

http://www.javascript-coder.com/javascript-form/javascript-reset-form.htm

How to add style from code behind?

Also make sure the aspx page has AutoEventWireup="true" and not AutoEventWireup="false"

What does ^M character mean in Vim?

try :%s/\^M// At least this worked for me.

Best way to store date/time in mongodb

The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.

> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }

The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.

If you need to, you can easily convert Date objects to and from Unix timestamps1), using the getTime() method and Date(milliseconds) constructor, respectively.

1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.

Get the cell value of a GridView row

Expanding on Dennis R answer above ... This will get the value based on the Heading Text (so you don't need to know what column...especially if its dynamic changing).

Example setting a session variable on SelectedIndexChange.

    protected void gvCustomer_SelectedIndexChanged(object sender, EventArgs e)
    {
        int iCustomerID = Convert.ToInt32(Library.gvGetVal(gvCustomer, "CustomerID"));
        Session[SSS.CustomerID] = iCustomerID;
    }

public class Library
{
    public static string gvGetVal(GridView gvGrid, string sHeaderText)
    {
        string sRetVal = string.Empty;
        if (gvGrid.Rows.Count > 0)
        {
            if (gvGrid.SelectedRow != null)
            {
                GridViewRow row = gvGrid.SelectedRow;
                int iCol = gvGetColumn(gvGrid, sHeaderText);
                if (iCol > -1)
                    sRetVal = row.Cells[iCol].Text;
            }
        }
        return sRetVal;
    }

    private static int gvGetColumn(GridView gvGrid, string sHeaderText)
    {
        int iRetVal = -1;
        for (int i = 0; i < gvGrid.Columns.Count; i++)
        {
            if (gvGrid.Columns[i].HeaderText.ToLower().Trim() == sHeaderText.ToLower().Trim())
            {
                iRetVal = i;
            }
        }
        return iRetVal;
    }
}

How to make a whole 'div' clickable in html and css without JavaScript?

a whole div links to another page when clicked without javascript and with valid code, is this possible?

Pedantic answer: No.

As you've already put on another comment, it's invalid to nest a div inside an a tag.

However, there's nothing preventing you from making your a tag behave very similarly to a div, with the exception that you cannot nest other block tags inside it. If it suits your markup, set display:block on your a tag and size / float it however you like.

If you renege on your question's premise that you need to avoid javascript, as others have pointed our you can use the onClick event handler. jQuery is a popular choice for making this easy and maintainable.

Update:

In HTML5, placing a <div> inside an <a> is valid.

See http://dev.w3.org/html5/markup/a.html#a-changes (thanks Damien)

How to programmatically move, copy and delete files and directories on SD?

Use standard Java I/O. Use Environment.getExternalStorageDirectory() to get to the root of external storage (which, on some devices, is an SD card).

C# elegant way to check if a property's property is null

Short Extension Method:

public static TResult IfNotNull<TInput, TResult>(this TInput o, Func<TInput, TResult> evaluator)
  where TResult : class where TInput : class
{
  if (o == null) return null;
  return evaluator(o);
}

Using

PropertyC value = ObjectA.IfNotNull(x => x.PropertyA).IfNotNull(x => x.PropertyB).IfNotNull(x => x.PropertyC);

This simple extension method and much more you can find on http://devtalk.net/csharp/chained-null-checks-and-the-maybe-monad/

EDIT:

After using it for moment I think the proper name for this method should be IfNotNull() instead of original With().

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

This worked for me in a Windows box:

set HTTP_PROXY=http://server:port
set HTTP_PROXY_USER=username
set HTTP_PROXY_PASS=userparssword
set HTTPS_PROXY=http://server:port
set HTTPS_PROXY_USER=username
set HTTPS_PROXY_PASS=userpassword

I have a batch file with these lines that I use to set environment values when I need it.

The trick, in my case, was HTTPS_PROXY sets. Without them, I always got a 407 proxy authentication error.

linux script to kill java process

Use jps to list running java processes. The command returns the process id along with the main class. You can use kill command to kill the process with the returned id or use following one liner script.

kill $(jps | grep <MainClass> | awk '{print $1}')

MainClass is a class in your running java program which contains the main method.

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

Verify what are you attempting to write. I was having the same issue, but I realized i was trying to write a byte array with length of 0.

It doesn't make sense to me, but I get: "Access to the path "

The total number of locks exceeds the lock table size

in windows: if you have mysql workbench. Go to server status. find the location of running server file in my case it was:

C:\ProgramData\MySQL\MySQL Server 5.7

open my.ini file and find the buffer_pool_size. Set the value high. default value is 8M. This is how i fixed this problem

Pandas sort by group aggregate and column

Here's a more concise approach...

df['a_bsum'] = df.groupby('A')['B'].transform(sum)
df.sort(['a_bsum','C'], ascending=[True, False]).drop('a_bsum', axis=1)

The first line adds a column to the data frame with the groupwise sum. The second line performs the sort and then removes the extra column.

Result:

    A       B           C
5   baz     -2.301539   True
2   baz     -0.528172   False
1   bar     -0.611756   True
4   bar      0.865408   False
3   foo     -1.072969   True
0   foo      1.624345   False

NOTE: sort is deprecated, use sort_values instead

Read XLSX file in Java

I had to do this in .NET and I couldn't find any API's out there. My solution was to unzip the .xlsx, and dive right into manipulating the XML. It's not so bad once you create your helper classes and such.

There are some "gotchas" like the nodes all have to be sorted according to the way excel expects them, that I didn't find in the official docs. Excel has its own date timestamping, so you'll need to make a conversion formula.

REST API Best practice: How to accept list of parameter values as input

A Step Back

First and foremost, REST describes a URI as a universally unique ID. Far too many people get caught up on the structure of URIs and which URIs are more "restful" than others. This argument is as ludicrous as saying naming someone "Bob" is better than naming him "Joe" – both names get the job of "identifying a person" done. A URI is nothing more than a universally unique name.

So in REST's eyes arguing about whether ?id=["101404","7267261"] is more restful than ?id=101404,7267261 or \Product\101404,7267261 is somewhat futile.

Now, having said that, many times how URIs are constructed can usually serve as a good indicator for other issues in a RESTful service. There are a couple of red flags in your URIs and question in general.

Suggestions

  1. Multiple URIs for the same resource and Content-Location

    We may want to accept both styles but does that flexibility actually cause more confusion and head aches (maintainability, documentation, etc.)?

    URIs identify resources. Each resource should have one canonical URI. This does not mean that you can't have two URIs point to the same resource but there are well defined ways to go about doing it. If you do decide to use both the JSON and list based formats (or any other format) you need to decide which of these formats is the main canonical URI. All responses to other URIs that point to the same "resource" should include the Content-Location header.

    Sticking with the name analogy, having multiple URIs is like having nicknames for people. It is perfectly acceptable and often times quite handy, however if I'm using a nickname I still probably want to know their full name – the "official" way to refer to that person. This way when someone mentions someone by their full name, "Nichloas Telsa", I know they are talking about the same person I refer to as "Nick".

  2. "Search" in your URI

    A more complex case is when we want to offer more complex inputs. For example, if we want to allow multiple filters on search...

    A general rule of thumb of mine is, if your URI contains a verb, it may be an indication that something is off. URI's identify a resource, however they should not indicate what we're doing to that resource. That's the job of HTTP or in restful terms, our "uniform interface".

    To beat the name analogy dead, using a verb in a URI is like changing someone's name when you want to interact with them. If I'm interacting with Bob, Bob's name doesn't become "BobHi" when I want to say Hi to him. Similarly, when we want to "search" Products, our URI structure shouldn't change from "/Product/..." to "/Search/...".

Answering Your Initial Question

  1. Regarding ["101404","7267261"] vs 101404,7267261: My suggestion here is to avoid the JSON syntax for simplicity's sake (i.e. don't require your users do URL encoding when you don't really have to). It will make your API a tad more usable. Better yet, as others have recommended, go with the standard application/x-www-form-urlencoded format as it will probably be most familiar to your end users (e.g. ?id[]=101404&id[]=7267261). It may not be "pretty", but Pretty URIs does not necessary mean Usable URIs. However, to reiterate my initial point though, ultimately when speaking about REST, it doesn't matter. Don't dwell too heavily on it.

  2. Your complex search URI example can be solved in very much the same way as your product example. I would recommend going the application/x-www-form-urlencoded format again as it is already a standard that many are familiar with. Also, I would recommend merging the two.

Your URI...

/Search?term=pumas&filters={"productType":["Clothing","Bags"],"color":["Black","Red"]}    

Your URI after being URI encoded...

/Search?term=pumas&filters=%7B%22productType%22%3A%5B%22Clothing%22%2C%22Bags%22%5D%2C%22color%22%3A%5B%22Black%22%2C%22Red%22%5D%7D

Can be transformed to...

/Product?term=pumas&productType[]=Clothing&productType[]=Bags&color[]=Black&color[]=Red

Aside from avoiding the requirement of URL encoding and making things look a bit more standard, it now homogenizes the API a bit. The user knows that if they want to retrieve a Product or List of Products (both are considered a single "resource" in RESTful terms), they are interested in /Product/... URIs.

How do I redirect to another webpage?

I just add another way:

To redirect for any specific page/links of your site to another page, just add this line of code:

<script>
    if(window.location.href == 'old_url')
    {
        window.location.href="new_url";
    }

    // Another URL redirect
    if(window.location.href == 'old_url2')
    {
        window.location.href="new_url2";
    }
</script>

For a real life example,

<script>
    if(window.location.href == 'https://old-site.com')
    {
        window.location.href="https://new-site.com";
    }

    // Another URL redirect
    if(window.location.href == 'https://old-site.com/simple-post.html')
    {
        window.location.href="https://new-site.com/simple-post.html";
    }
</script>

By using this simple code, you can redirect full site or any single page.

Rename a column in MySQL

In Server version: 5.6.34 MySQL Community Server

ALTER TABLE table_name
CHANGE COLUMN old_column_name new_column_name data_type;

Converting a Date object to a calendar object

it's so easy...converting a date to calendar like this:

Calendar cal=Calendar.getInstance();
DateFormat format=new SimpleDateFormat("yyyy/mm/dd");
format.format(date);
cal=format.getCalendar();

How do I get to IIS Manager?

To open IIS Manager, click Start, type inetmgr in the Search Programs and Files box, and then press ENTER.

if the IIS Manager doesn't open that means you need to install it.

So, Follow the instruction at this link: https://docs.microsoft.com/en-us/iis/install/installing-iis-7/installing-iis-on-windows-vista-and-windows-7

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

How do I get countifs to select all non-blank cells in Excel?

You can try this :

=COUNTIF(Data!A2:A300,"<>"&"")

failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2

Failed to find: com.android.support:appcompat-v7:22.0.0

The "I literally tried everything else" answer:

This problem will also occur if you don't have an upto date Android Support Library and Android Support Repository. Just install using the SDK manager.

Remove a child with a specific attribute, in SimpleXML for PHP

Just unset the node:

$str = <<<STR
<a>
  <b>
    <c>
    </c>
  </b>
</a>
STR;

$xml = simplexml_load_string($str);
unset($xml –> a –> b –> c); // this would remove node c
echo $xml –> asXML(); // xml document string without node c

This code was taken from How to delete / remove nodes in SimpleXML.

How to call python script on excel vba?

This code will works:

 your_path= ActiveWorkbook.Path & "\your_python_file.py" 
 Shell "RunDll32.Exe Url.Dll,FileProtocolHandler " & your_path, vbNormalFocus 

ActiveWorkbook.Path return the current directory of the workbook. The shell command open the file through the shell of Windows.

T-SQL - function with default parameters

You can call it three ways - with parameters, with DEFAULT and via EXECUTE

SET NOCOUNT ON;

DECLARE
@Table  SYSNAME = 'YourTable',
@Schema SYSNAME = 'dbo',
@Rows   INT;

SELECT dbo.TableRowCount( @Table, @Schema )

SELECT dbo.TableRowCount( @Table, DEFAULT )

EXECUTE @Rows = dbo.TableRowCount @Table

SELECT @Rows

how to download image from any web page in java

   // Do you want to download an image?
   // But are u denied access?
   // well here is the solution.

    public static void DownloadImage(String search, String path) {

    // This will get input data from the server
    InputStream inputStream = null;

    // This will read the data from the server;
    OutputStream outputStream = null;

    try {
        // This will open a socket from client to server
        URL url = new URL(search);

       // This user agent is for if the server wants real humans to visit
        String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";

       // This socket type will allow to set user_agent
        URLConnection con = url.openConnection();

        // Setting the user agent
        con.setRequestProperty("User-Agent", USER_AGENT);

        // Requesting input data from server
        inputStream = con.getInputStream();

        // Open local file writer
        outputStream = new FileOutputStream(path);

        // Limiting byte written to file per loop
        byte[] buffer = new byte[2048];

        // Increments file size
        int length;

        // Looping until server finishes
        while ((length = inputStream.read(buffer)) != -1) {
            // Writing data
            outputStream.write(buffer, 0, length);
        }
    } catch (Exception ex) {
        Logger.getLogger(WebCrawler.class.getName()).log(Level.SEVERE, null, ex);
     }

     // closing used resources
     // The computer will not be able to use the image
     // This is a must

     outputStream.close();
     inputStream.close();
}

What's the safest way to iterate through the keys of a Perl hash?

I always use method 2 as well. The only benefit of using each is if you're just reading (rather than re-assigning) the value of the hash entry, you're not constantly de-referencing the hash.

Firebase FCM notifications click_action payload

You can handle all your actions in function of your message in onMessageReceived() in your service extending FirebaseMessagingService. In order to do that, you must send a message containing exclusively data, using for example Advanced REST client in Chrome. Then you send a POST to https://fcm.googleapis.com/fcm/send using in "Raw headers":

Content-Type: application/json Authorization: key=YOUR_PERSONAL_FIREBASE_WEB_API_KEY

And a json message in the field "Raw payload".

Warning, if there is the field "notification" in your json, your message will never be received when app in background in onMessageReceived(), even if there is a data field ! For example, doing that, message work just if app in foreground:

{
    "condition": " 'Symulti' in topics || 'SymultiLite' in topics",
    "priority" : "normal",
    "time_to_live" : 0,
    "notification" : {
        "body" : "new Symulti update !",
        "title" : "new Symulti update !",
        "icon" : "ic_notif_symulti"
    },
    "data" : {
        "id" : 1,
        "text" : "new Symulti update !"
    }
}

In order to receive your message in all cases in onMessageReceived(), simply remove the "notification" field from your json !

Example:

{
    "condition": " 'Symulti' in topics || 'SymultiLite' in topics",
    "priority" : "normal",
    "time_to_live" : 0,,
    "data" : {
        "id" : 1,
        "text" : "new Symulti update !",
        "link" : "href://www.symulti.com"
    }
}

and in your FirebaseMessagingService :

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
      String message = "";
      obj = remoteMessage.getData().get("text");
      if (obj != null) {
        try {
          message = obj.toString();
        } catch (Exception e) {
          message = "";
          e.printStackTrace();
        }
      }

      String link = "";
      obj = remoteMessage.getData().get("link");
      if (obj != null) {
        try {
          link = (String) obj;
        } catch (Exception e) {
          link = "";
          e.printStackTrace();
        }
      }

      Intent intent;
      PendingIntent pendingIntent;
      if (link.equals("")) { // Simply run your activity
        intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      } else { // open a link
        String url = "";
        if (!link.equals("")) {
          intent = new Intent(Intent.ACTION_VIEW);
          intent.setData(Uri.parse(link));
          intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }
      }
      pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
          PendingIntent.FLAG_ONE_SHOT);


      NotificationCompat.Builder notificationBuilder = null;

      try {
        notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_notif_symulti)          // don't need to pass icon with your message if it's already in your app !
            .setContentTitle(URLDecoder.decode(getString(R.string.app_name), "UTF-8"))
            .setContentText(URLDecoder.decode(message, "UTF-8"))
            .setAutoCancel(true)
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
            .setContentIntent(pendingIntent);
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }

        if (notificationBuilder != null) {
          NotificationManager notificationManager =
              (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
          notificationManager.notify(id, notificationBuilder.build());
        } else {
          Log.d(TAG, "error NotificationManager");
        }
      }
    }
}

Enjoy !

How do I hide javascript code in a webpage?

Approach i used some years ago -

We need a jsp file , a servlet java file and a filter java file.

Give access of jsp file to user. User type url of jsp file .

Case 1 -

  • Jsp file will redirect user to Servlet .
  • Servlet will execute core script part embedded within xxxxx.js file and
  • Using Printwriter , it will render the response to user .

  • Meanwhile, Servlet will create a key file .

  • When servlet try to execute the xxxx.js file within it , Filter
    will activate and will detect key file exist and hence delete key
    file .

Thus one cycle is over.

In short ,key file will created by server and will be immediatly deleted by filter .

This will happen upon every hit .

Case 2 -

  • If user try to obtain the page source and directly click on xxxxxxx.js file , Filter will detect that key file does not exist .
  • It means the request has not come from any servlet. Hence , It will block the request chain .

Instead of File creation , one may use setting value in session variable .

CodeIgniter - How to return Json response from controller

This is not your answer and this is an alternate way to process the form submission

$('.signinform').click(function(e) { 
      e.preventDefault();
      $.ajax({
      type: "POST",
      url: 'index.php/user/signin', // target element(s) to be updated with server response 
      dataType:'json',
      success : function(response){ console.log(response); alert(response)}
     });
}); 

Reading a text file with SQL Server

if you want to read the file into a table at one time you should use BULK INSERT. ON the other hand if you preffer to parse the file line by line to make your own checks, you should take a look at this web: https://www.simple-talk.com/sql/t-sql-programming/reading-and-writing-files-in-sql-server-using-t-sql/ It is possible that you need to activate your xp_cmdshell or other OLE Automation features. Simple Google it and the script will appear. Hope to be useful.

PHP: Limit foreach() statement?

you should use the break statement

usually it's use this way

$i = 0;
foreach($data as $key => $row){
    if(++$i > 2) break;
}

on the same fashion the continue statement exists if you need to skip some items.

How to check whether a given string is valid JSON in Java

You can try below code, worked for me:

 import org.json.JSONObject;
 import org.json.JSONTokener;

 public static JSONObject parseJsonObject(String substring)
 {
  return new JSONObject(new JSONTokener(substring));
 }

How to extract text from a string using sed?

Try using rextract. It will let you extract text using a regular expression and reformat it.

Example:

$ echo "This is 02G05 a test string 20-Jul-2012" | ./rextract '([\d]+G[\d]+)' '${1}'

2G05

How to call a function within class?

Since these are member functions, call it as a member function on the instance, self.

def isNear(self, p):
    self.distToPoint(p)
    ...

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

ipynb import another ipynb file

Please make sure that you also add a __init__.py file in the package where all your other .ipynb files are located.

This is in addition to the nbviewer link that minrk and syi provided above.

I also had some similar problem and then I wrote the solution as well as a link to my public google drive folder which has a working example :)

My Stackoverflow post with step by step experimentation and Solution:

Jupyter Notebook: Import .ipynb file and access it's method in other .ipynb file giving error

Hope this will help others as well. Thanks all!

Casting LinkedHashMap to Complex Object

I had similar Issue where we have GenericResponse object containing list of values

 ResponseEntity<ResponseDTO> responseEntity = restTemplate.exchange(
                redisMatchedDriverUrl,
                HttpMethod.POST,
                requestEntity,
                ResponseDTO.class
        );

Usage of objectMapper helped in converting LinkedHashMap into respective DTO objects

 ObjectMapper mapper = new ObjectMapper();

 List<DriverLocationDTO> driverlocationsList = mapper.convertValue(responseDTO.getData(), new TypeReference<List<DriverLocationDTO>>() { });

When is each sorting algorithm used?

What the provided links to comparisons/animations do not consider is when the amount of data exceed available memory --- at which point the number of passes over the data, i.e. I/O-costs, dominate the runtime. If you need to do that, read up on "external sorting" which usually cover variants of merge- and heap sorts.

http://corte.si/posts/code/visualisingsorting/index.html and http://corte.si/posts/code/timsort/index.html also have some cool images comparing various sorting algorithms.

Python csv string to array

The official doc for csv.reader() https://docs.python.org/2/library/csv.html is very helpful, which says

file objects and list objects are both suitable

import csv

text = """1,2,3
a,b,c
d,e,f"""

lines = text.splitlines()
reader = csv.reader(lines, delimiter=',')
for row in reader:
    print('\t'.join(row))

How to get named excel sheets while exporting from SSRS

There is no direct way. You either export XML and then right an XSLT to format it properly (this is the hard way). An easier way is to write multiple reports with no explicit page breaks so each exports into one sheet only in excel and then write a script that would merge for you. Either way it requires a postprocessing step.

Using external images for CSS custom cursors

I found out that you need to add the pointer eg:

div{
    cursor: url('cursorurl.png'), pointer;
}

Powershell send-mailmessage - email to multiple recipients

That's right, each address needs to be quoted. If you have multiple addresses listed on the command line, the Send-MailMessage likes it if you specify both the human friendly and the email address parts.

How can I remove a substring from a given String?

private static void replaceChar() {
    String str = "hello world";
    final String[] res = Arrays.stream(str.split(""))
            .filter(s -> !s.equalsIgnoreCase("o"))
            .toArray(String[]::new);
    System.out.println(String.join("", res));
}

In case you have some complicated logic to filter the char, just another way instead of replace().

RuntimeError on windows trying python multiprocessing

In my case it was a simple bug in the code, using a variable before it was created. Worth checking that out before trying the above solutions. Why I got this particular error message, Lord knows.

How do I format a date with Dart?

You can also specify the date format like stated earlier: https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html

import 'package:intl/intl.dart';
String formatDate(DateTime date) => new DateFormat("MMMM d").format(date);

Produces: March 4

Redirect to external URL with return in laravel

You should be able to redirect to the url like this

return Redirect::to($url);

You can read about Redirects in the Laravel docs here.

How to use and style new AlertDialog from appCompat 22.1 and above

If you're like me you just want to modify some of the colors in AppCompat, and the only color you need to uniquely change in the dialog is the background. Then all you need to do is set a color for colorBackgroundFloating.

Here's my basic theme that simply modifies some colors with no nested themes:

    <style name="AppTheme" parent="Theme.AppCompat">
        <item name="colorPrimary">@color/theme_colorPrimary</item>
        <item name="colorPrimaryDark">@color/theme_colorPrimaryDark</item>
        <item name="colorAccent">@color/theme_colorAccent</item>
        <item name="colorControlActivated">@color/theme_colorControlActivated</item>
        <item name="android:windowBackground">@color/theme_bg</item>
        <item name="colorBackgroundFloating">@color/theme_dialog_bg</item><!-- Dialog background color -->
        <item name="colorButtonNormal">@color/theme_colorPrimary</item>
        <item name="colorControlHighlight">@color/theme_colorAccent</item>
    </style>

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

Base64 Decoding in iOS 7+

Swift 3+

let plainString = "foo"

Encoding

let plainData = plainString.data(using: .utf8)
let base64String = plainData?.base64EncodedString()
print(base64String!) // Zm9v

Decoding

if let decodedData = Data(base64Encoded: base64String!),
   let decodedString = String(data: decodedData, encoding: .utf8) {
  print(decodedString) // foo
}

Swift < 3

let plainString = "foo"

Encoding

let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
print(base64String!) // Zm9v

Decoding

let decodedData = NSData(base64EncodedString: base64String!, options: NSDataBase64DecodingOptions(rawValue: 0))
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
print(decodedString) // foo

Objective-C

NSString *plainString = @"foo";

Encoding

NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
NSLog(@"%@", base64String); // Zm9v

Decoding

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(@"%@", decodedString); // foo 

Cannot find java. Please use the --jdkhome switch

What worked for me is:

  • make sure java path is available:
$ which java
/usr/bin/java
  • then in etc/netbeans.conf make sure netbeans_jdkhome is commented out
  • in Finder go to /bin/ click on netbeans (terminal icon)

You would expect ./netbeans --jdkhome=/usr/bin/java to work, but it doesn't for some reason.

Select SQL results grouped by weeks

Declare @DatePeriod datetime
Set @DatePeriod = '2011-05-30'

Select  ProductName,
        IsNull([1],0) as 'Week 1',
        IsNull([2],0) as 'Week 2',
        IsNull([3],0) as 'Week 3',
        IsNull([4],0) as 'Week 4',
        IsNull([5], 0) as 'Week 5'
From 
(
Select  ProductName,
        DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, '2011-05-30'), 0), '2011-05-30') +1 as [Weeks],
        Sale as 'Sale'
From dbo.WeekReport

-- Only get rows where the date is the same as the DatePeriod
-- i.e DatePeriod is 30th May 2011 then only the weeks of May will be calculated
Where DatePart(Month, '2011-05-30')= DatePart(Month, @DatePeriod)
)p 
Pivot (Sum(Sale) for Weeks in ([1],[2],[3],[4],[5])) as pv

OUTPUT LOOK LIKE THIS

a   0   0   0   0   20
b   0   0   0   0   4
c   0   0   0   0   3

How is "mvn clean install" different from "mvn install"?

You can call more than one target goal with maven. mvn clean install calls clean first, then install. You have to clean manually, because clean is not a standard target goal and not executed automatically on every install.

clean removes the target folder - it deletes all class files, the java docs, the jars, reports and so on. If you don't clean, then maven will only "do what has to be done", like it won't compile classes when the corresponding source files haven't changed (in brief).

we call it target in ant and goal in maven

What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

size_t is defined by the C standard to be the unsigned integer return type of the sizeof operator (C99 6.3.5.4.4), and the argument of malloc and friends (C99 7.20.3.3 etc). The actual range is set such that the maximum (SIZE_MAX) is at least 65535 (C99 7.18.3.2).

However, this doesn't let us determine sizeof(size_t). The implementation is free to use any representation it likes for size_t - so there is no upper bound on size - and the implementation is also free to define a byte as 16-bits, in which case size_t can be equivalent to unsigned char.

Putting that aside, however, in general you'll have 32-bit size_t on 32-bit programs, and 64-bit on 64-bit programs, regardless of the data model. Generally the data model only affects static data; for example, in GCC:

`-mcmodel=small'
     Generate code for the small code model: the program and its
     symbols must be linked in the lower 2 GB of the address space.
     Pointers are 64 bits.  Programs can be statically or dynamically
     linked.  This is the default code model.

`-mcmodel=kernel'
     Generate code for the kernel code model.  The kernel runs in the
     negative 2 GB of the address space.  This model has to be used for
     Linux kernel code.

`-mcmodel=medium'
     Generate code for the medium model: The program is linked in the
     lower 2 GB of the address space but symbols can be located
     anywhere in the address space.  Programs can be statically or
     dynamically linked, but building of shared libraries are not
     supported with the medium model.

`-mcmodel=large'
     Generate code for the large model: This model makes no assumptions
     about addresses and sizes of sections.

You'll note that pointers are 64-bit in all cases; and there's little point to having 64-bit pointers but not 64-bit sizes, after all.

What does mscorlib stand for?

It stands for

Microsoft's Common Object Runtime Library

and it is the primary assembly for the Framework Common Library.

It contains the following namespaces:

 System
 System.Collections
 System.Configuration.Assemblies
 System.Diagnostics
 System.Diagnostics.SymbolStore
 System.Globalization
 System.IO
 System.IO.IsolatedStorage
 System.Reflection
 System.Reflection.Emit
 System.Resources
 System.Runtime.CompilerServices
 System.Runtime.InteropServices
 System.Runtime.InteropServices.Expando
 System.Runtime.Remoting
 System.Runtime.Remoting.Activation
 System.Runtime.Remoting.Channels
 System.Runtime.Remoting.Contexts
 System.Runtime.Remoting.Lifetime
 System.Runtime.Remoting.Messaging
 System.Runtime.Remoting.Metadata
 System.Runtime.Remoting.Metadata.W3cXsd2001
 System.Runtime.Remoting.Proxies
 System.Runtime.Remoting.Services
 System.Runtime.Serialization
 System.Runtime.Serialization.Formatters
 System.Runtime.Serialization.Formatters.Binary
 System.Security
 System.Security.Cryptography
 System.Security.Cryptography.X509Certificates
 System.Security.Permissions
 System.Security.Policy
 System.Security.Principal
 System.Text
 System.Threading
 Microsoft.Win32 

Interesting info about MSCorlib:

  • The .NET 2.0 assembly will reference and use the 2.0 mscorlib.The .NET 1.1 assembly will reference the 1.1 mscorlib but will use the 2.0 mscorlib at runtime (due to hard-coded version redirects in theruntime itself)
  • In GAC there is only one version of mscorlib, you dont find 1.1 version on GAC even if you have 1.1 framework installed on your machine. It would be good if somebody can explain why MSCorlib 2.0 alone is in GAC whereas 1.x version live inside framework folder
  • Is it possible to force a different runtime to be loaded by the application by making a config setting in your app / web.config? you won’t be able to choose the CLR version by settings in the ConfigurationFile – at that point, a CLR will already be running, and there can only be one per process. Immediately after the CLR is chosen the MSCorlib appropriate for that CLR is loaded.

Converting String array to java.util.List

As of Java 8 and Stream API you can use Arrays.stream and Collectors.toList:

String[] array = new String[]{"a", "b", "c"};
List<String> list = Arrays.stream(array).collect(Collectors.toList());

This is practical especially if you intend to perform further operations on the list.

String[] array = new String[]{"a", "bb", "ccc"};
List<String> list = Arrays.stream(array)
                          .filter(str -> str.length() > 1)
                          .map(str -> str + "!")
                          .collect(Collectors.toList());

How to Generate Unique Public and Private Key via RSA

When you use a code like this:

using (var rsa = new RSACryptoServiceProvider(1024))
{
   // Do something with the key...
   // Encrypt, export, etc.
}

.NET (actually Windows) stores your key in a persistent key container forever. The container is randomly generated by .NET

This means:

  1. Any random RSA/DSA key you have EVER generated for the purpose of protecting data, creating custom X.509 certificate, etc. may have been exposed without your awareness in the Windows file system. Accessible by anyone who has access to your account.

  2. Your disk is being slowly filled with data. Normally not a big concern but it depends on your application (e.g. it might generates hundreds of keys every minute).

To resolve these issues:

using (var rsa = new RSACryptoServiceProvider(1024))
{
   try
   {
      // Do something with the key...
      // Encrypt, export, etc.
   }
   finally
   {
      rsa.PersistKeyInCsp = false;
   }
}

ALWAYS

Shuffle an array with python, randomize array item order with python

# arr = numpy array to shuffle

def shuffle(arr):
    a = numpy.arange(len(arr))
    b = numpy.empty(1)
    for i in range(len(arr)):
        sel = numpy.random.random_integers(0, high=len(a)-1, size=1)
        b = numpy.append(b, a[sel])
        a = numpy.delete(a, sel)
    b = b[1:].astype(int)
    return arr[b]

What is pipe() function in Angular

Two very different types of Pipes Angular - Pipes and RxJS - Pipes

Angular-Pipe

A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's birthday property into a human-friendly date.

import { Component } from '@angular/core';

@Component({
  selector: 'app-hero-birthday',
  template: `<p>The hero's birthday is {{ birthday | date }}</p>`
})
export class HeroBirthdayComponent {
  birthday = new Date(1988, 3, 15); // April 15, 1988
}

RxJS - Pipe

Observable operators are composed using a pipe method known as Pipeable Operators. Here is an example.

import {Observable, range} from 'rxjs';
import {map, filter} from 'rxjs/operators';

const source$: Observable<number> = range(0, 10);

source$.pipe(
    map(x => x * 2),
    filter(x => x % 3 === 0)
).subscribe(x => console.log(x));

The output for this in the console would be the following:

0

6

12

18

For any variable holding an observable, we can use the .pipe() method to pass in one or multiple operator functions that can work on and transform each item in the observable collection.

So this example takes each number in the range of 0 to 10, and multiplies it by 2. Then, the filter function to filter the result down to only the odd numbers.

Java Compare Two Lists

public static boolean compareList(List ls1, List ls2){
    return ls1.containsAll(ls2) && ls1.size() == ls2.size() ? true :false;
     }

public static void main(String[] args) {

    ArrayList<String> one = new ArrayList<String>();
    one.add("one");
    one.add("two");
    one.add("six");

    ArrayList<String> two = new ArrayList<String>();
    two.add("one");
    two.add("six");
    two.add("two");

    System.out.println("Output1 :: " + compareList(one, two));

    two.add("ten");

    System.out.println("Output2 :: " + compareList(one, two));
  }

How to find largest objects in a SQL Server database?

I've found this query also very helpful in SqlServerCentral, here is the link to original post

Sql Server largest tables

  select name=object_schema_name(object_id) + '.' + object_name(object_id)
, rows=sum(case when index_id < 2 then row_count else 0 end)
, reserved_kb=8*sum(reserved_page_count)
, data_kb=8*sum( case 
     when index_id<2 then in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count 
     else lob_used_page_count + row_overflow_used_page_count 
    end )
, index_kb=8*(sum(used_page_count) 
    - sum( case 
           when index_id<2 then in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count 
        else lob_used_page_count + row_overflow_used_page_count 
        end )
     )    
, unused_kb=8*sum(reserved_page_count-used_page_count)
from sys.dm_db_partition_stats
where object_id > 1024
group by object_id
order by 
rows desc   

In my database they gave different results between this query and the 1st answer.

Hope somebody finds useful

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

Make sure you have DESERIALIZED objects like DATE/DATETIME etc. If you are directly sending JSON without deserializing it then it can cause this problem.

What is the iPhone 4 user-agent?

You cannot identify the (hardware) version of an iPhone by user agent.

It's only possible to recognize that it's an iPhone and which software versions it's running.

Using the Safari User Agent String

Not even WURLF can.

How to make an Android Spinner with initial text "Select One"?

Seems a banal solution but I usually put simply a TextView in the front of the spinner. The whole Xml looks like this. (hey guys, don't shoot me, I know that some of you don't like this kind of marriage):

<FrameLayout
    android:id="@+id/selectTypesLinear"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <Spinner
        android:id="@+id/spinnerExercises"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:entries="@array/exercise_spinner_entries"
        android:prompt="@string/exercise_spinner_prompt"
     />                         
    <TextView
        android:id="@+id/spinnerSelectText"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Hey! Select this guy!"
        android:gravity="center"
        android:background="#FF000000" />


</FrameLayout>

Then I hide the TextView when an Item was selected. Obviously the background color of the TextView should be the same as the Spinner. Works on Android 4.0. Don't know on older versions.

Yes. Because the Spinner calls setOnItemSelectedListener at the beginning, the hiding of the textview could be a little bit tricky, but can be done this way:

    Boolean controlTouched;

    exerciseSpinner.setOnTouchListener(new OnTouchListener() {


        @Override
        public boolean onTouch(View v, MotionEvent event) {
            controlTouched = true; // I touched it but but not yet selected an Item.
            return false;
        }

    });
    exerciseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            if (controlTouched) { // Are you sure that I touched it with my fingers and not someone else  ?
                spinnerSelText.setVisibility(View.GONE);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }

    });

MVC3 DropDownListFor - a simple example?

     @Html.DropDownListFor(m => m.SelectedValue,Your List,"ID","Values")

Here Value is that object of model where you want to save your Selected Value

Adding text to ImageView in Android

To add a text to your ImageView you can do this:

<RelativeLayout> // Only works inside a RelativeLayout
    <ImageView
        android:id="@+id/myImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/myImageSouce" />

    <TextView
        android:id="@+id/myImageViewText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/myImageView"
        android:layout_alignTop="@+id/myImageView"
        android:layout_alignRight="@+id/myImageView"
        android:layout_alignBottom="@+id/myImageView"
        android:layout_margin="1dp"
        android:gravity="center"
        android:text="Hello"
        android:textColor="#000000" />
 </RelativeLayout>

Templated check for the existence of a class member function?

Strange nobody suggested the following nice trick I saw once on this very site :

template <class T>
struct has_foo
{
    struct S { void foo(...); };
    struct derived : S, T {};

    template <typename V, V> struct W {};

    template <typename X>
    char (&test(W<void (X::*)(), &X::foo> *))[1];

    template <typename>
    char (&test(...))[2];

    static const bool value = sizeof(test<derived>(0)) == 1;
};

You have to make sure T is a class. It seems that ambiguity in the lookup of foo is a substitution failure. I made it work on gcc, not sure if it is standard though.

Illegal character in path at index 16

the install directory can't have space. reinstall the software will correct it

‘ant’ is not recognized as an internal or external command

create a script including the following; (replace the ant and jdk paths with whatever is correct for your machine)

set  PATH=%BASEPATH%
set ANT_HOME=c:\tools\apache-ant-1.9-bin
set JAVA_HOME=c:\tools\jdk7x64
set PATH=%ANT_HOME%\bin;%JAVA_HOME%\bin;%PATH%

run it in shell.

How do I shutdown, restart, or log off Windows via a bat file?

Some additions to the shutdown and rundll32.exe shell32.dll,SHExitWindowsEx n commands.

LOGOFF - allows you to logoff user by sessionid or session name

PSShutdown - requires a download from windows sysinternals.

bootim.exe - windows 10/8 shutdown iu

change/chglogon - prevents new users to login or take another session

NET SESSION /DELETE - ends a session for user

wusa /forcerestart /quiet - windows update manager but also can restart the machine

tsdiscon - disconnects you

rdpinit - logs you out , though I cant find any documentation at the moment

How to programmatically open the Permission Screen for a specific app on Android Marshmallow?

Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);

Description

Settings.ACTION_APPLICATION_DETAILS_SETTINGS
   Opens Details setting page for App. From here user have to manually assign desired permission.

Intent.FLAG_ACTIVITY_NEW_TASK
   Optional. If set then opens Settings Screen(Activity) as new activity. Otherwise, it will be opened in currently running activity.

Uri.fromParts("package", getPackageName(), null)
   Prepares or creates URI, whereas, getPackageName() - returns name of your application package.

intent.setData(uri)
   Don't forget to set this. Otherwise, you will get android.content.ActivityNotFoundException. Because you have set your intent as Settings.ACTION_APPLICATION_DETAILS_SETTINGS and android expects some name to search.

SQL Server: Examples of PIVOTing String data

I had a situation where I was parsing strings and the first two positions of the string in question would be the field names of a healthcare claims coding standard. So I would strip out the strings and get values for F4, UR and UQ or whatnot. This was great on one record or a few records for one user. But when I wanted to see hundreds of records and the values for all usersz it needed to be a PIVOT. This was wonderful especially for exporting lots of records to excel. The specific reporting request I had received was "every time someone submitted a claim for Benadryl, what value did they submit in fields F4, UR, and UQ. I had an OUTER APPLY that created the ColTitle and the value fields below

PIVOT(
  min(value)
  FOR ColTitle in([F4], [UR], [UQ])
 )

VBScript to send email without running Outlook

You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:

Set MyEmail=CreateObject("CDO.Message")

MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."

MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2

'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"

'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 

MyEmail.Configuration.Fields.Update
MyEmail.Send

set MyEmail=nothing

If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update line:

'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username" 
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"

More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm

How to use multiprocessing queue in Python?

Just made a simple and general example for demonstrating passing a message over a Queue between 2 standalone programs. It doesn't directly answer the OP's question but should be clear enough indicating the concept.

Server:

multiprocessing-queue-manager-server.py

import asyncio
import concurrent.futures
import multiprocessing
import multiprocessing.managers
import queue
import sys
import threading
from typing import Any, AnyStr, Dict, Union


class QueueManager(multiprocessing.managers.BaseManager):

    def get_queue(self, ident: Union[AnyStr, int, type(None)] = None) -> multiprocessing.Queue:
        pass


def get_queue(ident: Union[AnyStr, int, type(None)] = None) -> multiprocessing.Queue:
    global q

    if not ident in q:
        q[ident] = multiprocessing.Queue()

    return q[ident]


q: Dict[Union[AnyStr, int, type(None)], multiprocessing.Queue] = dict()
delattr(QueueManager, 'get_queue')


def init_queue_manager_server():
    if not hasattr(QueueManager, 'get_queue'):
        QueueManager.register('get_queue', get_queue)


def serve(no: int, term_ev: threading.Event):
    manager: QueueManager
    with QueueManager(authkey=QueueManager.__name__.encode()) as manager:
        print(f"Server address {no}: {manager.address}")

        while not term_ev.is_set():
            try:
                item: Any = manager.get_queue().get(timeout=0.1)
                print(f"Client {no}: {item} from {manager.address}")
            except queue.Empty:
                continue


async def main(n: int):
    init_queue_manager_server()
    term_ev: threading.Event = threading.Event()
    executor: concurrent.futures.ThreadPoolExecutor = concurrent.futures.ThreadPoolExecutor()

    i: int
    for i in range(n):
        asyncio.ensure_future(asyncio.get_running_loop().run_in_executor(executor, serve, i, term_ev))

    # Gracefully shut down
    try:
        await asyncio.get_running_loop().create_future()
    except asyncio.CancelledError:
        term_ev.set()
        executor.shutdown()
        raise


if __name__ == '__main__':
    asyncio.run(main(int(sys.argv[1])))

Client:

multiprocessing-queue-manager-client.py

import multiprocessing
import multiprocessing.managers
import os
import sys
from typing import AnyStr, Union


class QueueManager(multiprocessing.managers.BaseManager):

    def get_queue(self, ident: Union[AnyStr, int, type(None)] = None) -> multiprocessing.Queue:
        pass


delattr(QueueManager, 'get_queue')


def init_queue_manager_client():
    if not hasattr(QueueManager, 'get_queue'):
        QueueManager.register('get_queue')


def main():
    init_queue_manager_client()

    manager: QueueManager = QueueManager(sys.argv[1], authkey=QueueManager.__name__.encode())
    manager.connect()

    message = f"A message from {os.getpid()}"
    print(f"Message to send: {message}")
    manager.get_queue().put(message)


if __name__ == '__main__':
    main()

Usage

Server:

$ python3 multiprocessing-queue-manager-server.py N

N is a integer indicating how many servers should be created. Copy one of the <server-address-N> output by the server and make it the first argument of each multiprocessing-queue-manager-client.py.

Client:

python3 multiprocessing-queue-manager-client.py <server-address-1>

Result

Server:

Client 1: <item> from <server-address-1>

Gist: https://gist.github.com/89062d639e40110c61c2f88018a8b0e5


UPD: Created a package here.

Server:

import ipcq


with ipcq.QueueManagerServer(address=ipcq.Address.AUTO, authkey=ipcq.AuthKey.AUTO) as server:
    server.get_queue().get()

Client:

import ipcq


client = ipcq.QueueManagerClient(address=ipcq.Address.AUTO, authkey=ipcq.AuthKey.AUTO)
client.get_queue().put('a message')

enter image description here

How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

I had the same problem. Unfortunately I was in wrong catalog level.

I tried to: git push -u origin master -> there was a error

Then I tried: git pull --rebase -> there still was a problem
Finally i change directory cd your_directory

Then I tried again ( git push) and it works!

How to create loading dialogs in Android?

It's a ProgressDialog, with setIndeterminate(true).

From http://developer.android.com/guide/topics/ui/dialogs.html#ProgressDialog

ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "", 
                    "Loading. Please wait...", true);

An indeterminate progress bar doesn't actually show a bar, it shows a spinning activity circle thing. I'm sure you know what I mean :)

Jquery bind double click and single click separately

I've written a jQuery plugin that allow also to delegate the click and dblclick events

// jQuery plugin to bind both single and double click to objects
// parameter 'delegateSelector' is optional and allow to delegate the events
// parameter 'dblclickWait' is optional default is 300
(function($) {
$.fn.multipleClicks = function(delegateSelector, clickFun, dblclickFun, dblclickWait) {
    var obj;
    if (typeof(delegateSelector)==='function' && typeof(clickFun)==='function') {
        dblclickWait = dblclickFun; dblclickFun = clickFun; clickFun = delegateSelector; delegateSelector = null; // If 'delegateSelector' is missing reorder arguments
    } else if (!(typeof(delegateSelector)==='string' && typeof(clickFun)==='function' && typeof(dblclickFun)==='function')) {
        return false;
    }
    return $(this).each(function() {
        $(this).on('click', delegateSelector, function(event) {
            var self = this;
            clicks = ($(self).data('clicks') || 0)+1;
            $(self).data('clicks', clicks);
            if (clicks == 1) {
                setTimeout(function(){
                    if ($(self).data('clicks') == 1) {
                        clickFun.call(self, event); // Single click action
                    } else {
                        dblclickFun.call(self, event); // Double click action
                    }
                    $(self).data('clicks', 0);
                }, dblclickWait || 300);
            }
        });
    });
};
})(jQuery);

When do items in HTML5 local storage expire?

It's not possible to specify expiration. It's completely up to the user.

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Of course, it's possible that something your application stores on the client may not be there later. The user can explicitly get rid of local storage, or the browser may run into space considerations. It's good to program defensively. Generally however things remain "forever" based on some practical definition of that word.

edit — obviously, your own application can actively remove stuff if it decides it's too old. That is, you can explicitly include some sort of timestamp in what you've got saved, and then use that later to decide whether or not information should be flushed.

Running multiple commands with xargs

You can use

cat file.txt | xargs -i  sh -c 'command {} | command2 {} && command3 {}'

{} = variable for each line on the text file

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

Although this is valid in HTML, you can't use an ID starting with an integer in CSS selectors.

As pointed out, you can use getElementById instead, but you can also still achieve the same with a querySelector:

document.querySelector("[id='22']")

Difference between VARCHAR and TEXT in MySQL

There is an important detail that has been omitted in the answer above.

MySQL imposes a limit of 65,535 bytes for the max size of each row. The size of a VARCHAR column is counted towards the maximum row size, while TEXT columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.

Also note that the actual number of bytes required by a VARCHAR field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4 (which you almost certainly should) it will use up even more of your maximum row size.

Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR/TEXT field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)

Reasons to use TEXT:

  • If you want to store a paragraph or more of text
  • If you don't need to index the column
  • If you have reached the row size limit for your table

Reasons to use VARCHAR:

  • If you want to store a few words or a sentence
  • If you want to index the (entire) column
  • If you want to use the column with foreign-key constraints

Using python's mock patch.object to change the return value of a method called within another method

To add to Silfheed's answer, which was useful, I needed to patch multiple methods of the object in question. I found it more elegant to do it this way:

Given the following function to test, located in module.a_function.to_test.py:

from some_other.module import SomeOtherClass

def add_results():
    my_object = SomeOtherClass('some_contextual_parameters')
    result_a = my_object.method_a()
    result_b = my_object.method_b()
    
    return result_a + result_b

To test this function (or class method, it doesn't matter), one can patch multiple methods of the class SomeOtherClass by using patch.object() in combination with sys.modules:

@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
  mocked_other_class().method_a.return_value = 4
  mocked_other_class().method_b.return_value = 7

  self.assertEqual(add_results(), 11)

This works no matter the number of methods of SomeOtherClass you need to patch, with independent results.

Also, using the same patching method, an actual instance of SomeOtherClass can be returned if need be:

@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
  other_class_instance = SomeOtherClass('some_controlled_parameters')
  mocked_other_class.return_value = other_class_instance 
  ...

What is an abstract class in PHP?

An abstract class is a class that contains at least one abstract method, which is a method without any actual code in it, just the name and the parameters, and that has been marked as "abstract".

The purpose of this is to provide a kind of template to inherit from and to force the inheriting class to implement the abstract methods.

An abstract class thus is something between a regular class and a pure interface. Also interfaces are a special case of abstract classes where ALL methods are abstract.

See this section of the PHP manual for further reference.

Checking if any elements in one list are in another

Your original approach can work with a list comprehension:

def listCompare():
  list1 = [1, 2, 3, 4, 5]
  list2 = [5, 6, 7, 8, 9]
  if [item for item in list1 if item in list2]:
    print("Number was found")
  else:
    print("Number not in list")

Verilog generate/genvar in an always block

Within a module, Verilog contains essentially two constructs: items and statements. Statements are always found in procedural contexts, which include anything in between begin..end, functions, tasks, always blocks and initial blocks. Items, such as generate constructs, are listed directly in the module. For loops and most variable/constant declarations can exist in both contexts.

In your code, it appears that you want the for loop to be evaluated as a generate item but the loop is actually part of the procedural context of the always block. For a for loop to be treated as a generate loop it must be in the module context. The generate..endgenerate keywords are entirely optional(some tools require them) and have no effect. See this answer for an example of how generate loops are evaluated.

//Compiler sees this
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
genvar c;

    always @(posedge sysclk) //Procedural context starts here
    begin
        for (c = 0; c < ROWBITS; c = c + 1) begin: test
            temp[c] <= 1'b0; //Still a genvar
        end
    end

jQuery how to bind onclick event to dynamically added HTML element

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>    
<script>
    $(document).ready(function(){
        $(document).on('click', '.close', function(){
            var rowid='row'+this.id;
            var sl = '#tblData tr[id='+rowid+']';
            console.log(sl);
            $(sl).remove();
        });
        $("#addrow").click(function(){
            var row='';
            for(var i=0;i<10;i++){
                row=i;
                row='<tr id=row'+i+'>'
                    +   '<td>'+i+'</td>'
                    +   '<td>ID'+i+'</td>'
                    +   '<td>NAME'+i+'</td>'
                    +   '<td><input class=close type=button id='+i+' value=X></td>'
                    +'</tr>';
                console.log(row);
                $('#tblData tr:last').after(row);
            }
        });
    });

</script>
</head>
  <body>
    <br/><input type="button" id="addrow" value="Create Table"/>
    <table id="tblData" border="1" width="40%">
        <thead>
        <tr>
            <th>Sr</th>
            <th>ID</th>
            <th>Name</th>
            <th>Delete</th>
        </tr>
        </thead>
    </table>
    </body>
 </html>

ListView with OnItemClickListener

Hey check this, works for me... hope it work for u too

If list item contains ImageButton

Problem: OnItemClickListener just doesn’t repond any at all!

Reason: No idea

Solution: in code, set ImageButton's focus to “false”

1: ImageButton button = (ImageButton) convertView.findViewById(R.id.imageButton);

2: button.setFocusable(false);

Shortcut to exit scale mode in VirtualBox

Another solution (poor one do) is exiting VM Box with saving desktop (top option), restart would bring back the screen as it was before the rescale.

Add tooltip to font awesome icon

You should use 'title' attribute along with 'data-toogle' (bootstrap).

For example

<i class="fa fa-info" data-toggle="tooltip" title="Hooray!"></i>Hover over me

and do not forget to add the javascript to display the tooltip

<script>
    $(document).ready(function(){
        $('[data-toggle="tooltip"]').tooltip();   
    });
</script>

How do I change file permissions in Ubuntu

Add -R for recursive:

sudo chmod -R 666 /var/www

How to turn off INFO logging in Spark?

I you want to keep using the logging (Logging facility for Python) you can try splitting configurations for your application and for Spark:

LoggerManager()
logger = logging.getLogger(__name__)
loggerSpark = logging.getLogger('py4j')
loggerSpark.setLevel('WARNING')

jQuery move to anchor location on page load

Did you tried JQuery's scrollTo method? http://demos.flesler.com/jquery/scrollTo/

Or you can extend JQuery and add your custom mentod:

jQuery.fn.extend({
 scrollToMe: function () {
   var x = jQuery(this).offset().top - 100;
   jQuery('html,body').animate({scrollTop: x}, 400);
}});

Then you can call this method like:

$("#header").scrollToMe();

Paste a multi-line Java String in Eclipse

See: Multiple-line-syntax

It also support variables in multiline string, for example:

String name="zzg";
String lines = ""/**~!{
    SELECT * 
        FROM user
        WHERE name="$name"
}*/;
System.out.println(lines);

Output:

SELECT * 
    FROM user
    WHERE name="zzg"

Limit number of characters allowed in form input text field

Add the following to the header:

<script language="javascript" type="text/javascript">
function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    }
}
</script>

    <input type="text" id="sessionNo" name="sessionNum" onKeyDown="limitText(this,5);" 
onKeyUp="limitText(this,5);"" />

Can not find the tag library descriptor of springframework

Here is another case.

We have several portlets in different portlet application war and all of them use spring. So in order to reduce size of each war, we have created shared libraries for spring jars in the WebSphere Portal server.

However, I came across the same issue as above of not having the spring form tags being referred from the jsp files.

In order to resolve, I have copied the spring-form.tld file into the WEB-INF/ directory and redeployed the war and it worked.

Hope it helps for anyone having a similar issue as mine.

C++ pointer to objects

if you want to access a method :

1) while using an object of a class:

Myclass myclass;
myclass.DoSomething();

2) while using a pointer to an object of a class:

Myclass *myclass=&abc;
myclass->DoSomething();

gnuplot plotting multiple line graphs

andyras is completely correct. One minor addition, try this (for example)

plot 'ls.dat' using 4:xtic(1)

This will keep your datafile in the correct order, but also preserve your version tic labels on the x-axis.

Get Substring - everything before certain char

Building on BrainCore's answer:

    int index = 0;   
    str = "223232-1.jpg";

    //Assuming we trust str isn't null 
    if (str.Contains('-') == "true")
    {
      int index = str.IndexOf('-');
    }

    if(index > 0) {
        return str.Substring(0, index);
    }
    else {
       return str;
    }

How do you copy a record in a SQL table but swap out the unique id of the new row?

Ok, I know that it's an old issue but I post my answer anyway.

I like this solution. I only have to specify the identity column(s).

SELECT * INTO TempTable FROM MyTable_T WHERE id = 1;
ALTER TABLE TempTable DROP COLUMN id;
INSERT INTO MyTable_T SELECT * FROM TempTable;
DROP TABLE TempTable;

The "id"-column is the identity column and that's the only column I have to specify. It's better than the other way around anyway. :-)

I use SQL Server. You may want to use "CREATE TABLE" and "UPDATE TABLE" at row 1 and 2. Hmm, I saw that I did not really give the answer that he wanted. He wanted to copy the id to another column also. But this solution is nice for making a copy with a new auto-id.

I edit my solution with the idéas from Michael Dibbets.

use MyDatabase; 
SELECT * INTO #TempTable FROM [MyTable] WHERE [IndexField] = :id;
ALTER TABLE #TempTable DROP COLUMN [IndexField]; 
INSERT INTO [MyTable] SELECT * FROM #TempTable; 
DROP TABLE #TempTable;

You can drop more than one column by separating them with a ",". The :id should be replaced with the id of the row you want to copy. MyDatabase, MyTable and IndexField should be replaced with your names (of course).

How to print to stderr in Python?

In Python 3, one can just use print():

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

almost out of the box:

import sys
print("Hello, world!", file=sys.stderr)

or:

from sys import stderr
print("Hello, world!", file=stderr)

This is straightforward and does not need to include anything besides sys.stderr.

Checking Bash exit status of several commands efficiently

Personally I much prefer to use a lightweight approach, as seen here;

yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }
asuser() { sudo su - "$1" -c "${*:2}"; }

Example usage:

try apt-fast upgrade -y
try asuser vagrant "echo 'uname -a' >> ~/.profile"

Print out the values of a (Mat) matrix in OpenCV C++

I think using the matrix.at<type>(x,y) is not the best way to iterate trough a Mat object! If I recall correctly matrix.at<type>(x,y) will iterate from the beginning of the matrix each time you call it(I might be wrong though). I would suggest using cv::MatIterator_

cv::Mat someMat(1, 4, CV_64F, &someData);;
cv::MatIterator_<double> _it = someMat.begin<double>();
for(;_it!=someMat.end<double>(); _it++){
    std::cout << *_it << std::endl;
}

How to enable scrolling of content inside a modal?

When using Bootstrap modal with skrollr, the modal will become not scrollable.

Problem fixed with stop the touch event from propagating.

$('#modalFooter').on('touchstart touchmove touchend', function(e) {
    e.stopPropagation();
});

more details at Add scroll event to the element inside #skrollr-body

java.nio.file.Path for a classpath resource

This one works for me:

return Paths.get(ClassLoader.getSystemResource(resourceName).toURI());