Programs & Examples On #Svn switch

SVN 'switch' operation to change a working copy association.

What is the difference between a token and a lexeme?

Using "Compilers Principles, Techniques, & Tools, 2nd Ed." (WorldCat) by Aho, Lam, Sethi and Ullman, AKA the Purple Dragon Book,

Lexeme pg. 111

A lexeme is a sequence of characters in the source program that matches the pattern for a token and is identified by the lexical analyzer as an instance of that token.

Token pg. 111

A token is a pair consisting of a token name and an optional attribute value. The token name is an abstract symbol representing a kind of lexical unit, e.g., a particular keyword, or sequence of input characters denoting an identifier. The token names are the input symbols that the parser processes.

Pattern pg. 111

A pattern is a description of the form that the lexemes of a token may take. In the case of a keyword as a token, the pattern is just the sequence of characters that form the keyword. For identifiers and some other tokens, the pattern is more complex structure that is matched by many strings.

Figure 3.2: Examplesof tokens pg.112

[Token]       [Informal Description]                  [Sample Lexemes]
if            characters i, f                         if
else          characters e, l, s, e                   else
comparison    < or > or <= or >= or == or !=          <=, !=
id            letter followed by letters and digits   pi, score, D2
number        any numeric constant                    3.14159, 0, 6.02e23
literal       anything but ", surrounded by "'s       "core dumped"

To better understand this relation to a lexer and parser we will start with the parser and work backwards to the input.

To make it easier to design a parser, a parser does not work with the input directly but takes in a list of tokens generated by a lexer. Looking at the token column in Figure 3.2 we see tokens such as if, else, comparison, id, number and literal; these are names of tokens. Typically with a lexer/parser a token is a structure that holds not only the name of the token, but the characters/symbols that make up the token and the start and end position of the string of characters that make up the token, with the start and end position being used for error reporting, highlighting, etc.

Now the lexer takes the input of characters/symbols and using the rules of the lexer converts the input characters/symbols into tokens. Now people who work with lexer/parser have their own words for things they use often. What you think of as a sequence of characters/symbols that make up a token are what people who use lexer/parsers call lexeme. So when you see lexeme, just think of a sequence of characters/symbols representing a token. In the comparison example, the sequence of characters/symbols can be different patterns such as < or > or else or 3.14, etc.

Another way to think of the relation between the two is that a token is a programming structure used by the parser that has a property called lexeme that holds the character/symbols from the input. Now if you look at most definitions of token in code you may not see lexeme as one of the properties of the token. This is because a token will more likely hold the start and end position of the characters/symbols that represent the token and the lexeme, sequence of characters/symbols can be derived from the start and end position as needed because the input is static.

How to install latest version of Node using Brew

Have you run brew update first? If you don't do that, Homebrew can't update its formulas, and if it doesn't update its formulas it doesn't know how to install the latest versions of software.

Set focus to field in dynamically loaded DIV

The load() function is an asynchronous function. You should set the focus after the load() call finishes, that is in the callback function of load(), because otherwise the element you are referring to by #header, does not yet exist. For example:

$("#display").load("?control=msgs", {}, function() { 
  $('#header').focus();
}); 

I had issues myself even with this solution, so i did a setTimeout in the callback and set the focus in the timeout to make /really/ sure the element exists.

Get records of current month

This query should work for you:

SELECT *
FROM table
WHERE MONTH(columnName) = MONTH(CURRENT_DATE())
AND YEAR(columnName) = YEAR(CURRENT_DATE())

delete word after or around cursor in VIM

Normal mode:

daw : delete the word under the cursor    
caw : delete the word under the cursor and put you in insert mode 

How to view instagram profile picture in full-size?

You can even set the prof. pic size to its high resolution that is '1080x1080'

replace "150x150" with 1080x1080 and remove /vp/ from the link.

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

Django optional url parameters

You can use nested routes

Django <1.8

urlpatterns = patterns(''
    url(r'^project_config/', include(patterns('',
        url(r'^$', ProjectConfigView.as_view(), name="project_config")
        url(r'^(?P<product>\w+)$', include(patterns('',
            url(r'^$', ProductView.as_view(), name="product"),
            url(r'^(?P<project_id>\w+)$', ProjectDetailView.as_view(), name="project_detail")
        ))),
    ))),
)

Django >=1.8

urlpatterns = [
    url(r'^project_config/', include([
        url(r'^$', ProjectConfigView.as_view(), name="project_config")
        url(r'^(?P<product>\w+)$', include([
            url(r'^$', ProductView.as_view(), name="product"),
            url(r'^(?P<project_id>\w+)$', ProjectDetailView.as_view(), name="project_detail")
        ])),
    ])),
]

This is a lot more DRY (Say you wanted to rename the product kwarg to product_id, you only have to change line 4, and it will affect the below URLs.

Edited for Django 1.8 and above

What is a postback?

Postback is essentially when a form is submitted to the same page or script (.php .asp etc) as you are currently on to proccesses the data rather than sending you to a new page.

An example could be a page on a forum (viewpage.php), where you submit a comment and it is submitted to the same page (viewpage.php) and you would then see it with the new content added.

See: http://en.wikipedia.org/wiki/Postback

How can I remove duplicate rows?

Yet another easy solution can be found at the link pasted here. This one easy to grasp and seems to be effective for most of the similar problems. It is for SQL Server though but the concept used is more than acceptable.

Here are the relevant portions from the linked page:

Consider this data:

EMPLOYEE_ID ATTENDANCE_DATE
A001    2011-01-01
A001    2011-01-01
A002    2011-01-01
A002    2011-01-01
A002    2011-01-01
A003    2011-01-01

So how can we delete those duplicate data?

First, insert an identity column in that table by using the following code:

ALTER TABLE dbo.ATTENDANCE ADD AUTOID INT IDENTITY(1,1)  

Use the following code to resolve it:

DELETE FROM dbo.ATTENDANCE WHERE AUTOID NOT IN (SELECT MIN(AUTOID) _
    FROM dbo.ATTENDANCE GROUP BY EMPLOYEE_ID,ATTENDANCE_DATE) 

Is it a bad practice to use an if-statement without curly braces?

One problem with leaving out statement blocks is the else-ambiguity. That is C-inspired languages ignore indentation and so have no way of separating this:

if(one)
    if(two)
        foo();
    else
        bar();

From this:

if(one)
    if(two)
        foo();
else
    bar();

Formatting floats in a numpy array

In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:

In [1]: float_formatter = "{:.2f}".format

The f here means fixed-point format (not 'scientific'), and the .2 means two decimal places (you can read more about string formatting here).

Let's test it out with a float value:

In [2]: float_formatter(1.234567E3)
Out[2]: '1234.57'

To make numpy print all float arrays this way, you can pass the formatter= argument to np.set_printoptions:

In [3]: np.set_printoptions(formatter={'float_kind':float_formatter})

Now numpy will print all float arrays this way:

In [4]: np.random.randn(5) * 10
Out[4]: array([5.25, 3.91, 0.04, -1.53, 6.68]

Note that this only affects numpy arrays, not scalars:

In [5]: np.pi
Out[5]: 3.141592653589793

It also won't affect non-floats, complex floats etc - you will need to define separate formatters for other scalar types.

You should also be aware that this only affects how numpy displays float values - the actual values that will be used in computations will retain their original precision.

For example:

In [6]: a = np.array([1E-9])

In [7]: a
Out[7]: array([0.00])

In [8]: a == 0
Out[8]: array([False], dtype=bool)

numpy prints a as if it were equal to 0, but it is not - it still equals 1E-9.

If you actually want to round the values in your array in a way that affects how they will be used in calculations, you should use np.round, as others have already pointed out.

Bootstrap 3 - jumbotron background image effect

Example: http://bootply.com/103783

One way to achieve this is using a position:fixed container for the background image and place it outside of the .jumbotron. Make the bg container the same height as the .jumbotron and center the background image:

background: url('/assets/example/...jpg') no-repeat center center;

CSS

.bg {
  background: url('/assets/example/bg_blueplane.jpg') no-repeat center center;
  position: fixed;
  width: 100%;
  height: 350px; /*same height as jumbotron */
  top:0;
  left:0;
  z-index: -1;
}

.jumbotron {
  margin-bottom: 0px;
  height: 350px;
  color: white;
  text-shadow: black 0.3em 0.3em 0.3em;
  background:transparent;
}

Then use jQuery to decrease the height of the .jumbtron as the window scrolls. Since the background image is centered in the DIV it will adjust accordingly -- creating a parallax affect.

JavaScript

var jumboHeight = $('.jumbotron').outerHeight();
function parallax(){
    var scrolled = $(window).scrollTop();
    $('.bg').css('height', (jumboHeight-scrolled) + 'px');
}

$(window).scroll(function(e){
    parallax();
});

Demo

http://bootply.com/103783

Table with table-layout: fixed; and how to make one column wider

You could just give the first cell (therefore column) a width and have the rest default to auto

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
  width: 150px;_x000D_
}_x000D_
td+td {_x000D_
  width: auto;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>150px</td>_x000D_
    <td>equal</td>_x000D_
    <td>equal</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_


or alternatively the "proper way" to get column widths might be to use the col element itself

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
.wide {_x000D_
  width: 150px;_x000D_
}
_x000D_
<table>_x000D_
  <col span="1" class="wide">_x000D_
    <tr>_x000D_
      <td>150px</td>_x000D_
      <td>equal</td>_x000D_
      <td>equal</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to select the nth row in a SQL database table?

But really, isn't all this really just parlor tricks for good database design in the first place? The few times I needed functionality like this it was for a simple one off query to make a quick report. For any real work, using tricks like these is inviting trouble. If selecting a particular row is needed then just have a column with a sequential value and be done with it.

List and kill at jobs on UNIX

To delete a job which has not yet run, you need the atrm command. You can use atq command to get its number in the at list.

To kill a job which has already started to run, you'll need to grep for it using:

ps -eaf | grep <command name>

and then use kill to stop it.

A quicker way to do this on most systems is:

pkill <command name>

CSV in Python adding an extra carriage return, on Windows

Note that if you use DictWriter, you will have a new line from the open function and a new line from the writerow function. You can use newline='' within the open function to remove the extra newline.

Correct format specifier to print pointer or address?

Use %p, for "pointer", and don't use anything else*. You aren't guaranteed by the standard that you are allowed to treat a pointer like any particular type of integer, so you'd actually get undefined behaviour with the integral formats. (For instance, %u expects an unsigned int, but what if void* has a different size or alignment requirement than unsigned int?)

*) [See Jonathan's fine answer!] Alternatively to %p, you can use pointer-specific macros from <inttypes.h>, added in C99.

All object pointers are implicitly convertible to void* in C, but in order to pass the pointer as a variadic argument, you have to cast it explicitly (since arbitrary object pointers are only convertible, but not identical to void pointers):

printf("x lives at %p.\n", (void*)&x);

How to get the number of columns from a JDBC ResultSet?

Number of a columns in the result set you can get with code (as DB is used PostgreSQL):

//load the driver for PostgreSQL
Class.forName("org.postgresql.Driver");

String url = "jdbc:postgresql://localhost/test";
Properties props = new Properties();
props.setProperty("user","mydbuser");
props.setProperty("password","mydbpass");
Connection conn = DriverManager.getConnection(url, props);

//create statement
Statement stat = conn.createStatement();

//obtain a result set
ResultSet rs = stat.executeQuery("SELECT c1, c2, c3, c4, c5 FROM MY_TABLE");

//from result set give metadata
ResultSetMetaData rsmd = rs.getMetaData();

//columns count from metadata object
int numOfCols = rsmd.getColumnCount();

But you can get more meta-informations about columns:

for(int i = 1; i <= numOfCols; i++)
{
    System.out.println(rsmd.getColumnName(i));
}

And at least but not least, you can get some info not just about table but about DB too, how to do it you can find here and here.

Android Studio SDK location

I tried the accepted solution but it didn't resolve the issue for me.

I had already installed Android Studio 2-3 years ago, but I uninstalled it at some point. Installing the latest version was giving me an error. I did multiple uninstalls/reinstallations, but the issue persisted.

I found an SDK was available on my machine in %LocalAppData%. I opened the environment variable and deleted all the references of Android like Android Home /Path. I performed the uninstallation of Android Studio and then reinstalled.

This time it worked and installed properly; it is even downloading the other SDK-related files.

Sequence contains no matching element

Well, I'd expect it's this line that's throwing the exception:

var documentRow = _dsACL.Documents.First(o => o.ID == id)

First() will throw an exception if it can't find any matching elements. Given that you're testing for null immediately afterwards, it sounds like you want FirstOrDefault(), which returns the default value for the element type (which is null for reference types) if no matching items are found:

var documentRow = _dsACL.Documents.FirstOrDefault(o => o.ID == id)

Other options to consider in some situations are Single() (when you believe there's exactly one matching element) and SingleOrDefault() (when you believe there's exactly one or zero matching elements). I suspect that FirstOrDefault is the best option in this particular case, but it's worth knowing about the others anyway.

On the other hand, it looks like you might actually be better off with a join here in the first place. If you didn't care that it would do all matches (rather than just the first) you could use:

var query = from target in _lstAcl.Documents
            join source in _dsAcl.Document
            where source.ID.ToString() equals target.ID
            select new { source, target };
foreach (var pair in query)
{
    target.Read = source.Read;
    target.ReadRule = source.ReadRule;
    // etc
}

That's simpler and more efficient IMO.

Even if you do decide to keep the loop, I have a couple of suggestions:

  • Get rid of the outer if. You don't need it, as if Count is zero the for loop body will never execute
  • Use exclusive upper bounds in for loops - they're more idiomatic in C#:

    for (i = 0; i < _lstAcl.Documents.Count; i++)
    
  • Eliminate common subexpressions:

    var target = _lstAcl.Documents[i];
    // Now use target for the rest of the loop body
    
  • Where possible use foreach instead of for to start with:

    foreach (var target in _lstAcl.Documents)
    

Redirect within component Angular 2

This worked for me Angular cli 6.x:

import {Router} from '@angular/router';

constructor(private artistService: ArtistService, private router: Router) { }

  selectRow(id: number): void{
       this.router.navigate([`./artist-detail/${id}`]);

  }

How do I set the classpath in NetBeans?

  1. Right-click your Project.
  2. Select Properties.
  3. On the left-hand side click Libraries.
  4. Under Compile tab - click Add Jar/Folder button.

Or

  1. Expand your Project.
  2. Right-click Libraries.
  3. Select Add Jar/Folder.

How to specify table's height such that a vertical scroll bar appears?

Try using the overflow CSS property. There are also separate properties to define the behaviour of just horizontal overflow (overflow-x) and vertical overflow (overflow-y).

Since you only want the vertical scroll, try this:

table {
  height: 500px;
  overflow-y: scroll;
}

EDIT:

Apparently <table> elements don't respect the overflow property. This appears to be because <table> elements are not rendered as display: block by default (they actually have their own display type). You can force the overflow property to work by setting the <table> element to be a block type:

table {
  display: block;
  height: 500px;
  overflow-y: scroll;
}

Note that this will cause the element to have 100% width, so if you don't want it to take up the entire horizontal width of the page, you need to specify an explicit width for the element as well.

Change all files and folders permissions of a directory to 644/755

This can work too:

chmod -R 755 *  // All files and folders to 755.

chmod -R 644 *.*  // All files will be 644.

MongoDB query multiple collections at once

Perform multiple queries or use embedded documents or look at "database references".

Read only file system on Android

Not all phones and versions of android have things mounted the same.
Limiting options when remounting would be best.

Simply remount as rw (Read/Write):

# mount -o rw,remount /system

Once you are done making changes, remount to ro (read-only):

# mount -o ro,remount /system

How do I remove  from the beginning of a file?

You can open it by PhpStorm and right-click on your file and click on Remove BOM...

How to format a string as a telephone number in C#

using string interpolation and the new array index/range

var p = "1234567890";
var formatted = $"({p[0..3]}) {p[3..6]}-{p[6..10]}"

Output: (123) 456-7890

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

When you establish a connection for a transaction, you acquire a lock before performing the transaction. If not able to acquire the lock, then you try for sometime. If lock is still not obtainable, then lock wait time exceeded error is thrown. Why you will not able to acquire a lock is that you are not closing the connection. So, when you are trying to get a lock second time, you will not be able to acquire the lock as your previous connection is still unclosed and holding the lock.

Solution: close the connection or setAutoCommit(true) (according to your design) to release the lock.

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

Getting random numbers in Java

int max = 50;
int min = 1;

1. Using Math.random()

double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);

This will give you value from 1 to 50 in case of int or 1.0 (inclusive) to 50.0 (exclusive) in case of double

Why?

random() method returns a random number between 0.0 and 0.9..., you multiply it by 50, so upper limit becomes 0.0 to 49.999... when you add 1, it becomes 1.0 to 50.999..., now when you truncate to int, you get 1 to 50. (thanks to @rup in comments). leepoint's awesome write-up on both the approaches.

2. Using Random class in Java.

Random rand = new Random(); 
int value = rand.nextInt(50); 

This will give value from 0 to 49.

For 1 to 50: rand.nextInt((max - min) + 1) + min;

Source of some Java Random awesomeness.

IOS: verify if a point is inside a rect

UIView's pointInside:withEvent: could be a good solution. Will return a boolean value indicating wether or not the given CGPoint is in the UIView instance you are using. Example:

UIView *aView = [UIView alloc]initWithFrame:CGRectMake(0,0,100,100);
CGPoint aPoint = CGPointMake(5,5);
BOOL isPointInsideView = [aView pointInside:aPoint withEvent:nil];

How to fix "set SameSite cookie to none" warning?

As the new feature comes, SameSite=None cookies must also be marked as Secure or they will be rejected.

One can find more information about the change on chromium updates and on this blog post

Note: not quite related directly to the question, but might be useful for others who landed here as it was my concern at first during development of my website:

if you are seeing the warning from question that lists some 3rd party sites (in my case it was google.com, huh) - that means they need to fix it and it's nothing to do with your site. Of course unless the warning mentions your site, in which case adding Secure should fix it.

Android: How do I get string from resources using its name?

Easier way is to use the getString() function within the activity.

String myString = getString(R.string.mystring);

Reference: http://developer.android.com/guide/topics/resources/string-resource.html

I think this feature is added in a recent Android version, anyone who knows the history can comment on this.

How to get class object's name as a string in Javascript?

Shog9 is right that this doesn't make all that much sense to ask, since an object could be referred to by multiple variables. If you don't really care about that, and all you want is to find the name of one of the global variables that refers to that object, you could do the following hack:

function myClass() { 
  this.myName = function () { 
    // search through the global object for a name that resolves to this object
    for (var name in this.global) 
      if (this.global[name] == this) 
        return name 
  } 
}
// store the global object, which can be referred to as this at the top level, in a
// property on our prototype, so we can refer to it in our object's methods
myClass.prototype.global = this
// create a global variable referring to an object
var myVar = new myClass()
myVar.myName() // returns "myVar"

Note that this is an ugly hack, and should not be used in production code. If there is more than one variable referring to an object, you can't tell which one you'll get. It will only search the global variables, so it won't work if a variable is local to a function. In general, if you need to name something, you should pass the name in to the constructor when you create it.

edit: To respond to your clarification, if you need to be able to refer to something from an event handler, you shouldn't be referring to it by name, but instead add a function that refers to the object directly. Here's a quick example that I whipped up that shows something similar, I think, to what you're trying to do:

function myConstructor () {
  this.count = 0
  this.clickme = function () {
    this.count += 1
    alert(this.count)
  }

  var newDiv = document.createElement("div")
  var contents = document.createTextNode("Click me!")

  // This is the crucial part. We don't construct an onclick handler by creating a
  // string, but instead we pass in a function that does what we want. In order to
  // refer to the object, we can't use this directly (since that will refer to the 
  // div when running event handler), but we create an anonymous function with an 
  // argument and pass this in as that argument.
  newDiv.onclick = (function (obj) { 
    return function () {
      obj.clickme()
    }
  })(this)

  newDiv.appendChild(contents)
  document.getElementById("frobnozzle").appendChild(newDiv)

}
window.onload = function () {
  var myVar = new myConstructor()
}

VBA - Select columns using numbers?

In this way, you can start to select data even behind column "Z" and select a lot of columns.

Sub SelectColumNums()
    Dim xCol1 As Integer, xNumOfCols as integer
    xCol1 = 26
    xNumOfCols = 17
    Range(Columns(xCol1), Columns(xCol1 + xNumOfCols)).Select
End Sub

Prevent RequireJS from Caching Required Scripts

The urlArgs solution has problems. Unfortunately you cannot control all proxy servers that might be between you and your user's web browser. Some of these proxy servers can be unfortunately configured to ignore URL parameters when caching files. If this happens, the wrong version of your JS file will be delivered to your user.

I finally gave up and implemented my own fix directly into require.js. If you are willing to modify your version of the requirejs library, this solution might work for you.

You can see the patch here:

https://github.com/jbcpollak/requirejs/commit/589ee0cdfe6f719cd761eee631ce68eee09a5a67

Once added, you can do something like this in your require config:

var require = {
    baseUrl: "/scripts/",
    cacheSuffix: ".buildNumber"
}

Use your build system or server environment to replace buildNumber with a revision id / software version / favorite color.

Using require like this:

require(["myModule"], function() {
    // no-op;
});

Will cause require to request this file:

http://yourserver.com/scripts/myModule.buildNumber.js

On our server environment, we use url rewrite rules to strip out the buildNumber, and serve the correct JS file. This way we don't actually have to worry about renaming all of our JS files.

The patch will ignore any script that specifies a protocol, and it will not affect any non-JS files.

This works well for my environment, but I realize some users would prefer a prefix rather than a suffix, it should be easy to modify my commit to suit your needs.

Update:

In the pull request discussion, the requirejs author suggest this might work as a solution to prefix the revision number:

var require = {
    baseUrl: "/scripts/buildNumber."
};

I have not tried this, but the implication is that this would request the following URL:

http://yourserver.com/scripts/buildNumber.myModule.js

Which might work very well for many people who can use a prefix.

Here are some possible duplicate questions:

RequireJS and proxy caching

require.js - How can I set a version on required modules as part of the URL?

GitHub Error Message - Permission denied (publickey)

I was getting this error. Turns out I had just upgraded OSX to Sierra and my old key was no longer registered.

At first I thought it was "Upgrading to macOS Sierra will break your SSH keys and lock you out of your own servers"

But I had sidestepped that one. Turns out I just had to re-register my existing key:

ssh-add -K

And type the passphrase... done!

How do I get total physical memory size using PowerShell without WMI?

Below gives the total physical memory.

gwmi Win32_OperatingSystem | Measure-Object -Property TotalVisibleMemorySize -Sum | % {[Math]::Round($_.sum/1024/1024)}

How can I install a CPAN module into a local directory?

I strongly recommend Perlbrew. It lets you run multiple versions of Perl, install packages, hack Perl internals if you want to, all regular user permissions.

How to check if image exists with given url?

$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function(){
            //do something depressing
    },
    success: function(){
            //do something cheerful :)
    }
});

from: http://www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06

How to check Grants Permissions at Run-Time?

use Dexter library

Include the library in your build.gradle

dependencies{
    implementation 'com.karumi:dexter:4.2.0'
}

this example requests WRITE_EXTERNAL_STORAGE.

Dexter.withActivity(this)
                .withPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .withListener(new PermissionListener() {
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse response) {
                        // permission is granted, open the camera
                    }

                    @Override
                    public void onPermissionDenied(PermissionDeniedResponse response) {
                        // check for permanent denial of permission
                        if (response.isPermanentlyDenied()) {
                            // navigate user to app settings
                        }
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                }).check();

check this answer here

Show loading screen when navigating between routes in Angular 2

You could also use this existing solution. The demo is here. It looks like youtube loading bar. I just found it and added it to my own project.

How do I get the total number of unique pairs of a set in the database?

TLDR; The formula is n(n-1)/2 where n is the number of items in the set.

Explanation:

To find the number of unique pairs in a set, where the pairs are subject to the commutative property (AB = BA), you can calculate the summation of 1 + 2 + ... + (n-1) where n is the number of items in the set.

The reasoning is as follows, say you have 4 items:

A
B
C
D

The number of items that can be paired with A is 3, or n-1:

AB
AC
AD

It follows that the number of items that can be paired with B is n-2 (because B has already been paired with A):

BC
BD

and so on...

(n-1) + (n-2) + ... + (n-(n-1))

which is the same as

1 + 2 + ... + (n-1)

or

n(n-1)/2

Bytes of a string in Java

There's a method called getBytes(). Use it wisely .

How to get all of the immediate subdirectories in Python

I have to mention the path.py library, which I use very often.

Fetching the immediate subdirectories become as simple as that:

my_dir.dirs()

The full working example is:

from path import Path

my_directory = Path("path/to/my/directory")

subdirs = my_directory.dirs()

NB: my_directory still can be manipulated as a string, since Path is a subclass of string, but providing a bunch of useful methods for manipulating paths

How to find the index of an element in an int array?

/**
     * Method to get the index of the given item from the list
     * @param stringArray
     * @param name
     * @return index of the item if item exists else return -1
     */
    public static int getIndexOfItemInArray(String[] stringArray, String name) {
        if (stringArray != null && stringArray.length > 0) {
            ArrayList<String> list = new ArrayList<String>(Arrays.asList(stringArray));
            int index = list.indexOf(name);
            list.clear();
            return index;
        }
        return -1;
    }

How to trigger event when a variable's value is changed?

Seems to me like you want to create a property.

public int MyProperty
{
    get { return _myProperty; }
    set
    {
        _myProperty = value;
        if (_myProperty == 1)
        {
            // DO SOMETHING HERE
        }
    }
}

private int _myProperty;

This allows you to run some code any time the property value changes. You could raise an event here, if you wanted.

Dynamically replace img src attribute with jQuery

You need to check out the attr method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src with the string specified in the 2nd parameter.

http://api.jquery.com/attr/

A better way to approach replacing a series of images source would be to loop through each and check it's source.

Example:

$('img').each(function () {
  var curSrc = $(this).attr('src');
  if ( curSrc === 'http://example.com/smith.gif' ) {
      $(this).attr('src', 'http://example.com/johnson.gif');
  }
  if ( curSrc === 'http://example.com/williams.gif' ) {
      $(this).attr('src', 'http://example.com/brown.gif');
  }
});

jQuery vs. javascript?

It's all about performance and development speed. Of course, if you are a good programmer and design something that is really tailored to your needs, you might achieve better performance than if you had used a Javascript framework. But do you have the time to do it all by yourself?

My personal opinion is that Javascript is incredibly useful and overused, but that if you really need it, a framework is the way to go.

Now comes the choice of the framework. For what benchmarks are worth, you can find one at http://ejohn.org/files/142/ . It also depends on which plugins are available and what you intend to do with them. I started using jQuery because it seemed to be maintained and well featured, even though it wasn't the fastest at that moment. I do not regret it but I didn't test anything else since then.

JavaFX Panel inside Panel auto resizing

I was designing a GUI in SceneBuilder, trying to make the main container adapt to whatever the window size is. It should always be 100% wide.

This is where you can set these values in SceneBuilder:

AnchorPane Constraints in SceneBuilder

Toggling the dotted/red lines will actually just add/remove the attributes that Korki posted in his solution (AnchorPane.topAnchor etc.).

Create a new workspace in Eclipse

You can create multiple workspaces in Eclipse. You have to just specify the path of the workspace during Eclipse startup. You can even switch workspaces via File?Switch workspace.

You can then import project to your workspace, copy paste project to your new workspace folder, then

File?Import?Existing project in to workspace?select project.

git undo all uncommitted or unsaved changes

Adding this answer because the previous answers permanently delete your changes

The Safe way

git stash -u

Explanation: Stash local changes including untracked changes (-u flag). The command saves your local modifications away and reverts the working directory to match the HEAD commit.

Want to recover the changes later?

git stash pop

Explanation: The command will reapply the changes to the top of the current working tree state.

Want to permanently remove the changes?

git stash drop

Explanation: The command will permanently remove the stashed entry

Link to git stash documentation

if statement in ng-click

From http://php.quicoto.com/inline-ifelse-statement-ngclick-angularjs/, this is how you do it, if you really have to:

ng-click="variable = (condition=='X' ? 'Y' : 'X')"

using batch echo with special characters

You can escape shell metacharacters with ^:

echo ^<?xml version="1.0" encoding="utf-8" ?^> > myfile.xml

Note that since echo is a shell built-in it doesn't follow the usual conventions regarding quoting, so just quoting the argument will output the quotes instead of removing them.

Does JavaScript guarantee object property order?

Property order in normal Objects is a complex subject in Javascript.

While in ES5 explicitly no order has been specified, ES2015 has an order in certain cases. Given is the following object:

o = Object.create(null, {
  m: {value: function() {}, enumerable: true},
  "2": {value: "2", enumerable: true},
  "b": {value: "b", enumerable: true},
  0: {value: 0, enumerable: true},
  [Symbol()]: {value: "sym", enumerable: true},
  "1": {value: "1", enumerable: true},
  "a": {value: "a", enumerable: true},
});

This results in the following order (in certain cases):

Object {
  0: 0,
  1: "1",
  2: "2",
  b: "b",
  a: "a",
  m: function() {},
  Symbol(): "sym"
}
  1. integer-like keys in ascending order
  2. normal keys in insertion order
  3. Symbols in insertion order

Thus, there are three segments, which may alter the insertion order (as happened in the example). And integer-like keys don't stick to the insertion order at all.

The question is, for what methods this order is guaranteed in the ES2015 spec?

The following methods guarantee the order shown:

  • Object.assign
  • Object.defineProperties
  • Object.getOwnPropertyNames
  • Object.getOwnPropertySymbols
  • Reflect.ownKeys

The following methods/loops guarantee no order at all:

  • Object.keys
  • for..in
  • JSON.parse
  • JSON.stringify

Conclusion: Even in ES2015 you shouldn't rely on the property order of normal objects in Javascript. It is prone to errors. Use Map instead.

CreateProcess: No such file or directory

I had the same problem (I'm running cygwin)

Starting a shell through cygwin.bat didn't help, but starting a shell through MingWShell did. Not quite sure why, but I think it had something to do with the extra layer that cygwin puts between the executing script and the underlying filesystem.

I was running pip install from within a virtual env's cygwin to install django sentry..

difference between width auto and width 100 percent

Width 100% : It will make content with 100%. margin, border, padding will be added to this width and element will overflow if any of these added.

Width auto : It will fit the element in available space including margin, border and padding. space remaining after adjusting margin + padding + border will be available width/ height.

Width 100% + box-sizing: border box : It will also fits the element in available space including border, padding (margin will make it overflow the container).

count distinct values in spreadsheet

Link to Working Examples

Solution 0

This can be accompished using pivot tables.

Pivot table Example - Count rows by value

Solution 1

Use the unique formula to get all the distinct values. Then use countif to get the count of each value. See the working example link at the top to see exactly how this is implemented.

Unique Values        Count
=UNIQUE(A3:A8)       =COUNTIF(A3:A8;B3)
                     =COUNTIF(A3:A8;B4)
                     ...

Solution 2

If you setup your data as such:

City    
----    
London   1
Paris    1
London   1
Berlin   1
Rome     1
Paris    1

Then the following will produce the desired result.

=sort(transpose(query(A3:B8,"Select sum(B) pivot (A)")),2,FALSE)

I'm sure there is a way to get rid of the second column since all values will be 1. Not an ideal solution in my opinion.

via http://googledocsforlife.blogspot.com/2011/12/counting-unique-values-of-data-set.html

Other Possibly Helpful Links

Deleting an object in C++

saveLeaves(vec,msh);
I'm assuming takes the msh pointer and puts it inside of vec. Since msh is just a pointer to the memory, if you delete it, it will also get deleted inside of the vector.

Using logging in multiple modules

@Yarkee's solution seemed better. I would like to add somemore to it -

class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances.keys():
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]


class LoggerManager(object):
    __metaclass__ = Singleton

    _loggers = {}

    def __init__(self, *args, **kwargs):
        pass

    @staticmethod
    def getLogger(name=None):
        if not name:
            logging.basicConfig()
            return logging.getLogger()
        elif name not in LoggerManager._loggers.keys():
            logging.basicConfig()
            LoggerManager._loggers[name] = logging.getLogger(str(name))
        return LoggerManager._loggers[name]    


log=LoggerManager().getLogger("Hello")
log.setLevel(level=logging.DEBUG)

So LoggerManager can be a pluggable to the entire application. Hope it makes sense and value.

How to "properly" create a custom object in JavaScript?

To continue off of bobince's answer

In es6 you can now actually create a class

So now you can do:

class Shape {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    toString() {
        return `Shape at ${this.x}, ${this.y}`;
    }
}

So extend to a circle (as in the other answer) you can do:

class Circle extends Shape {
    constructor(x, y, r) {
        super(x, y);
        this.r = r;
    }

    toString() {
        let shapeString = super.toString();
        return `Circular ${shapeString} with radius ${this.r}`;
    }
}

Ends up a bit cleaner in es6 and a little easier to read.


Here is a good example of it in action:

_x000D_
_x000D_
class Shape {_x000D_
  constructor(x, y) {_x000D_
    this.x = x;_x000D_
    this.y = y;_x000D_
  }_x000D_
_x000D_
  toString() {_x000D_
    return `Shape at ${this.x}, ${this.y}`;_x000D_
  }_x000D_
}_x000D_
_x000D_
class Circle extends Shape {_x000D_
  constructor(x, y, r) {_x000D_
    super(x, y);_x000D_
    this.r = r;_x000D_
  }_x000D_
_x000D_
  toString() {_x000D_
    let shapeString = super.toString();_x000D_
    return `Circular ${shapeString} with radius ${this.r}`;_x000D_
  }_x000D_
}_x000D_
_x000D_
let c = new Circle(1, 2, 4);_x000D_
_x000D_
console.log('' + c, c);
_x000D_
_x000D_
_x000D_

How to fully delete a git repository created with init?

true,like mine was stored in USERS,so had to open USERS go to View on you upper left find Options,open it and edit folders'view options in view still to display hidden files/folders,all your folders will be displayed and you can deleted the repo manually,remember to hide the files/folders once done with the delete.

find the array index of an object with a specific key value in underscore

This is to help lodash users. check if your key is present by doing:

hideSelectedCompany(yourKey) {
 return _.findIndex(yourArray, n => n === yourKey) === -1;
}

Add day(s) to a Date object

Note : Use it if calculating / adding days from current date.

Be aware: this answer has issues (see comments)

var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);

It should be like

var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

In case anyone looking for commonly supported formats by server

3g2|3gp|3gp2|3gpp|aac|aaf|aca|accdb|accde|accdt|acx|adt|adts|afm|ai|aif|aifc|aiff|appcache|application|art|asd|asf|asi|asm|asr|asx|atom|au|avi|axs|bas|bcpio|bin|bmp|c|cab|calx|cat|cdf|chm|class|clp|cmx|cnf|cod|cpio|cpp|crd|crl|crt|csh|css|csv|cur|dcr|deploy|der|dib|dir|disco|dll|dllconfig|dlm|doc|docm|docx|dot|dotm|dotx|dsp|dtd|dvi|dvr-ms|dwf|dwp|dxr|eml|emz|eot|eps|esd|etx|evy|exe|execonfig|fdf|fif|fla|flr|flv|gif|gtar|gz|h|hdf|hdml|hhc|hhk|hhp|hlp|hqx|hta|htc|htm|html|htt|hxt|ico|ics|ief|iii|inf|ins|isp|IVF|jar|java|jck|jcz|jfif|jpb|jpe|jpeg|jpg|js|json|jsonld|jsx|latex|less|lit|lpk|lsf|lsx|lzh|m13|m14|m1v|m2ts|m3u|m4a|m4v|man|manifest|map|mdb|mdp|me|mht|mhtml|mid|midi|mix|mmf|mno|mny|mov|movie|mp2|mp3|mp4|mp4v|mpa|mpe|mpeg|mpg|mpp|mpv2|ms|msi|mso|mvb|mvc|nc|nsc|nws|ocx|oda|odc|ods|oga|ogg|ogv|one|onea|onepkg|onetmp|onetoc|onetoc2|osdx|otf|p10|p12|p7b|p7c|p7m|p7r|p7s|pbm|pcx|pcz|pdf|pfb|pfm|pfx|pgm|pko|pma|pmc|pml|pmr|pmw|png|pnm|pnz|pot|potm|potx|ppam|ppm|pps|ppsm|ppsx|ppt|pptm|pptx|prf|prm|prx|ps|psd|psm|psp|pub|qt|qtl|qxd|ra|ram|rar|ras|rf|rgb|rm|rmi|roff|rpm|rtf|rtx|scd|sct|sea|setpay|setreg|sgml|sh|shar|sit|sldm|sldx|smd|smi|smx|smz|snd|snp|spc|spl|spx|src|ssm|sst|stl|sv4cpio|sv4crc|svg|svgz|swf|t|tar|tcl|tex|texi|texinfo|tgz|thmx|thn|tif|tiff|toc|tr|trm|ts|tsv|ttf|tts|txt|u32|uls|ustar|vbs|vcf|vcs|vdx|vml|vsd|vss|vst|vsto|vsw|vsx|vtx|wav|wax|wbmp|wcm|wdb|webm|wks|wm|wma|wmd|wmf|wml|wmlc|wmls|wmlsc|wmp|wmv|wmx|wmz|woff|woff2|wps|wri|wrl|wrz|wsdl|wtv|wvx|x|xaf|xaml|xap|xbap|xbm|xdr|xht|xhtml|xla|xlam|xlc|xlm|xls|xlsb|xlsm|xlsx|xlt|xltm|xltx|xlw|xml|xof|xpm|xps|xsd|xsf|xsl|xslt|xsn|xtp|xwd|z|zip

Where are static variables stored in C and C++?

In fact, a variable is tuple (storage, scope, type, address, value):

storage     :   where is it stored, for example data, stack, heap...
scope       :   who can see us, for example global, local...
type        :   what is our type, for example int, int*...
address     :   where are we located
value       :   what is our value

Local scope could mean local to either the translational unit (source file), the function or the block depending on where its defined. To make variable visible to more than one function, it definitely has to be in either DATA or the BSS area (depending on whether its initialized explicitly or not, respectively). Its then scoped accordingly to either all function(s) or function(s) within source file.

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

I had this issue and realized that the file cgi-bin/php-fcgi had no execution rights.

It had 644 mode while is should have 755 mode.

Setting the correct mode was impossible (probably because the file was opened or sth), so I copied that file from another domain directory where it had proper rights already set and that fixed everything.

How to display multiple notifications in android

At the place of uniqueIntNo put unique integer number like this:

mNotificationManager.notify(uniqueIntNo, builder.build());

SQL Format as of Round off removing decimals

CAST(Round(MySum * 20.0 /100, 0) AS INT)

FYI

MySum * 20 /100, I get 11

This is because when all 3 operands are INTs, SQL Server will do perform integer maths, from left to right, truncating all intermediate results.

58 * 20 / 100 => 1160 / 100 => 11 (truncated from 11.6)

Also for the record ROUND(m,n) returns the result to n decimal places, not n significant figures.

How to assign string to bytes array

Besides the methods mentioned above, you can also do a trick as

s := "hello"
b := *(*[]byte)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&s))))

Go Play: http://play.golang.org/p/xASsiSpQmC

You should never use this :-)

What is the difference between JavaScript and jQuery?

Javascript is a programming language whereas jQuery is a library to help make writing in javascript easier. It's particularly useful for simply traversing the DOM in an HTML page.

When is it acceptable to call GC.Collect?

This isn't that relevant to the question, but for XSLT transforms in .NET (XSLCompiledTranform) then you might have no choice. Another candidate is the MSHTML control.

How can I get all the request headers in Django?

<b>request.META</b><br>
{% for k_meta, v_meta in request.META.items %}
  <code>{{ k_meta }}</code> : {{ v_meta }} <br>
{% endfor %}

How do I get a python program to do nothing?

You can use continue

if condition:
    continue
else:
    #do something

How to center a "position: absolute" element

A simple CSS trick, just add:

width: 100%;
text-align: center;

This works on both images and text.

UPDATE with CASE and IN - Oracle

There is another workaround you can use to update using a join. This example below assumes you want to de-normalize a table by including a lookup value (in this case storing a users name in the table). The update includes a join to find the name and the output is evaluated in a CASE statement that supports the name being found or not found. The key to making this work is ensuring all the columns coming out of the join have unique names. In the sample code, notice how b.user_name conflicts with the a.user_name column and must be aliased with the unique name "user_user_name".

UPDATE
(
    SELECT a.user_id, a.user_name, b.user_name as user_user_name
    FROM some_table a
    LEFT OUTER JOIN user_table b ON a.user_id = b.user_id
    WHERE a.user_id IS NOT NULL
)
SET user_name = CASE
    WHEN user_user_name IS NOT NULL THEN user_user_name
    ELSE 'UNKNOWN'
    END;   

WAITING at sun.misc.Unsafe.park(Native Method)

unsafe.park is pretty much the same as thread.wait, except that it's using architecture specific code (thus the reason it's 'unsafe'). unsafe is not made available publicly, but is used within java internal libraries where architecture specific code would offer significant optimization benefits. It's used a lot for thread pooling.

So, to answer your question, all the thread is doing is waiting for something, it's not really using any CPU. Considering that your original stack trace shows that you're using a lock I would assume a deadlock is going on in your case.

Yes I know you have almost certainly already solved this issue by now. However, you're one of the top results if someone googles sun.misc.unsafe.park. I figure answering the question may help others trying to understand what this method that seems to be using all their CPU is.

How to sync with a remote Git repository?

Generally git pull is enough, but I'm not sure what layout you have chosen (or has github chosen for you).

How do you clear Apache Maven's cache?

I've had this same problem, and I wrote a one-liner in shell to do it.

rm -rf $(mvn help:evaluate -Dexpression=settings.localRepository\
                       -Dorg.slf4j.simpleLogger.defaultLogLevel=WARN -B \
                       -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn | grep -vF '[INFO]')/*

I did it as a one-liner because I wanted to have a Jenkins-project to simply run this whenever I needed, so I wouldn't have to log on to stuff, etc. If you allow yourself a shell-script for it, you can write it cleaner:

#!/usr/bin/env bash
REPOSITORY=$(mvn help:evaluate \
  -Dexpression=settings.localRepository \
  -Dorg.slf4j.simpleLogger.defaultLogLevel=WARN \
  -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn \
  --batch-mode \
  | grep -vF '[INFO]')

rm -rf $REPOSITORY/*

Should work, but I have not tested all of that script. (I've tested the first command, but not the whole script.) This approach has the downside of running a large complicated command first. It is idempotent, so you can test it out for yourself. The deletion is its own command afterwards, and this lets you try it all out and check that it does what you think it does, because you shouldn't trust deletion commands without verification. However, it is smart for one good reason: It's portable. It respects your settings.xml file. If you're running this command, and tell maven to use a specific xml file (the -s or --settings argument), this will still work. So you don't have to fiddle with making sure everything is the same everywhere.

It's a bit wieldy, but it's a decent way of doing business, IMO.

Jquery, Clear / Empty all contents of tbody element?

        <table id="table_id" class="table table-hover">
          <thead>
            <tr>
             ...
             ...
            </tr>
          </thead>
        </table>

use this command to clear the body of that table: $("#table_id tbody").empty()

I use jquery to load the table content dynamically, and use this command to clear the body when doing the refreshing.

hope this helps you.

How to merge a list of lists with same type of items to a single list of items?

For List<List<List<x>>> and so on, use

list.SelectMany(x => x.SelectMany(y => y)).ToList();

This has been posted in a comment, but it does deserves a separate reply in my opinion.

How to add data via $.ajax ( serialize() + extra data ) like this

You can do it like this:

postData[postData.length] = { name: "variable_name", value: variable_value };

Description Box using "onmouseover"

This an old question but for people still looking. In JS you can now use the title property.

button.title = ("Popup text here");

Take the content of a list and append it to another list

You probably want

list2.extend(list1)

instead of

list2.append(list1)

Here's the difference:

>>> a = range(5)
>>> b = range(3)
>>> c = range(2)
>>> b.append(a)
>>> b
[0, 1, 2, [0, 1, 2, 3, 4]]
>>> c.extend(a)
>>> c
[0, 1, 0, 1, 2, 3, 4]

Since list.extend() accepts an arbitrary iterable, you can also replace

for line in mylog:
    list1.append(line)

by

list1.extend(mylog)

Regular expression to return text between parenthesis

Building on tkerwin's answer, if you happen to have nested parentheses like in

st = "sum((a+b)/(c+d))"

his answer will not work if you need to take everything between the first opening parenthesis and the last closing parenthesis to get (a+b)/(c+d), because find searches from the left of the string, and would stop at the first closing parenthesis.

To fix that, you need to use rfind for the second part of the operation, so it would become

st[st.find("(")+1:st.rfind(")")]

What is the best way to access redux store outside a react component?

It might be a bit late but i think the best way is to use axios.interceptors as below. Import urls might change based on your project setup.

index.js

import axios from 'axios';
import setupAxios from './redux/setupAxios';
import store from './redux/store';

// some other codes

setupAxios(axios, store);

setupAxios.js

export default function setupAxios(axios, store) {
    axios.interceptors.request.use(
        (config) => {
            const {
                auth: { tokens: { authorization_token } },
            } = store.getState();

            if (authorization_token) {
                config.headers.Authorization = `Bearer ${authorization_token}`;
            }

            return config;
        },
       (err) => Promise.reject(err)
    );
}

How do I automatically set the $DISPLAY variable for my current session?

Here's something I've just knocked up. It inspects the environment of the last-launched "gnome-session" process (DISPLAY is set correctly when VNC launches a session/window manager). Replace "gnome-session" with the name of whatever process your VNC server launches on startup.

PID=`pgrep -n -u $USER gnome-session`
if [ -n "$PID" ]; then
    export DISPLAY=`awk 'BEGIN{FS="="; RS="\0"}  $1=="DISPLAY" {print $2; exit}' /proc/$PID/environ`
    echo "DISPLAY set to $DISPLAY"
else
    echo "Could not set DISPLAY"
fi
unset PID

You should just be able to drop that in your .bashrc file.

get current date from [NSDate date] but set the time to 10:00 am

You can use this method for any minute / hour / period (aka am/pm) combination:

- (NSDate *)todayModifiedWithHours:(NSString *)hours
                           minutes:(NSString *)minutes
                         andPeriod:(NSString *)period
{
    NSDate *todayModified = NSDate.date;

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSMinuteCalendarUnit fromDate:todayModified];

    [components setMinute:minutes.intValue];

    int hour = 0;

    if ([period.uppercaseString isEqualToString:@"AM"]) {

        if (hours.intValue == 12) {
            hour = 0;
        }
        else {
            hour = hours.intValue;
        }
    }
    else if ([period.uppercaseString isEqualToString:@"PM"]) {

        if (hours.intValue != 12) {
            hour = hours.intValue + 12;
        }
        else {
            hour = 12;
        }
    }
    [components setHour:hour];

    todayModified = [calendar dateFromComponents:components];

    return todayModified;
}

Requested Example:

NSDate *todayAt10AM = [self todayModifiedWithHours:@"10"
                                           minutes:@"00"
                                         andPeriod:@"am"];

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

This method works for me well, and I think this is the simplest one to do this job.

The general idea is to redirect the user to some other pages after the form submission, which would stop the form resubmission on page refresh. Still, if you need to hold the user on the same page after the form is submitted, you can do it in multiple ways, but here I am describing the javascript method.

Javascript Method

This method is quite easy and blocks the pop up asking for form resubmission on refresh once the form is submitted. Just place this line of javascript code at the footer of your file and see the magic.

_x000D_
_x000D_
<script>_x000D_
if ( window.history.replaceState ) {_x000D_
  window.history.replaceState( null, null, window.location.href );_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

What does LayoutInflater in Android do?

This class is used to instantiate layout XML file into its corresponding View objects. It is never be used directly -- use getLayoutInflater() or getSystemService(String) to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on. For example:

LayoutInflater inflater = (LayoutInflater)context.getSystemService
      (Context.LAYOUT_INFLATER_SERVICE);

Reference: http://developer.android.com/reference/android/view/LayoutInflater.html

How to create custom button in Android using XML Styles

<gradient android:startColor="#ffdd00"
    android:endColor="@color/colorPrimary"
    android:centerColor="#ffff" />

<corners android:radius="33dp"/>

<padding
    android:bottom="7dp"
    android:left="7dp"
    android:right="7dp"
    android:top="7dp"
    />

Error in contrasts when defining a linear model in R

From my experience ten minutes ago this situation can happen where there are more than one category but with a lot of NAs. Taking the Kaggle Houseprice Dataset as example, if you loaded data and run a simple regression,

train.df = read.csv('train.csv')
lm1 = lm(SalePrice ~ ., data = train.df)

you will get same error. I also tried testing the number of levels of each factor, but none of them says it has less than 2 levels.

cols = colnames(train.df)
for (col in cols){
  if(is.factor(train.df[[col]])){
    cat(col, ' has ', length(levels(train.df[[col]])), '\n')
  }
}

So after a long time I used summary(train.df) to see details of each col, and removed some, and it finally worked:

train.df = subset(train.df, select=-c(Id, PoolQC,Fence, MiscFeature, Alley, Utilities))
lm1 = lm(SalePrice ~ ., data = train.df)

and removing any one of them the regression fails to run again with same error (which I have tested myself).

And above attributes generally have 1400+ NAs and 10 useful values, so you might want to remove these garbage attributes, even they have 3 or 4 levels. I guess a function counting how many NAs in each column will help.

How to get request url in a jQuery $.get/ajax request

Since jQuery.get is just a shorthand for jQuery.ajax, another way would be to use the latter one's context option, as stated in the documentation:

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

So you would use

$.ajax('http://www.example.org', {
  dataType: 'xml',
  data: {'a':1,'b':2,'c':3},
  context: {
    url: 'http://www.example.org'
  }
}).done(function(xml) {alert(this.url});

convert NSDictionary to NSString

You can call [aDictionary description], or anywhere you would need a format string, just use %@ to stand in for the dictionary:

[NSString stringWithFormat:@"my dictionary is %@", aDictionary];

or

NSLog(@"My dictionary is %@", aDictionary);

How to check what version of jQuery is loaded?

…just because this method hasn't been mentioned so far - open the console and type:

$ === jQuery

As @Juhana mentioned above $().jquery will return the version number.

How to access child's state in React?

Now You can access the InputField's state which is the child of FormEditor .

Basically whenever there is a change in the state of the input field(child) we are getting the value from the event object and then passing this value to the Parent where in the state in the Parent is set.

On button click we are just printing the state of the Input fields.

The key point here is that we are using the props to get the Input Field's id/value and also to call the functions which are set as attributes on the Input Field while we generate the reusable child Input fields.

class InputField extends React.Component{
  handleChange = (event)=> {
    const val = event.target.value;
    this.props.onChange(this.props.id , val);
  }

  render() {
    return(
      <div>
        <input type="text" onChange={this.handleChange} value={this.props.value}/>
        <br/><br/>
      </div>
    );
  }
}       


class FormEditorParent extends React.Component {
  state = {};
  handleFieldChange = (inputFieldId , inputFieldValue) => {
    this.setState({[inputFieldId]:inputFieldValue});
  }
  //on Button click simply get the state of the input field
  handleClick = ()=>{
    console.log(JSON.stringify(this.state));
  }

  render() {
    const fields = this.props.fields.map(field => (
      <InputField
        key={field}
        id={field}
        onChange={this.handleFieldChange}
        value={this.state[field]}
      />
    ));

    return (
      <div>
        <div>
          <button onClick={this.handleClick}>Click Me</button>
        </div>
        <div>
          {fields}
        </div>
      </div>
    );
  }
}

const App = () => {
  const fields = ["field1", "field2", "anotherField"];
  return <FormEditorParent fields={fields} />;
};

ReactDOM.render(<App/>, mountNode);

Parallel foreach with asynchronous lambda

In the accepted answer the ConcurrentBag is not required. Here's an implementation without it:

var tasks = myCollection.Select(GetData).ToList();
await Task.WhenAll(tasks);
var results = tasks.Select(t => t.Result);

Any of the "// some pre stuff" and "// some post stuff" can go into the GetData implementation (or another method that calls GetData)

Aside from being shorter, there's no use of an "async void" lambda, which is an anti pattern.

Embedding JavaScript engine into .NET

Hey take a look for Javascript .NET on codeplex (http://javascriptdotnet.codeplex.com/) with the version 0.3.1 there is some pretty sweet new features that will probly interest you.

Check out a sample code:

// Initialize the context
JavascriptContext context = new JavascriptContext();

// Setting the externals parameters of the context
context.SetParameter("console", new SystemConsole());
context.SetParameter("message", "Hello World !");
context.SetParameter("number", 1);

// Running the script
context.Run("var i; for (i = 0; i < 5; i++) console.Print(message + ' (' + i + ')'); number += i;");

// Getting a parameter
Console.WriteLine("number: " + context.GetParameter("number"));

Can jQuery check whether input content has changed?

I had to use this kind of code for a scanner that pasted stuff into the field

$(document).ready(function() {
  var tId,oldVal;
  $("#fieldId").focus(function() {
     oldVal = $("#fieldId").val();
     tId=setInterval(function() { 
      var newVal = $("#fieldId").val(); 
      if (oldVal!=newVal) oldVal=newVal;
      someaction() },100);
  });
  $("#fieldId").blur(function(){ clearInterval(tId)});
});

Not tested...

How to slice an array in Bash

There is also a convenient shortcut to get all elements of the array starting with specified index. For example "${A[@]:1}" would be the "tail" of the array, that is the array without its first element.

version=4.7.1
A=( ${version//\./ } )
echo "${A[@]}"    # 4 7 1
B=( "${A[@]:1}" )
echo "${B[@]}"    # 7 1

Read and Write CSV files including unicode with Python 2.7

Another alternative:

Use the code from the unicodecsv package ...

https://pypi.python.org/pypi/unicodecsv/

>>> import unicodecsv as csv
>>> from io import BytesIO
>>> f = BytesIO()
>>> w = csv.writer(f, encoding='utf-8')
>>> _ = w.writerow((u'é', u'ñ'))
>>> _ = f.seek(0)
>>> r = csv.reader(f, encoding='utf-8')
>>> next(r) == [u'é', u'ñ']
True

This module is API compatible with the STDLIB csv module.

Java integer list

So it would become:

List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
while(true)
    Iterator<Integer> myListIterator = myCoords.iterator(); 
    while (myListIterator.hasNext()) {
        Integer coord = myListIterator.next();    
        System.out.print("\r" + coord);
        try{
    Thread.sleep(2000);
  }catch(Exception e){
   // handle the exception...
  }
    }
}

ReCaptcha API v2 Styling

A bit late but I tried this and it worked to make the Recaptcha responsive on screens smaller than 460px width. You can't use css selector to select elements inside the iframe. So, better use the outermost parent element which is the class g-recaptcha to basically zoom-out i.e transform the size of the entire container. Here's my code which worked:

@media(max-width:459.99px) {
    .modal .g-recaptcha {
        transform:scale(0.75);
        -webkit-transform:scale(0.75); }
    }
}

You have to be inside an angular-cli project in order to use the build command after reinstall of angular-cli

I had the same issue - it turned out that i was using a deprecated angular-cli instead of @angular/cli. The latter was used by my dev team and it took me some time to notice that we were using a different versions of angular-cli.

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

SQLiteOpenHelper onCreate() and onUpgrade() callbacks are invoked when the database is actually opened, for example by a call to getWritableDatabase(). The database is not opened when the database helper object itself is created.

SQLiteOpenHelper versions the database files. The version number is the int argument passed to the constructor. In the database file, the version number is stored in PRAGMA user_version.

onCreate() is only run when the database file did not exist and was just created. If onCreate() returns successfully (doesn't throw an exception), the database is assumed to be created with the requested version number. As an implication, you should not catch SQLExceptions in onCreate() yourself.

onUpgrade() is only called when the database file exists but the stored version number is lower than requested in the constructor. The onUpgrade() should update the table schema to the requested version.

When changing the table schema in code (onCreate()), you should make sure the database is updated. Two main approaches:

  1. Delete the old database file so that onCreate() is run again. This is often preferred at development time where you have control over the installed versions and data loss is not an issue. Some ways to delete the database file:

    • Uninstall the application. Use the application manager or adb uninstall your.package.name from the shell.

    • Clear application data. Use the application manager.

  2. Increment the database version so that onUpgrade() is invoked. This is slightly more complicated as more code is needed.

    • For development time schema upgrades where data loss is not an issue, you can just use execSQL("DROP TABLE IF EXISTS <tablename>") in to remove your existing tables and call onCreate() to recreate the database.

    • For released versions, you should implement data migration in onUpgrade() so your users don't lose their data.

Can I add color to bootstrap icons only using CSS?

With the latest release of Bootstrap RC 3, changing the color of the icons is as simple as adding a class with the color you want and adding it to the span.

Default black color:

<h1>Password Changed <span class="glyphicon glyphicon-ok"></span></h1>

would become

<h1>Password Changed <span class="glyphicon glyphicon-ok icon-success"></span></h1>

CSS

.icon-success {
    color: #5CB85C;
}

Bootstrap 3 Glyphicons List

File upload from <input type="file">

There is a slightly better way to access attached files. You could use template reference variable to get an instance of the input element.

Here is an example based on the first answer:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="file" #file (change)="onChange(file.files)"/>
    </div>
  `,
  providers: [ UploadService ]
})

export class AppComponent {
  onChange(files) {
    console.log(files);
  }
}

Here is an example app to demonstrate this in action.

Template reference variables might be useful, e.g. you could access them via @ViewChild directly in the controller.

Find a file in python

In Python 3.4 or newer you can use pathlib to do recursive globbing:

>>> import pathlib
>>> sorted(pathlib.Path('.').glob('**/*.py'))
[PosixPath('build/lib/pathlib.py'),
 PosixPath('docs/conf.py'),
 PosixPath('pathlib.py'),
 PosixPath('setup.py'),
 PosixPath('test_pathlib.py')]

Reference: https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob

In Python 3.5 or newer you can also do recursive globbing like this:

>>> import glob
>>> glob.glob('**/*.txt', recursive=True)
['2.txt', 'sub/3.txt']

Reference: https://docs.python.org/3/library/glob.html#glob.glob

How to change Windows 10 interface language on Single Language version

You can download language pack and use "Install or Uninstall display languages" wizard. To do this:

  • Press Win+R, paste lpksetup and press Enter
  • Wizard will appear on the screen
  • Click the Install display languages button
  • In the next page of the wizard, click Browse and pick the *.cab file of the MUI language you downloaded
  • Click the Next button to install language

Difference between clustered and nonclustered index

You should be using indexes to help SQL server performance. Usually that implies that columns that are used to find rows in a table are indexed.

Clustered indexes makes SQL server order the rows on disk according to the index order. This implies that if you access data in the order of a clustered index, then the data will be present on disk in the correct order. However if the column(s) that have a clustered index is frequently changed, then the row(s) will move around on disk, causing overhead - which generally is not a good idea.

Having many indexes is not good either. They cost to maintain. So start out with the obvious ones, and then profile to see which ones you miss and would benefit from. You do not need them from start, they can be added later on.

Most column datatypes can be used when indexing, but it is better to have small columns indexed than large. Also it is common to create indexes on groups of columns (e.g. country + city + street).

Also you will not notice performance issues until you have quite a bit of data in your tables. And another thing to think about is that SQL server needs statistics to do its query optimizations the right way, so make sure that you do generate that.

Prevent Caching in ASP.NET MVC for specific actions using an attribute

In the controller action append to the header the following lines

    public ActionResult Create(string PositionID)
    {
        Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
        Response.AppendHeader("Expires", "0"); // Proxies.

How to process POST data in Node.js?

Express v4.17.0

app.use(express.urlencoded( {extended: true} ))

console.log(req.body) // object

Demo Form

Another Answer Related

Child element click event trigger the parent click event

Without jQuery : DEMO

 <div id="parentDiv" onclick="alert('parentDiv');">
   <div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;">
     AAA
   </div>   
</div>

Convert List<String> to List<Integer> directly

No, you will have to iterate over each element:

for(String number : numbers) {
   numberList.add(Integer.parseInt(number)); 
}

The reason this happens is that there is no straightforward way to convert a list of one type into any other type. Some conversions are not possible, or need to be done in a specific way. Essentially the conversion depends on the objects involved and the context of the conversion so there is no "one size fits all" solution. For example, what if you had a Car object and a Person object. You can't convert a List<Car> into a List<Person> directly since it doesn't really make sense.

Username and password in https url

When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.

With Basic Auth, the HTTP request from the question will look something like this:

GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk

The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password).

To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl, the username and password will be clearly visible on the process list and might turn up in the bash history file.

When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.

Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.

When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.

Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.

How to access ssis package variables inside script component

Strongly typed var don't seem to be available, I have to do the following in order to get access to them:

String MyVar = Dts.Variables["MyVarName"].Value.ToString();

Axios get in url works but with second parameter as object it doesn't

axios.get accepts a request config as the second parameter (not query string params).

You can use the params config option to set query string params as follows:

axios.get('/api', {
  params: {
    foo: 'bar'
  }
});

Responsive image map

Check out the image-map plugin on Github. It works both with vanilla JavaScript and as a jQuery plugin.

$('img[usemap]').imageMap();     // jQuery

ImageMap('img[usemap]')          // JavaScript

Check out the demo.

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

I know that we are (n-1) * (n times), but why the division by 2?

It's only (n - 1) * n if you use a naive bubblesort. You can get a significant savings if you notice the following:

  • After each compare-and-swap, the largest element you've encountered will be in the last spot you were at.

  • After the first pass, the largest element will be in the last position; after the kth pass, the kth largest element will be in the kth last position.

Thus you don't have to sort the whole thing every time: you only need to sort n - 2 elements the second time through, n - 3 elements the third time, and so on. That means that the total number of compare/swaps you have to do is (n - 1) + (n - 2) + .... This is an arithmetic series, and the equation for the total number of times is (n - 1)*n / 2.

Example: if the size of the list is N = 5, then you do 4 + 3 + 2 + 1 = 10 swaps -- and notice that 10 is the same as 4 * 5 / 2.

How to define object in array in Mongoose schema correctly with 2d geo index

You can declare trk by the following ways : - either

trk : [{
    lat : String,
    lng : String
     }]

or

trk : { type : Array , "default" : [] }

In the second case during insertion make the object and push it into the array like

db.update({'Searching criteria goes here'},
{
 $push : {
    trk :  {
             "lat": 50.3293714,
             "lng": 6.9389939
           } //inserted data is the object to be inserted 
  }
});

or you can set the Array of object by

db.update ({'seraching criteria goes here ' },
{
 $set : {
          trk : [ {
                     "lat": 50.3293714,
                     "lng": 6.9389939
                  },
                  {
                     "lat": 50.3293284,
                     "lng": 6.9389634
                  }
               ]//'inserted Array containing the list of object'
      }
});

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

I saw something in the new C# 6.0, this is by using '?' instead of checking

for example instead of using

if (Person != null && Person.Contact!=null && Person.Contact.Address!= null && Person.Contact.Address.City != null)
{ 
  var city = person.contact.address.city;
}

you simply use

var city = person?.contact?.address?.city;

I hope it helped somebody.


UPDATE:

You could do like this now

 var city = (Person != null)? 
           ((Person.Contact!=null)? 
              ((Person.Contact.Address!= null)?
                      ((Person.Contact.Address.City!=null)? 
                                 Person.Contact.Address.City : null )
                       :null)
               :null)
            : null;

BOOLEAN or TINYINT confusion

The numeric type overview for MySQL states: BOOL, BOOLEAN: These types are synonyms for TINYINT(1). A value of zero is considered false. Nonzero values are considered true.

See here: https://dev.mysql.com/doc/refman/5.7/en/numeric-type-overview.html

Team Build Error: The Path ... is already mapped to workspace

Here is what I did (well what I do):

Using TFS Sidekicks clear out the user and server filters so they are blank. This will let you get all workspaces.

Check the build error for the workspace name. In the OPs case it is BuildServer_23. It is different in my environment but basically just match up the error name with the one in the tfs sidekick list.

Click the red x to delete the workspace.

Viola!

Create a List that contain each Line of a File

my_list = [line.split(',') for line in open("filename.txt")]

Conditional Replace Pandas

Try

df.loc[df.my_channel > 20000, 'my_channel'] = 0

Note: Since v0.20.0, ix has been deprecated in favour of loc / iloc.

How to force addition instead of concatenation in javascript

The following statement appends the value to the element with the id of response

$('#response').append(total);

This makes it look like you are concatenating the strings, but you aren't, you're actually appending them to the element

change that to

$('#response').text(total);

You need to change the drop event so that it replaces the value of the element with the total, you also need to keep track of what the total is, I suggest something like the following

$(function() {
    var data = [];
    var total = 0;

    $( "#draggable1" ).draggable();
    $( "#draggable2" ).draggable();
    $( "#draggable3" ).draggable();

    $("#droppable_box").droppable({
        drop: function(event, ui) {
        var currentId = $(ui.draggable).attr('id');
        data.push($(ui.draggable).attr('id'));

        if(currentId == "draggable1"){
            var myInt1 = parseFloat($('#MealplanCalsPerServing1').val());
        }
        if(currentId == "draggable2"){
            var myInt2 = parseFloat($('#MealplanCalsPerServing2').val());
        }
        if(currentId == "draggable3"){
            var myInt3 = parseFloat($('#MealplanCalsPerServing3').val());
        }
        if ( typeof myInt1 === 'undefined' || !myInt1 ) {
            myInt1 = parseInt(0);
        }
        if ( typeof myInt2 === 'undefined' || !myInt2){
            myInt2 = parseInt(0);
        }
        if ( typeof myInt3 === 'undefined' || !myInt3){
        myInt3 = parseInt(0);
        }
        total += parseFloat(myInt1 + myInt2 + myInt3);
        $('#response').text(total);
        }
    });

    $('#myId').click(function(event) {
        $.post("process.php", ({ id: data }), function(return_data, status) {
            alert(data);
            //alert(total);
        });
    });
});

I moved the var total = 0; statement out of the drop event and changed the assignment statment from this

total = parseFloat(myInt1 + myInt2 + myInt3);

to this

total += parseFloat(myInt1 + myInt2 + myInt3);

Here is a working example http://jsfiddle.net/axrwkr/RCzGn/

Session timeout in ASP.NET

IIS sessions timeout value is for classic .asp applications only, this is controlled on IIS configuration. In your case For ASP.NET apps, only the web.config-specified timeout value applies.

PHP session handling errors

I got these two error messages, along with two others, and fiddled around for a while before discovering that all I needed to do was restart XAMPP! I hope this helps save someone else from the same wasted time!

Warning: session_start(): open(/var/folders/zw/hdfw48qd25xcch5sz9dd3w600000gn/T/sess_f8bgs41qn3fk6d95s0pfps60n4, O_RDWR) failed: Permission denied (13) in /Applications/XAMPP/xamppfiles/htdocs/foo/bar.php on line 3

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /Applications/XAMPP/xamppfiles/htdocs/foo/bar.php:3) in /Applications/XAMPP/xamppfiles/htdocs/foo/bar.php on line 3

Warning: Unknown: open(/var/lib/php/session/sess_isu2r2bqudeosqvpoo8a67oj02, O_RDWR) failed: Permission denied (13) in Unknown on line 0

Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/lib/php/session) in Unknown on line 0

Override intranet compatibility mode IE8

Try putting the following in the header:

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

Courtesy Paul Irish's HTML5 Boilerplate (but it works in XHTML Transitional, too).

How to set Meld as git mergetool

I think that mergetool.meld.path should point directly to the meld executable. Thus, the command you want is:

git config --global mergetool.meld.path c:/Progra~2/meld/bin/meld

Configuration with name 'default' not found. Android Studio

Step.1 $ git submodule update

Step.2 To be commented out the dependences of classpass

How to round double to nearest whole number and then convert to a float?

For what is worth:

the closest integer to any given input as shown in the following table can be calculated using Math.ceil or Math.floor depending of the distance between the input and the next integer

+-------+--------+
| input | output |
+-------+--------+
|     1 |      0 |
|     2 |      0 |
|     3 |      5 |
|     4 |      5 |
|     5 |      5 |
|     6 |      5 |
|     7 |      5 |
|     8 |     10 |
|     9 |     10 |
+-------+--------+

private int roundClosest(final int i, final int k) {
    int deic = (i % k);
    if (deic <= (k / 2.0)) {
        return (int) (Math.floor(i / (double) k) * k);
    } else {
        return (int) (Math.ceil(i / (double) k) * k);
    }
}

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

I encountered this issue when trying to import the results of a Stored Proc into a temp table, and that Stored Proc inserted into a temp table as part of its own operation. The issue being that SQL Server does not allow the same process to write to two different temp tables at the same time.

The accepted OPENROWSET answer works fine, but I needed to avoid using any Dynamic SQL or an external OLE provider in my process, so I went a different route.

One easy workaround I found was to change the temporary table in my stored procedure to a table variable. It works exactly the same as it did with a temp table, but no longer conflicts with my other temp table insert.

Just to head off the comment I know that a few of you are about to write, warning me off Table Variables as performance killers... All I can say to you is that in 2020 it pays dividends not to be afraid of Table Variables. If this was 2008 and my Database was hosted on a server with 16GB RAM and running off 5400RPM HDDs, I might agree with you. But it's 2020 and I have an SSD array as my primary storage and hundreds of gigs of RAM. I could load my entire company's database to a table variable and still have plenty of RAM to spare.

Table Variables are back on the menu!

Why am I getting error for apple-touch-icon-precomposed.png

Simply create zero-sized files called the appropriate names.

The request will be satisfied with no additional data transfer nor further logging lines.

How to save user input into a variable in html and js

I found this to work best for me https://jsfiddle.net/Lu92akv6/ [I found this to work for me try this fiddle][1]

_x000D_
_x000D_
document.getElementById("btnmyNumber").addEventListener("click", myFunctionVar);_x000D_
function myFunctionVar() {_x000D_
  var numberr = parseInt(document.getElementById("myNumber").value, 10);_x000D_
  // alert(numberr);_x000D_
  if ( numberr > 1) {_x000D_
_x000D_
    document.getElementById("minusE5").style.display = "none";_x000D_
_x000D_
_x000D_
_x000D_
}}
_x000D_
   <form onsubmit="return false;">_x000D_
       <input class="button button3" type="number" id="myNumber" value="" min="0" max="30">_x000D_
       <input type="submit" id="btnmyNumber">_x000D_
_x000D_
       </form>
_x000D_
_x000D_
_x000D_

How do I increase the RAM and set up host-only networking in Vagrant?

You can modify various VM properties by adding the following configuration (see the Vagrant docs for a bit more info):

  # Configure VM Ram usage
  config.vm.customize [
                        "modifyvm", :id,
                        "--name", "Test_Environment",
                        "--memory", "1024"
                      ]

You can obtain the properties that you want to change from the documents for VirtualBox command-line options:

The vagrant documentation has the section on how to change IP address:

Vagrant::Config.run do |config|
  config.vm.network :hostonly, "192.168.50.4"
end

Also you can restructure the configuration like this, ending is do with end without nesting it. This is simpler.

config.vm.define :web do |web_config|
    web_config.vm.box = "lucid32"
    web_config.vm.forward_port 80, 8080
end
web_config.vm.provision :puppet do |puppet|
    puppet.manifests_path = "manifests"
    puppet.manifest_file = "lucid32.pp"
end

Please initialize the log4j system properly. While running web service

Warning No appenders could be found for logger means that you're using log4j logging system, but you haven't added any Appenders (such as FileAppender, ConsoleAppender, SocketAppender, SyslogAppender, etc.) into your configuration file or the configuration file is missing.

There are three ways to configure log4j: with a properties file (log4j.properties), with an XML file and through Java code (rootLogger.addAppender(new NullAppender());).

If you've property file present (e.g. when installing Solr), you need to place this file within your classpath directory.

classpath

Here are some command suggestions how to determine your classpath value:

$ echo $CLASSPATH
$ ps wuax | grep -i classpath
$ grep -Ri classpath /etc/tomcat? /var/lib/tomcat?/conf

or from Java: System.getProperty("java.class.path").

Tomcat

If you're using Tomcat, you may place your log4j.properties into: /usr/share/tomcat?/lib/ or /var/lib/tomcat?/webapps/*/WEB-INF/lib/ folder.

Solr

For the reference, Solr log4j.properties looks like:

#  Logging level
solr.log=logs/
log4j.rootLogger=INFO, file, CONSOLE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender

log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x \u2013 %m%n

#- size rotation with log cleanup.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=4MB
log4j.appender.file.MaxBackupIndex=9

#- File to log to and log format
log4j.appender.file.File=${solr.log}/solr.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS}; %C; %m\n

log4j.logger.org.apache.zookeeper=WARN
log4j.logger.org.apache.hadoop=WARN

# set to INFO to enable infostream log messages
log4j.logger.org.apache.solr.update.LoggingInfoStream=OFF

How to make an authenticated web request in Powershell?

The PowerShell is almost exactly the same.

$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)

Avoid browser popup blockers

In addition Swiss Mister post, in my case the window.open was launched inside a promise, which turned the popup blocker on, my solution was: in angular:

$scope.gotClick = function(){

  var myNewTab = browserService.openNewTab();
  someService.getUrl().then(
    function(res){
        browserService.updateTabLocation(res.url, myNewTab);

    }
  );
};

browserService:

this.openNewTab = function(){
     var newTabWindow = $window.open();
     return newTabWindow;
}

this.updateTabLocation = function(tabLocation, tab) {
     if(!tabLocation){
       tab.close();
     }
     tab.location.href = tabLocation;
}

this is how you can open a new tab using the promise response and not invoking the popup blocker.

How do I get column datatype in Oracle with PL-SQL with low privileges?

The best solution that I've found for such case is

select column_name, data_type||
case
when data_precision is not null and nvl(data_scale,0)>0 then '('||data_precision||','||data_scale||')'
when data_precision is not null and nvl(data_scale,0)=0 then '('||data_precision||')'
when data_precision is null and data_scale is not null then '(*,'||data_scale||')'
when char_length>0 then '('||char_length|| case char_used 
                                                         when 'B' then ' Byte'
                                                         when 'C' then ' Char'
                                                         else null 
                                           end||')'
end||decode(nullable, 'N', ' NOT NULL')
from user_tab_columns
where table_name = 'TABLE_NAME'
and column_name = 'COLUMN_NAME';

@Aaron Stainback, thank you for correction!

How to parse a text file with C#

OK, here's what we do: open the file, read it line by line, and split it by tabs. Then we grab the second integer and loop through the rest to find the path.

StreamReader reader = File.OpenText("filename.txt");
string line;
while ((line = reader.ReadLine()) != null) 
{
    string[] items = line.Split('\t');
    int myInteger = int.Parse(items[1]);   // Here's your integer.

    // Now let's find the path.
    string path = null;
    foreach (string item in items) 
    {
        if (item.StartsWith("item\\") && item.EndsWith(".ddj"))
            path = item;
    }

    // At this point, `myInteger` and `path` contain the values we want
    // for the current line. We can then store those values or print them,
    // or anything else we like.
}

Get $_POST from multiple checkboxes

Edit To reflect what @Marc said in the comment below.

You can do a loop through all the posted values.

HTML:

<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />

PHP:

foreach($_POST['check_list'] as $item){
  // query to delete where item = $item
}

getApplication() vs. getApplicationContext()

To answer the question, getApplication() returns an Application object and getApplicationContext() returns a Context object. Based on your own observations, I would assume that the Context of both are identical (i.e. behind the scenes the Application class calls the latter function to populate the Context portion of the base class or some equivalent action takes place). It shouldn't really matter which function you call if you just need a Context.

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

change "CreateDate": "0001-01-01 00:00:00" to "CreateDate": "2020-12-19 00:00:00",

CreateDate type is public DateTime CreateDate

error json:

{ "keyValue": 1, "entity": { "TodoId": 1, "SysId": "3730e2b8-8d65-457a-bd50-041ce9705dc6", "AllowApproval": false, "ApprovalUrl": null, "ApprovalContent": null, "IsRead": true, "ExpireTime": "2020-12-19 00:00:00", "CreateDate": "0001-01-01 00:00:00", "CreateBy": null, "ModifyDate": "2020-12-18 9:42:10", "ModifyBy": null, "UserId": "f5250229-c6d1-4210-aed9-1c0287ab1ce3", "MessageUrl": "https://bing.com" } }

correct json:

{ "keyValue": 1, "entity": { "TodoId": 1, "SysId": "3730e2b8-8d65-457a-bd50-041ce9705dc6", "AllowApproval": false, "ApprovalUrl": null, "ApprovalContent": null, "IsRead": true, "ExpireTime": "2020-12-19 00:00:00", "CreateDate": "2020-12-19 00:00:00", "CreateBy": null, "ModifyDate": "2020-12-18 9:42:10", "ModifyBy": null, "UserId": "f5250229-c6d1-4210-aed9-1c0287ab1ce3", "MessageUrl": "https://bing.com" } }

Is there a standardized method to swap two variables in Python?

I know three ways to swap variables, but a, b = b, a is the simplest. There is

XOR (for integers)

x = x ^ y
y = y ^ x
x = x ^ y

Or concisely,

x ^= y
y ^= x
x ^= y

Temporary variable

w = x
x = y
y = w
del w

Tuple swap

x, y = y, x

No module named setuptools

The question mentions Windows, and the accepted answer also works for Ubuntu, but for those who found this question coming from a Redhat flavor of Linux, this did the trick:

sudo yum install -y python-setuptools

R - Markdown avoiding package loading messages

You can use include=FALSE to exclude everything in a chunk.

```{r include=FALSE}
source("C:/Rscripts/source.R")
```

If you only want to suppress messages, use message=FALSE instead:

```{r message=FALSE}
source("C:/Rscripts/source.R")
```

Publish to IIS, setting Environment Variable

@tredder solution with editing applicationHost.config is the one that works if you have several different applications located within virtual directories on IIS.

My case is:

  • I do have API project and APP project, under the same domain, placed in different virtual directories
  • Root page XXX doesn't seem to propagate ASPNETCORE_ENVIRONMENT variable to its children in virtual directories and...
  • ...I'm unable to set the variables inside the virtual directory as @NickAb described (got error The request is not supported. (Exception from HRESULT: 0x80070032) during saving changes in Configuration Editor):
  • Going into applicationHost.config and manually creating nodes like this:

    <location path="XXX/app"> <system.webServer> <aspNetCore> <environmentVariables> <clear /> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" /> </environmentVariables> </aspNetCore> </system.webServer> </location> <location path="XXX/api"> <system.webServer> <aspNetCore> <environmentVariables> <clear /> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" /> </environmentVariables> </aspNetCore> </system.webServer> </location>

and restarting the IIS did the job.

Truncate a string straight JavaScript

Updated ES6 version

const truncateString = (string, maxLength = 50) => {
  if (!string) return null;
  if (string.length <= maxLength) return string;
  return `${string.substring(0, maxLength)}...`;
};

truncateString('what up', 4); // returns 'what...'

How can I convert a VBScript to an executable (EXE) file?

There is no way to convert a VBScript (.vbs file) into an executable (.exe file) because VBScript is not a compiled language. The process of converting source code into native executable code is called "compilation", and it's not supported by scripting languages like VBScript.

Certainly you can add your script to a self-extracting archive using something like WinZip, but all that will do is compress it. It's doubtful that the file size will shrink noticeably, and since it's a plain-text file to begin with, it's really not necessary to compress it at all. The only purpose of a self-extracting archive is that decompression software (like WinZip) is not required on the end user's computer to be able to extract or "decompress" the file. If it isn't compressed in the first place, this is a moot point.

Alternatively, as you mentioned, there are ways to wrap VBScript code files in a standalone executable file, but these are just wrappers that automatically execute the script (in its current, uncompiled state) when the user double-clicks on the .exe file. I suppose that can have its benefits, but it doesn't sound like what you're looking for.

In order to truly convert your VBScript into an executable file, you're going to have to rewrite it in another language that can be compiled. Visual Basic 6 (the latest version of VB, before the .NET Framework was introduced) is extremely similar in syntax to VBScript, but does support compiling to native code. If you move your VBScript code to VB 6, you can compile it into a native executable. Running the .exe file will require that the user has the VB 6 Run-time libraries installed, but they come built into most versions of Windows that are found now in the wild.

Alternatively, you could go ahead and make the jump to Visual Basic .NET, which remains somewhat similar in syntax to VB 6 and VBScript (although it won't be anywhere near a cut-and-paste migration). VB.NET programs will also compile to an .exe file, but they require the .NET Framework runtime to be installed on the user's computer. Fortunately, this has also become commonplace, and it can be easily redistributed if your users don't happen to have it. You mentioned going this route in your question (porting your current script in to VB Express 2008, which uses VB.NET), but that you were getting a lot of errors. That's what I mean about it being far from a cut-and-paste migration. There are some huge differences between VB 6/VBScript and VB.NET, despite some superficial syntactical similarities. If you want help migrating over your VBScript, you could post a question here on Stack Overflow. Ultimately, this is probably the best way to do what you want, but I can't promise you that it will be simple.

Swift Open Link in Safari

Swift 3 & IOS 10.2

UIApplication.shared.open(URL(string: "http://www.stackoverflow.com")!, options: [:], completionHandler: nil)

Swift 3 & IOS 10.2

HTTP Request in Kotlin

Send HTTP POST/GET request with parameters using HttpURLConnection :

POST with Parameters:

fun sendPostRequest(userName:String, password:String) {

    var reqParam = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8")
    reqParam += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8")
    val mURL = URL("<Your API Link>")

    with(mURL.openConnection() as HttpURLConnection) {
        // optional default is GET
        requestMethod = "POST"

        val wr = OutputStreamWriter(getOutputStream());
        wr.write(reqParam);
        wr.flush();

        println("URL : $url")
        println("Response Code : $responseCode")

        BufferedReader(InputStreamReader(inputStream)).use {
            val response = StringBuffer()

            var inputLine = it.readLine()
            while (inputLine != null) {
                response.append(inputLine)
                inputLine = it.readLine()
            }
            println("Response : $response")
        }
    }
}

GET with Parameters:

fun sendGetRequest(userName:String, password:String) {

        var reqParam = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8")
        reqParam += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8")

        val mURL = URL("<Yout API Link>?"+reqParam)

        with(mURL.openConnection() as HttpURLConnection) {
            // optional default is GET
            requestMethod = "GET"

            println("URL : $url")
            println("Response Code : $responseCode")

            BufferedReader(InputStreamReader(inputStream)).use {
                val response = StringBuffer()

                var inputLine = it.readLine()
                while (inputLine != null) {
                    response.append(inputLine)
                    inputLine = it.readLine()
                }
                it.close()
                println("Response : $response")
            }
        }
    }

How to include scripts located inside the node_modules folder?

If you want a quick and easy solution (and you have gulp installed).

In my gulpfile.js I run a simple copy paste task that puts any files I might need into ./public/modules/ directory.

gulp.task('modules', function() {
    sources = [
      './node_modules/prismjs/prism.js',
      './node_modules/prismjs/themes/prism-dark.css',
    ]
    gulp.src( sources ).pipe(gulp.dest('./public/modules/'));
});

gulp.task('copy-modules', ['modules']);

The downside to this is that it isn't automated. However, if all you need is a few scripts and styles copied over (and kept in a list), this should do the job.

phpmailer error "Could not instantiate mail function"

Seems in my case it was just SERVER REJECTION. Please check your mail server log / smtp connection accessibility.

How to retrieve absolute path given relative

My favourite solution was the one by @EugenKonkov because it didn't imply the presence of other utilities (the coreutils package).

But it failed for the relative paths "." and "..", so here is a slightly improved version handling these special cases.

It still fails if the user doesn't have the permission to cd into the parent directory of the relative path, though.

#! /bin/sh

# Takes a path argument and returns it as an absolute path. 
# No-op if the path is already absolute.
function to-abs-path {
    local target="$1"

    if [ "$target" == "." ]; then
        echo "$(pwd)"
    elif [ "$target" == ".." ]; then
        echo "$(dirname "$(pwd)")"
    else
        echo "$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"
    fi
}

How to load/edit/run/save text files (.py) into an IPython notebook cell?

To write/save

%%writefile myfile.py

  • write/save cell contents into myfile.py (use -a to append). Another alias: %%file myfile.py

To run

%run myfile.py

  • run myfile.py and output results in the current cell

To load/import

%load myfile.py

  • load "import" myfile.py into the current cell

For more magic and help

%lsmagic

  • list all the other cool cell magic commands.

%COMMAND-NAME?

  • for help on how to use a certain command. i.e. %run?

Note

Beside the cell magic commands, IPython notebook (now Jupyter notebook) is so cool that it allows you to use any unix command right from the cell (this is also equivalent to using the %%bash cell magic command).

To run a unix command from the cell, just precede your command with ! mark. for example:

  • !python --version see your python version
  • !python myfile.py run myfile.py and output results in the current cell, just like %run (see the difference between !python and %run in the comments below).

Also, see this nbviewer for further explanation with examples. Hope this helps.

Difference in boto3 between resource, client, and session?

I'll try and explain it as simple as possible. So there is no guarantee of the accuracy of the actual terms.

Session is where to initiate the connectivity to AWS services. E.g. following is default session that uses the default credential profile(e.g. ~/.aws/credentials, or assume your EC2 using IAM instance profile )

sqs = boto3.client('sqs')
s3 = boto3.resource('s3')

Because default session is limit to the profile or instance profile used, sometimes you need to use the custom session to override the default session configuration (e.g. region_name, endpoint_url, etc. ) e.g.

# custom resource session must use boto3.Session to do the override
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource('s3')
video_s3 = my_east_session.resource('s3')

# you have two choices of create custom client session. 
backup_s3c = my_west_session.client('s3')
video_s3c = boto3.client("s3", region_name = 'us-east-1')

Resource : This is the high-level service class recommended to be used. This allows you to tied particular AWS resources and passes it along, so you just use this abstraction than worry which target services are pointed to. As you notice from the session part, if you have a custom session, you just pass this abstract object than worrying about all custom regions,etc to pass along. Following is a complicated example E.g.

import boto3 
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource("s3")
video_s3 = my_east_session.resource("s3")
backup_bucket = backup_s3.Bucket('backupbucket') 
video_bucket = video_s3.Bucket('videobucket')

# just pass the instantiated bucket object
def list_bucket_contents(bucket):
   for object in bucket.objects.all():
      print(object.key)

list_bucket_contents(backup_bucket)
list_bucket_contents(video_bucket)

Client is a low level class object. For each client call, you need to explicitly specify the targeting resources, the designated service target name must be pass long. You will lose the abstraction ability.

For example, if you only deal with the default session, this looks similar to boto3.resource.

import boto3 
s3 = boto3.client('s3')

def list_bucket_contents(bucket_name):
   for object in s3.list_objects_v2(Bucket=bucket_name) :
      print(object.key)

list_bucket_contents('Mybucket') 

However, if you want to list objects from a bucket in different regions, you need to specify the explicit bucket parameter required for the client.

import boto3 
backup_s3 = my_west_session.client('s3',region_name = 'us-west-2')
video_s3 = my_east_session.client('s3',region_name = 'us-east-1')

# you must pass boto3.Session.client and the bucket name 
def list_bucket_contents(s3session, bucket_name):
   response = s3session.list_objects_v2(Bucket=bucket_name)
   if 'Contents' in response:
     for obj in response['Contents']:
        print(obj['key'])

list_bucket_contents(backup_s3, 'backupbucket')
list_bucket_contents(video_s3 , 'videobucket') 

How do I navigate to a parent route from a child route?

Do you want a link/HTML or do you want to route imperatively/in code?

Link: The RouterLink directive always treats the provided link as a delta to the current URL:

[routerLink]="['/absolute']"
[routerLink]="['../../parent']"
[routerLink]="['../sibling']"
[routerLink]="['./child']"     // or
[routerLink]="['child']" 

// with route param     ../../parent;abc=xyz
[routerLink]="['../../parent', {abc: 'xyz'}]"
// with query param and fragment   ../../parent?p1=value1&p2=v2#frag
[routerLink]="['../../parent']" [queryParams]="{p1: 'value', p2: 'v2'}" fragment="frag"

With RouterLink, remember to import and use the directives array:

import { ROUTER_DIRECTIVES } from '@angular/router';
@Component({
    directives: [ROUTER_DIRECTIVES],

Imperative: The navigate() method requires a starting point (i.e., the relativeTo parameter). If none is provided, the navigation is absolute:

import { Router, ActivatedRoute } from '@angular/router';
...
constructor(private router: Router, private route: ActivatedRoute) {}
...
this.router.navigate(["/absolute/path"]);
this.router.navigate(["../../parent"], {relativeTo: this.route});
this.router.navigate(["../sibling"],   {relativeTo: this.route});
this.router.navigate(["./child"],      {relativeTo: this.route}); // or
this.router.navigate(["child"],        {relativeTo: this.route});

// with route param     ../../parent;abc=xyz
this.router.navigate(["../../parent", {abc: 'xyz'}], {relativeTo: this.route});
// with query param and fragment   ../../parent?p1=value1&p2=v2#frag
this.router.navigate(["../../parent"], {relativeTo: this.route, 
    queryParams: {p1: 'value', p2: 'v2'}, fragment: 'frag'});

// navigate without updating the URL 
this.router.navigate(["../../parent"], {relativeTo: this.route, skipLocationChange: true});

PHP CSV string to array

A modification of previous answers using array_map.
Blow up the CSV data with multiple lines.

$csv = array_map('str_getcsv', explode("\n", $csvData));

How to ignore files/directories in TFS for avoiding them to go to central source repository?

It does seem a little cumbersome to ignore files (and folders) in Team Foundation Server. I've found a couple ways to do this (using TFS / Team Explorer / Visual Studio 2008). These methods work with the web site ASP project type, too.

One way is to add a new or existing item to a project (e.g. right click on project, Add Existing Item or drag and drop from Windows explorer into the solution explorer), let TFS process the file(s) or folder, then undo pending changes on the item(s). TFS will unmark them as having a pending add change, and the files will sit quietly in the project and stay out of TFS.

Another way is with the Add Items to Folder command of Source Control Explorer. This launches a small wizard, and on one of the steps you can select items to exclude (although, I think you have to add at least one item to TFS with this method for the wizard to let you continue).

You can even add a forbidden patterns check-in policy (under Team -> Team Project Settings -> Source Control... -> Check-in Policy) to disallow other people on the team from mistakenly checking in certain assets.

How to vertically align into the center of the content of a div with defined width/height?

margin: all_four_margin

by providing 50% to all_four_margin will place the element at the center

style="margin: 50%"

you can apply it for following too

margin: top right bottom left

margin: top right&left bottom

margin: top&bottom right&left

by giving appropriate % we get the element wherever we want.

size of struct in C

Your default alignment is probably 4 bytes. Either the 30 byte element got 32, or the structure as a whole was rounded up to the next 4 byte interval.

How to make a query with group_concat in sql server

This can also be achieved using the Scalar-Valued Function in MSSQL 2008
Declare your function as following,

CREATE FUNCTION [dbo].[FunctionName]
(@MaskId INT)
RETURNS Varchar(500) 
AS
BEGIN

    DECLARE @SchoolName varchar(500)                        

    SELECT @SchoolName =ISNULL(@SchoolName ,'')+ MD.maskdetail +', ' 
    FROM maskdetails MD WITH (NOLOCK)       
    AND MD.MaskId=@MaskId

    RETURN @SchoolName

END

And then your final query will be like

SELECT m.maskid,m.maskname,m.schoolid,s.schoolname,
(SELECT [dbo].[FunctionName](m.maskid)) 'maskdetail'
FROM tblmask m JOIN school s on s.id = m.schoolid 
ORDER BY m.maskname ;

Note: You may have to change the function, as I don't know the complete table structure.

Markdown and including multiple files

Another HTML-based, client-side solution using markdown-it and jQuery. Below is a small HTML wrapper as a master document, that supports unlimited includes of markdown files, but not nested includes. Explanation is provided in the JS comments. Error handling is omitted.

<script src="/markdown-it.min.js"></script>
<script src="/jquery-3.5.1.min.js"></script>

<script> 
  $(function() {
    var mdit = window.markdownit();
    mdit.options.html=true;
    // Process all div elements of class include.  Follow up with custom callback
    $('div.include').each( function() {
      var inc = $(this);
      // Use contents between div tag as the file to be included from server
      var filename = inc.html();
      // Unable to intercept load() contents.  post-process markdown rendering with callback
      inc.load(filename, function () {
        inc.html( mdit.render(this.innerHTML) );
      });
  });
})
</script>
</head>

<body>
<h1>Master Document </h1>

<h1>Section 1</h1>
<div class="include">sec_1.md</div>
<hr/>
<h1>Section 2</h1>
<div class="include">sec_2.md</div>

Store multiple values in single key in json

Use arrays:

{
    "number": ["1", "2", "3"],
    "alphabet": ["a", "b", "c"]
}

You can the access the different values from their position in the array. Counting starts at left of array at 0. myJsonObject["number"][0] == 1 or myJsonObject["alphabet"][2] == 'c'

JavaScript: set dropdown selected item based on option text

This works in latest Chrome, FireFox and Edge, but not IE11:

document.evaluate('//option[text()="Yahoo"]', document).iterateNext().selected = 'selected';

And if you want to ignore spaces around the title:

document.evaluate('//option[normalize-space(text())="Yahoo"]', document).iterateNext().selected = 'selected'

Get query string parameters url values with jQuery / Javascript (querystring)

Building on @Rob Neild's answer above, here is a pure JS adaptation that returns a simple object of decoded query string params (no %20's, etc).

function parseQueryString () {
  var parsedParameters = {},
    uriParameters = location.search.substr(1).split('&');

  for (var i = 0; i < uriParameters.length; i++) {
    var parameter = uriParameters[i].split('=');
    parsedParameters[parameter[0]] = decodeURIComponent(parameter[1]);
  }

  return parsedParameters;
}

Stack Memory vs Heap Memory

It's a language abstraction - some languages have both, some one, some neither.

In the case of C++, the code is not run in either the stack or the heap. You can test what happens if you run out of heap memory by repeatingly calling new to allocate memory in a loop without calling delete to free it it. But make a system backup before doing this.

How to access single elements in a table in R

Maybe not so perfect as above ones, but I guess this is what you were looking for.

data[1:1,3:3]    #works with positive integers
data[1:1, -3:-3] #does not work, gives the entire 1st row without the 3rd element
data[i:i,j:j]    #given that i and j are positive integers

Here indexing will work from 1, i.e,

data[1:1,1:1]    #means the top-leftmost element

Scrolling a div with jQuery

jCarousel is a Jquery Plugin , it have same functionality already implemented , which might want to archive. it's nice and easy. here is the link

and complete documentation can be found here

Format price in the current locale and currency

For formatting the price in another currency than the current one:

Mage::app()->getLocale()->currency('EUR')->toCurrency($price);

Run task only if host does not belong to a group

Here's another way to do this:

- name: my command
  command: echo stuff
  when: "'groupname' not in group_names"

group_names is a magic variable as documented here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables :

group_names is a list (array) of all the groups the current host is in.

In Python, how to check if a string only contains certain characters?

This has already been answered satisfactorily, but for people coming across this after the fact, I have done some profiling of several different methods of accomplishing this. In my case I wanted uppercase hex digits, so modify as necessary to suit your needs.

Here are my test implementations:

import re

hex_digits = set("ABCDEF1234567890")
hex_match = re.compile(r'^[A-F0-9]+\Z')
hex_search = re.compile(r'[^A-F0-9]')

def test_set(input):
    return set(input) <= hex_digits

def test_not_any(input):
    return not any(c not in hex_digits for c in input)

def test_re_match1(input):
    return bool(re.compile(r'^[A-F0-9]+\Z').match(input))

def test_re_match2(input):
    return bool(hex_match.match(input))

def test_re_match3(input):
    return bool(re.match(r'^[A-F0-9]+\Z', input))

def test_re_search1(input):
    return not bool(re.compile(r'[^A-F0-9]').search(input))

def test_re_search2(input):
    return not bool(hex_search.search(input))

def test_re_search3(input):
    return not bool(re.match(r'[^A-F0-9]', input))

And the tests, in Python 3.4.0 on Mac OS X:

import cProfile
import pstats
import random

# generate a list of 10000 random hex strings between 10 and 10009 characters long
# this takes a little time; be patient
tests = [ ''.join(random.choice("ABCDEF1234567890") for _ in range(l)) for l in range(10, 10010) ]

# set up profiling, then start collecting stats
test_pr = cProfile.Profile(timeunit=0.000001)
test_pr.enable()

# run the test functions against each item in tests. 
# this takes a little time; be patient
for t in tests:
    for tf in [test_set, test_not_any, 
               test_re_match1, test_re_match2, test_re_match3,
               test_re_search1, test_re_search2, test_re_search3]:
        _ = tf(t)

# stop collecting stats
test_pr.disable()

# we create our own pstats.Stats object to filter 
# out some stuff we don't care about seeing
test_stats = pstats.Stats(test_pr)

# normally, stats are printed with the format %8.3f, 
# but I want more significant digits
# so this monkey patch handles that
def _f8(x):
    return "%11.6f" % x

def _print_title(self):
    print('   ncalls     tottime     percall     cumtime     percall', end=' ', file=self.stream)
    print('filename:lineno(function)', file=self.stream)

pstats.f8 = _f8
pstats.Stats.print_title = _print_title

# sort by cumulative time (then secondary sort by name), ascending
# then print only our test implementation function calls:
test_stats.sort_stats('cumtime', 'name').reverse_order().print_stats("test_*")

which gave the following results:

         50335004 function calls in 13.428 seconds

   Ordered by: cumulative time, function name
   List reduced from 20 to 8 due to restriction 

   ncalls     tottime     percall     cumtime     percall filename:lineno(function)
    10000    0.005233    0.000001    0.367360    0.000037 :1(test_re_match2)
    10000    0.006248    0.000001    0.378853    0.000038 :1(test_re_match3)
    10000    0.010710    0.000001    0.395770    0.000040 :1(test_re_match1)
    10000    0.004578    0.000000    0.467386    0.000047 :1(test_re_search2)
    10000    0.005994    0.000001    0.475329    0.000048 :1(test_re_search3)
    10000    0.008100    0.000001    0.482209    0.000048 :1(test_re_search1)
    10000    0.863139    0.000086    0.863139    0.000086 :1(test_set)
    10000    0.007414    0.000001    9.962580    0.000996 :1(test_not_any)

where:

ncalls
The number of times that function was called
tottime
the total time spent in the given function, excluding time made to sub-functions
percall
the quotient of tottime divided by ncalls
cumtime
the cumulative time spent in this and all subfunctions
percall
the quotient of cumtime divided by primitive calls

The columns we actually care about are cumtime and percall, as that shows us the actual time taken from function entry to exit. As we can see, regex match and search are not massively different.

It is faster not to bother compiling the regex if you would have compiled it every time. It is about 7.5% faster to compile once than every time, but only 2.5% faster to compile than to not compile.

test_set was twice as slow as re_search and thrice as slow as re_match

test_not_any was a full order of magnitude slower than test_set

TL;DR: Use re.match or re.search

Unique constraint on multiple columns

If the table is already created in the database, then you can add a unique constraint later on by using this SQL query:

ALTER TABLE dbo.User
  ADD CONSTRAINT ucCodes UNIQUE (fcode, scode, dcode)

How do you easily horizontally center a <div> using CSS?

The title of the question and the content is actually different, so I will post two solutions for that using Flexbox.

I guess Flexbox will replace/add to the current standard solution by the time IE8 and IE9 is completely destroyed ;)

Check the current Browser compatibility table for flexbox

Single element

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}
_x000D_
<div class="container">_x000D_
  <img src="http://placehold.it/100x100">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Multiple elements but center only one

Default behaviour is flex-direction: row which will align all the child items in a single line. Setting it to flex-direction: column will help the lines to be stacked.

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
.centered {_x000D_
  align-self: center;_x000D_
}
_x000D_
<div class="container">_x000D_
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged._x000D_
   </p>_x000D_
  <div class="centered"><img src="http://placehold.it/100x100"></div>_x000D_
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It_x000D_
    has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I quickly rename a MySQL database (change schema name)?

Really, the simplest answer is to export your old database then import it into the new one that you've created to replace the old one. Of course, you should use phpMyAdmin or command line to do this.

Renaming and Jerry-rigging the database is a BAD-IDEA! DO NOT DO IT. (Unless you are the "hacker-type" sitting in your mother's basement in the dark and eating pizza sleeping during the day.)

You will end up with more problems and work than you want.

So,

  1. Create a new_database and name it the correct way.
  2. Go to your phpMyAdmin and open the database you want to export.
  3. Export it (check the options, but you should be OK with the defaults.
  4. You will get a file like or similar to this.
  5. The extension on this file is .sql

    -- phpMyAdmin SQL Dump -- version 3.2.4

    -- http://www.phpmyadmin.net

    -- Host: localhost -- Generation Time: Jun 30, 2010 at 12:17 PM -- Server version: 5.0.90 -- PHP Version: 5.2.6

    SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

    /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT /; /!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS /; /!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION /; /!40101 SET NAMES utf8 */;

    --

    -- Database: mydatab_online


    --

    -- Table structure for table user

    CREATE TABLE IF NOT EXISTS user ( timestamp int(15) NOT NULL default '0', ip varchar(40) NOT NULL default '', file varchar(100) NOT NULL default '', PRIMARY KEY (timestamp), KEY ip (ip), KEY file (file) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

    --

    -- Dumping data for table user

    INSERT INTO user (timestamp, ip, file) VALUES (1277911052, '999.236.177.116', ''), (1277911194, '999.236.177.116', '');

This will be your .sql file. The one that you've just exported.

Find it on your hard-drive; usually it is in /temp. Select the empty database that has the correct name (the reason why you are reading this). SAY: Import - GO

Connect your program to the correct database by entering it into what usually is a configuration.php file. Refresh the server (both. Why? Because I am a UNIX oldtimer, and I said so. Now, you should be in good shape. If you have any further questions visit me on the web.

How to make a radio button look like a toggle button

Here's my version of that nice CSS solution JS Fiddle example posted above.

http://jsfiddle.net/496c9/

HTML

<div id="donate">
    <label class="blue"><input type="radio" name="toggle"><span>$20</span></label>
    <label class="green"><input type="radio" name="toggle"><span>$50</span></label>
    <label class="yellow"><input type="radio" name="toggle"><span>$100</span></label>
    <label class="pink"><input type="radio" name="toggle"><span>$500</span></label>
    <label class="purple"><input type="radio" name="toggle"><span>$1000</span></label>
</div>

CSS

body {
    font-family:sans-serif;
}

#donate {
    margin:4px;

    float:left;
}

#donate label {
    float:left;
    width:170px;
    margin:4px;
    background-color:#EFEFEF;
    border-radius:4px;
    border:1px solid #D0D0D0;
    overflow:auto;

}

#donate label span {
    text-align:center;
    font-size: 32px;
    padding:13px 0px;
    display:block;
}

#donate label input {
    position:absolute;
    top:-20px;
}

#donate input:checked + span {
    background-color:#404040;
    color:#F7F7F7;
}

#donate .yellow {
    background-color:#FFCC00;
    color:#333;
}

#donate .blue {
    background-color:#00BFFF;
    color:#333;
}

#donate .pink {
    background-color:#FF99FF;
    color:#333;
}

#donate .green {
    background-color:#A3D900;
    color:#333;
}
#donate .purple {
    background-color:#B399FF;
    color:#333;
}

Styled with coloured buttons :)

Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

Along the same lines as previous answers, but a very short addition that Allows to use all Control properties without having cross thread invokation exception.

Helper Method

    /// <summary>
    /// Helper method to determin if invoke required, if so will rerun method on correct thread.
    /// if not do nothing.
    /// </summary>
    /// <param name="c">Control that might require invoking</param>
    /// <param name="a">action to preform on control thread if so.</param>
    /// <returns>true if invoke required</returns>
    public bool ControlInvokeRequired(Control c,Action a)
    {
        if (c.InvokeRequired) c.Invoke(new MethodInvoker(delegate { a(); }));
        else return false;

        return true;
    }

Sample Usage

    // usage on textbox
    public void UpdateTextBox1(String text)
    {
        //Check if invoke requied if so return - as i will be recalled in correct thread
        if (ControlInvokeRequired(textBox1, () => UpdateTextBox1(text))) return;
        textBox1.Text = ellapsed;
    }

    //Or any control
    public void UpdateControl(Color c,String s)
    {
        //Check if invoke requied if so return - as i will be recalled in correct thread
        if (ControlInvokeRequired(myControl, () => UpdateControl(c,s))) return;
        myControl.Text = s;
        myControl.BackColor = c;
    }

Javascript to check whether a checkbox is being checked or unchecked

function enter_comment(super_id) {
    if (!(document.getElementById(super_id).checked)) {
        alert('selected checkbox is unchecked now')
    } else {
        alert('selected checkbox is checked now');
    }
}

<input type="checkbox" name="a" id="1" value="1" onclick="enter_comment(this.value)" />

<input type="checkbox" name="b" id="2" value="2" onclick="enter_comment(this.value)" />

Add column to dataframe with constant value

Summing up what the others have suggested, and adding a third way

You can:

where the argument loc ( 0 <= loc <= len(columns) ) allows you to insert the column where you want.

'loc' gives you the index that your column will be at after the insertion. For example, the code above inserts the column Name as the 0-th column, i.e. it will be inserted before the first column, becoming the new first column. (Indexing starts from 0).

All these methods allow you to add a new column from a Series as well (just substitute the 'abc' default argument above with the series).

Implementing INotifyPropertyChanged - does a better way exist?

Here is a Unity3D or non-CallerMemberName version of NotifyPropertyChanged

public abstract class Bindable : MonoBehaviour, INotifyPropertyChanged
{
    private readonly Dictionary<string, object> _properties = new Dictionary<string, object>();
    private static readonly StackTrace stackTrace = new StackTrace();
    public event PropertyChangedEventHandler PropertyChanged;

    /// <summary>
    ///     Resolves a Property's name from a Lambda Expression passed in.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="property"></param>
    /// <returns></returns>
    internal string GetPropertyName<T>(Expression<Func<T>> property)
    {
        var expression = (MemberExpression) property.Body;
        var propertyName = expression.Member.Name;

        Debug.AssertFormat(propertyName != null, "Bindable Property shouldn't be null!");
        return propertyName;
    }

    #region Notification Handlers

    /// <summary>
    ///     Notify's all other objects listening that a value has changed for nominated propertyName
    /// </summary>
    /// <param name="propertyName"></param>
    internal void NotifyOfPropertyChange(string propertyName)
    {
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    /// <summary>
    ///     Notifies subscribers of the property change.
    /// </summary>
    /// <typeparam name="TProperty">The type of the property.</typeparam>
    /// <param name="property">The property expression.</param>
    internal void NotifyOfPropertyChange<TProperty>(Expression<Func<TProperty>> property)
    {
        var propertyName = GetPropertyName(property);
        NotifyOfPropertyChange(propertyName);
    }

    /// <summary>
    ///     Raises the <see cref="PropertyChanged" /> event directly.
    /// </summary>
    /// <param name="e">The <see cref="PropertyChangedEventArgs" /> instance containing the event data.</param>
    internal void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, e);
        }
    }

    #endregion

    #region Getters

    /// <summary>
    ///     Gets the value of a property
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="name"></param>
    /// <returns></returns>
    internal T Get<T>(Expression<Func<T>> property)
    {
        var propertyName = GetPropertyName(property);
        return Get<T>(GetPropertyName(property));
    }

    /// <summary>
    ///     Gets the value of a property automatically based on its caller.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    internal T Get<T>()
    {
        var name = stackTrace.GetFrame(1).GetMethod().Name.Substring(4); // strips the set_ from name;
        return Get<T>(name);
    }

    /// <summary>
    ///     Gets the name of a property based on a string.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="name"></param>
    /// <returns></returns>
    internal T Get<T>(string name)
    {
        object value = null;
        if (_properties.TryGetValue(name, out value))
            return value == null ? default(T) : (T) value;
        return default(T);
    }

    #endregion

    #region Setters

    /// <summary>
    ///     Sets the value of a property whilst automatically looking up its caller name.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value"></param>
    internal void Set<T>(T value)
    {
        var propertyName = stackTrace.GetFrame(1).GetMethod().Name.Substring(4); // strips the set_ from name;
        Set(value, propertyName);
    }

    /// <summary>
    ///     Sets the value of a property
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value"></param>
    /// <param name="name"></param>
    internal void Set<T>(T value, string propertyName)
    {
        Debug.Assert(propertyName != null, "name != null");
        if (Equals(value, Get<T>(propertyName)))
            return;
        _properties[propertyName] = value;
        NotifyOfPropertyChange(propertyName);
    }

    /// <summary>
    ///     Sets the value of a property based off an Expression (()=>FieldName)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value"></param>
    /// <param name="property"></param>
    internal void Set<T>(T value, Expression<Func<T>> property)
    {
        var propertyName = GetPropertyName(property);

        Debug.Assert(propertyName != null, "name != null");

        if (Equals(value, Get<T>(propertyName)))
            return;
        _properties[propertyName] = value;
        NotifyOfPropertyChange(propertyName);
    }

    #endregion
}

This code enables you to write property backing fields like this:

  public string Text
    {
        get { return Get<string>(); }
        set { Set(value); }
    }

Furthermore, in resharper if you create a pattern/search snippet you can then also automate you're workflow by converting simple prop fields into the above backing.

Search Pattern:

public $type$ $fname$ { get; set; }

Replace Pattern:

public $type$ $fname$
{
    get { return Get<$type$>(); }
    set { Set(value); }
}

How to keep keys/values in same order as declared?

Another alternative is to use Pandas dataframe as it guarantees the order and the index locations of the items in a dict-like structure.

Unable to get spring boot to automatically create database schema

You just add createDatabaseIfNotExist=true like this

spring.datasource.url=jdbc:mysql://localhost:3306/test?createDatabaseIfNotExist=true&amp;amp;useUnicode=true&amp;amp;characterEncoding=utf-8&amp;amp;autoReconnect=true

to your application.properties file

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

In WCF serive project this issue may be due to Reference of System.Web.Mvc.dll 's different version or may be any other DLL's different version issue. So this may be compatibility issue of DLL's different version

When I use

System.Web.Mvc.dll version 5.2.2.0 -> it thorows the Error The content type text/html; charset=utf-8 of the response message

but when I use

System.Web.Mvc.dll version 4.0.0.0 or lower -> That's works fine in my project and not have an Error.

I don't know the reason of this different version of DLL's issue but when I change the DLL's verison which is compatible with your WCF Project than it works fine.

This Error even generate when you add reference of other Project in your WCF Project and this reference project has different version of System.Web.Mvc DLL or could be any other DLL.

ERROR 1049 (42000): Unknown database 'mydatabasename'

I had the same issue, i run this command on command line and just like you i had added the ';' at the end. Removing it solved the issue. Instead of this

mysql -uroot -pmypassword mydatabase<mydatabase.sql;

try this

mysql -uroot -pmypassword mydatabase<mydatabase.sql

Deadly CORS when http://localhost is the origin

The solution is to install an extension that lifts the block that Chrome does, for example:

Access Control-Allow-Origin - Unblock (https://add0n.com/access-control.html?version=0.1.5&type=install).

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

The only solution I have found is not to set the index to a previous frame and wait (then OpenCV stops reading frames, anyway), but to initialize the capture one more time. So, it looks like this:

cap = cv2.VideoCapture(camera_url)
while True:
    ret, frame = cap.read()

    if not ret:
        cap = cv.VideoCapture(camera_url)
        continue

    # do your processing here

And it works perfectly!

How to get screen width without (minus) scrollbar?

You can use vanilla javascript by simply writing:

var width = el.clientWidth;

You could also use this to get the width of the document as follows:

var docWidth = document.documentElement.clientWidth || document.body.clientWidth;

Source: MDN

You can also get the width of the full window, including the scrollbar, as follows:

var fullWidth = window.innerWidth;

However this is not supported by all browsers, so as a fallback, you may want to use docWidth as above, and add on the scrollbar width.

Source: MDN

Horizontal ListView in Android?

You may use ViewFlipper to include the layout XML and add images , listview for each layout XML

How can I add new dimensions to a Numpy array?

I followed this approach:

import numpy as np
import cv2

ls = []

for image in image_paths:
    ls.append(cv2.imread('test.jpg'))

img_np = np.array(ls) # shape (100, 480, 640, 3)
img_np = np.rollaxis(img_np, 0, 4) # shape (480, 640, 3, 100).

How to resume Fragment from BackStack if exists

Easier solution will be changing this line

ft.replace(R.id.content_frame, A); to ft.add(R.id.content_frame, A);

And inside your XML layout please use

  android:background="@color/white"
  android:clickable="true"
  android:focusable="true"

Clickable means that it can be clicked by a pointer device or be tapped by a touch device.

Focusable means that it can gain the focus from an input device like a keyboard. Input devices like keyboards cannot decide which view to send its input events to based on the inputs itself, so they send them to the view that has focus.

Angular.js How to change an elements css class on click and to remove all others

have you tried with a condition in ng-class like here : http://jsfiddle.net/DotDotDot/zvLvg/ ?

    <span id='1' ng-class='{"myclass":tog==1}' ng-click='tog=1'>span 1</span>
    <span id='2' ng-class='{"myclass":tog==2}' ng-click='tog=2'>span 2</span>

nodejs module.js:340 error: cannot find module

Faced the same problem while trying to run node-red.

node <directory structure where js  is located>/red. js

In my case it was :

node AppData/Roaming/npm/node_modules/node-red/red.js