Programs & Examples On #Magic constants

add a string prefix to each value in a string column using Pandas

If you load you table file with dtype=str
or convert column type to string df['a'] = df['a'].astype(str)
then you can use such approach:

df['a']= 'col' + df['a'].str[:]

This approach allows prepend, append, and subset string of df.
Works on Pandas v0.23.4, v0.24.1. Don't know about earlier versions.

Android: ListView elements with multiple clickable buttons

Isn't the platform solution for this implementation to use a context menu that shows on a long press?

Is the question author aware of context menus? Stacking up buttons in a listview has performance implications, will clutter your UI and violate the recommended UI design for the platform.

On the flipside; context menus - by nature of not having a passive representation - are not obvious to the end user. Consider documenting the behaviour?

This guide should give you a good start.

http://www.mikeplate.com/2010/01/21/show-a-context-menu-for-long-clicks-in-an-android-listview/

SQL Server 2008 - Case / If statements in SELECT Clause

Try something like

SELECT
    CASE var
        WHEN xyz THEN col1
        WHEN zyx THEN col2
        ELSE col7
    END AS col1,
    ...

In other words, use a conditional expression to select the value, then rename the column.

Alternately, you could build up some sort of dynamic SQL hack to share the query tail; I've done this with iBatis before.

What does PHP keyword 'var' do?

It's for declaring class member variables in PHP4, and is no longer needed. It will work in PHP5, but will raise an E_STRICT warning in PHP from version 5.0.0 up to version 5.1.2, as of when it was deprecated. Since PHP 5.3, var has been un-deprecated and is a synonym for 'public'.

Example usage:

class foo {
    var $x = 'y'; // or you can use public like...
    public $x = 'y'; //this is also a class member variables.
    function bar() {
    }
}

How to import spring-config.xml of one project into spring-config.xml of another project?

<import resource="classpath*:spring-config.xml" /> 

This is the most suitable one for class path configuration. Particularly when you are searching for the .xml files in a different project which is in your class path.

Creating a PDF from a RDLC Report in the Background

This is easy to do, you can render the report as a PDF, and save the resulting byte array as a PDF file on disk. To do this in the background, that's more a question of how your app is written. You can just spin up a new thread, or use a BackgroundWorker (if this is a WinForms app), etc. There, of course, may be multithreading issues to be aware of.

Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;

byte[] bytes = reportViewer.LocalReport.Render(
    "PDF", null, out mimeType, out encoding, out filenameExtension,
    out streamids, out warnings);

using (FileStream fs = new FileStream("output.pdf", FileMode.Create))
{
    fs.Write(bytes, 0, bytes.Length);
}

How to remove specific substrings from a set of strings in Python?

>>> x = 'Pear.good'
>>> y = x.replace('.good','')
>>> y
'Pear'
>>> x
'Pear.good'

.replace doesn't change the string, it returns a copy of the string with the replacement. You can't change the string directly because strings are immutable.

You need to take the return values from x.replace and put them in a new set.

How to insert close button in popover for Bootstrap

I found the code below very useful (taken from https://www.emanueletessore.com/twitter-bootstrap-popover-add-close-button/):

$('[data-toggle="popover"]').popover({
  title: function(){
    return $(this).data('title')+'<span class="close" style="margin-top: -5px">&times;</span>';
  }
}).on('shown.bs.popover', function(e){
  var popover = $(this);
  $(this).parent().find('div.popover .close').on('click', function(e){
    popover.popover('hide');
  });
});

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

Everyone's versions do things a little different. This is the version that I have developed over the years. This version seems to account for all of the issues I have encountered. Simply populate a data set into a table then pass the table name to this stored procedure.

I call this stored procedure like this:

EXEC    @return_value = *DB_You_Create_The_SP_In*.[dbo].[Export_CSVFile]
        @DB = N'*YourDB*',
        @TABLE_NAME = N'*YourTable*',
        @Dir = N'*YourOutputDirectory*',
        @File = N'*YourOutputFileName*'

There are also two other variables:

  • @NullBlanks -- This will take any field that doesn't have a value and null it. This is useful because in the true sense of the CSV specification each data point should have quotes around them. If you have a large data set this will save you a fair amount of space by not having "" (two double quotes) in those fields. If you don't find this useful then set it to 0.
  • @IncludeHeaders -- I have one stored procedure for outputting CSV files, so I do have that flag in the event I don't want headers.

This will create the stored procedure:

CREATE PROCEDURE [dbo].[Export_CSVFile] 
(@DB varchar(128),@TABLE_NAME varchar(128), @Dir varchar(255), @File varchar(250),@NULLBLANKS bit=1,@IncludeHeader bit=1)
AS

DECLARE @CSVHeader varchar(max)=''  --CSV Header
, @CmdExc varchar(max)=''           --EXEC commands
, @SQL varchar(max)=''              --SQL Statements
, @COLUMN_NAME varchar(128)=''      --Column Names
, @DATA_TYPE varchar(15)=''         --Data Types

DECLARE @T table (COLUMN_NAME varchar(128),DATA_TYPE varchar(15))

--BEGIN Ensure Dir variable has a backslash as the final character
IF NOT RIGHT(@Dir,1) = '\' BEGIN SET @Dir=@Dir+'\' END
--END

--BEGIN Drop TEMP Table IF Exists
SET @SQL='IF (EXISTS (SELECT * FROM '+@DB+'.INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ''TEMP_'+@TABLE_NAME+''')) BEGIN EXEC(''DROP TABLE ['+@DB+'].[dbo].[TEMP_'+@TABLE_NAME+']'') END'
EXEC(@SQL)
--END

SET @SQL='SELECT COLUMN_NAME,DATA_TYPE FROM '+@DB+'.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='''+@TABLE_NAME+''' ORDER BY ORDINAL_POSITION'
INSERT INTO @T
EXEC (@SQL)

SET @SQL=''
WHILE exists(SELECT * FROM @T)
    BEGIN
        SELECT top(1) @DATA_TYPE=DATA_TYPE,@COLUMN_NAME=COLUMN_NAME FROM @T
        IF @DATA_TYPE LIKE '%char%' OR @DATA_TYPE LIKE '%text'
            BEGIN 
            IF @NULLBLANKS = 1
                BEGIN
                    SET @SQL+='CASE PATINDEX(''%[0-9,a-z]%'','+@COLUMN_NAME+') WHEN ''0'' THEN NULL ELSE ''"''+RTRIM(LTRIM('+@COLUMN_NAME+'))+''"'' END AS ['+@COLUMN_NAME+'],' 
                END
            ELSE
                BEGIN
                    SET @SQL+='''"''+RTRIM(LTRIM('+@COLUMN_NAME+'))+''"'' AS ['+@COLUMN_NAME+'],' 
                END
            END
        ELSE
            BEGIN SET @SQL+=@COLUMN_NAME+',' END
            SET @CSVHeader+='"'+@COLUMN_NAME+'",'
            DELETE top(1) @T
    END 

IF LEN(@CSVHeader)>1 BEGIN SET @CSVHeader=RTRIM(LTRIM(LEFT(@CSVHeader,LEN(@CSVHeader)-1))) END

IF LEN(@SQL)>1 BEGIN SET @SQL= 'SELECT '+ LEFT(@SQL,LEN(@SQL)-1) + ' INTO ['+@DB+'].[dbo].[TEMP_'+@TABLE_NAME+'] FROM ['+@DB+'].[dbo].['+@TABLE_NAME+']' END
EXEC(@SQL)

IF @IncludeHeader=0 
    BEGIN
        --BEGIN Create Data file
        SET  @CmdExc ='BCP "'+@DB+'.dbo.TEMP_'+@TABLE_NAME+'" out "'+@Dir+'Data_'+@TABLE_NAME+'.csv" /c /t, -T' 
        EXEC master..xp_cmdshell @CmdExc
        --END
        SET  @CmdExc ='del '+@Dir+@File EXEC master..xp_cmdshell @CmdExc
        SET  @CmdExc ='ren '+@Dir+'Data_'+@TABLE_NAME+'.csv '+@File EXEC master..xp_cmdshell @CmdExc
    END 
else
    BEGIN

        --BEGIN Create Header and main file
        SET  @CmdExc ='echo '+@CSVHeader+'> '+@Dir+@File EXEC master..xp_cmdshell @CmdExc
        --END

        --BEGIN Create Data file
        SET  @CmdExc ='BCP "'+@DB+'.dbo.TEMP_'+@TABLE_NAME+'" out "'+@Dir+'Data_'+@TABLE_NAME+'.csv" /c /t, -T' 
        EXEC master..xp_cmdshell @CmdExc
        --END

        --BEGIN Merge Data File With Header File
        SET @CmdExc = 'TYPE '+@Dir+'Data_'+@TABLE_NAME+'.csv >> '+@Dir+@File EXEC master..xp_cmdshell @CmdExc
        --END

        --BEGIN Delete Data File
        SET @CmdExc = 'DEL /q '+@Dir+'Data_'+@TABLE_NAME+'.csv' EXEC master..xp_cmdshell @CmdExc
        --END
    END
--BEGIN Drop TEMP Table IF Exists
SET @SQL='IF (EXISTS (SELECT * FROM '+@DB+'.INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ''TEMP_'+@TABLE_NAME+''')) BEGIN EXEC(''DROP TABLE ['+@DB+'].[dbo].[TEMP_'+@TABLE_NAME+']'') END'
EXEC(@SQL)

Can you Run Xcode in Linux?

I think you need MonoTouch (not free!) for that plugin.

And no, there is no way to run Xcode on Linux.

Sorry for all the bad news. :)

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

My version of the answer is actually very similar to the @Stefan Haustein. I found the answer on Android Developer page Retrieving File Information; the information here is even more condensed on this specific topic than on Storage Access Framework guide site. In the result from the query the column index containing file name is OpenableColumns.DISPLAY_NAME. None of other answers/solutions for column indexes worked for me. Below is the sample function:

 /**
 * @param uri uri of file.
 * @param contentResolver access to server app.
 * @return the name of the file.
 */
def extractFileName(uri: Uri, contentResolver: ContentResolver): Option[String] = {

    var fileName: Option[String] = None
    if (uri.getScheme.equals("file")) {

        fileName = Option(uri.getLastPathSegment)
    } else if (uri.getScheme.equals("content")) {

        var cursor: Cursor = null
        try {

            // Query the server app to get the file's display name and size.
            cursor = contentResolver.query(uri, null, null, null, null)

            // Get the column indexes of the data in the Cursor,
            // move to the first row in the Cursor, get the data.
            if (cursor != null && cursor.moveToFirst()) {

                val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                fileName = Option(cursor.getString(nameIndex))
            }

        } finally {

            if (cursor != null) {
                cursor.close()
            }

        }

    }

    fileName
}

Quickly create large file on a Windows system

I needed a regular 10 GB file for testing, so I couldn't use fsutil because it creates sparse files (thanks @ZXX).

@echo off

:: Create file with 2 bytes
echo.>file-big.txt

:: Expand to 1 KB
for /L %%i in (1, 1, 9) do type file-big.txt>>file-big.txt

:: Expand to 1 MB
for /L %%i in (1, 1, 10) do type file-big.txt>>file-big.txt

:: Expand to 1 GB
for /L %%i in (1, 1, 10) do type file-big.txt>>file-big.txt

:: Expand to 4 GB
del file-4gb.txt
for /L %%i in (1, 1, 4) do type file-big.txt>>file-4gb.txt

del file-big.txt

I wanted to create a 10 GB file, but for some reason it only showed up as 4 GB, so I wanted to be safe and stopped at 4 GB. If you really want to be sure your file will be handled properly by the operating system and other applications, stop expanding it at 1 GB.

Why can't I call a public method in another class?

It sounds like you're not instantiating your class. That's the primary reason I get the "an object reference is required" error.

MyClass myClass = new MyClass();

once you've added that line you can then call your method

myClass.myMethod();

Also, are all of your classes in the same namespace? When I was first learning c# this was a common tripping point for me.

How do you round a floating point number in Perl?

See perldoc/perlfaq:

Remember that int() merely truncates toward 0. For rounding to a certain number of digits, sprintf() or printf() is usually the easiest route.

 printf("%.3f",3.1415926535);
 # prints 3.142

The POSIX module (part of the standard Perl distribution) implements ceil(), floor(), and a number of other mathematical and trigonometric functions.

use POSIX;
$ceil  = ceil(3.5); # 4
$floor = floor(3.5); # 3

In 5.000 to 5.003 perls, trigonometry was done in the Math::Complex module.

With 5.004, the Math::Trig module (part of the standard Perl distribution) > implements the trigonometric functions.

Internally it uses the Math::Complex module and some functions can break out from the real axis into the complex plane, for example the inverse sine of 2.

Rounding in financial applications can have serious implications, and the rounding method used should be specified precisely. In these cases, it probably pays not to trust whichever system rounding is being used by Perl, but to instead implement the rounding function you need yourself.

To see why, notice how you'll still have an issue on half-way-point alternation:

for ($i = 0; $i < 1.01; $i += 0.05)
{
   printf "%.1f ",$i
}

0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7 0.8 0.8 0.9 0.9 1.0 1.0

Don't blame Perl. It's the same as in C. IEEE says we have to do this. Perl numbers whose absolute values are integers under 2**31 (on 32 bit machines) will work pretty much like mathematical integers. Other numbers are not guaranteed.

"Cannot instantiate the type..."

I had the very same issue, not being able to instantiate the type of a class which I was absolutely sure was not abstract. Turns out I was implementing an abstract class from Java.util instead of implementing my own class.

So if the previous answers did not help you, please check that you import the class you actually wanted to import, and not something else with the same name that you IDE might have hinted you.

For example, if you were trying to instantiate the class Queue from the package myCollections which you coded yourself :

import java.util.*; // replace this line
import myCollections.Queue; // by this line

     Queue<Edge> theQueue = new Queue<Edge>();

better way to drop nan rows in pandas

Use dropna:

dat.dropna()

You can pass param how to drop if all labels are nan or any of the labels are nan

dat.dropna(how='any')    #to drop if any value in the row has a nan
dat.dropna(how='all')    #to drop if all values in the row are nan

Hope that answers your question!

Edit 1: In case you want to drop rows containing nan values only from particular column(s), as suggested by J. Doe in his answer below, you can use the following:

dat.dropna(subset=[col_list])  # col_list is a list of column names to consider for nan values.

Get Max value from List<myType>

How about this way:

List<int> myList = new List<int>(){1, 2, 3, 4}; //or any other type
myList.Sort();
int greatestValue = myList[ myList.Count - 1 ];

You basically let the Sort() method to do the job for you instead of writing your own method. Unless you don't want to sort your collection.

javascript createElement(), style problem

yourElement.setAttribute("style", "background-color:red; font-size:2em;");

Or you could write the element as pure HTML and use .innerHTML = [raw html code]... that's very ugly though.

In answer to your first question, first you use var myElement = createElement(...);, then you do document.body.appendChild(myElement);.

Fetching data from MySQL database to html dropdown list

# here database details      
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');

$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);

echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
    echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";

# here username is the column of my table(userregistration)
# it works perfectly

How can I set NODE_ENV=production on Windows?

first in powershell type

$env:NODE_ENV="production"

then type

node fileName.js

It will work perfectly displaying all the outputs.

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

Display a float with two decimal places in Python

You could use the string formatting operator for that:

>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'

The result of the operator is a string, so you can store it in a variable, print etc.

How to process a file in PowerShell line-by-line as a stream

If you are really about to work on multi-gigabyte text files then do not use PowerShell. Even if you find a way to read it faster processing of huge amount of lines will be slow in PowerShell anyway and you cannot avoid this. Even simple loops are expensive, say for 10 million iterations (quite real in your case) we have:

# "empty" loop: takes 10 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) {} }

# "simple" job, just output: takes 20 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i } }

# "more real job": 107 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i.ToString() -match '1' } }

UPDATE: If you are still not scared then try to use the .NET reader:

$reader = [System.IO.File]::OpenText("my.log")
try {
    for() {
        $line = $reader.ReadLine()
        if ($line -eq $null) { break }
        # process the line
        $line
    }
}
finally {
    $reader.Close()
}

UPDATE 2

There are comments about possibly better / shorter code. There is nothing wrong with the original code with for and it is not pseudo-code. But the shorter (shortest?) variant of the reading loop is

$reader = [System.IO.File]::OpenText("my.log")
while($null -ne ($line = $reader.ReadLine())) {
    $line
}

Responsively change div size keeping aspect ratio

Bumming off Chris's idea, another option is to use pseudo elements so you don't need to use an absolutely positioned internal element.

<style>
.square {
    /* width within the parent.
       can be any percentage. */
    width: 100%;
}
.square:before {
    content: "";
    float: left;

    /* essentially the aspect ratio. 100% means the
       div will remain 100% as tall as it is wide, or
       square in other words.  */
    padding-bottom: 100%;
}
/* this is a clearfix. you can use whatever
   clearfix you usually use, add
   overflow:hidden to the parent element,
   or simply float the parent container. */
.square:after {
    content: "";
    display: table;
    clear: both;
}
</style>
<div class="square">
  <h1>Square</h1>
  <p>This div will maintain its aspect ratio.</p>
</div>

I've put together a demo here: http://codepen.io/tcmulder/pen/iqnDr


EDIT:

Now, bumming off of Isaac's idea, it's easier in modern browsers to simply use vw units to force aspect ratio (although I wouldn't also use vh as he does or the aspect ratio will change based on window height).

So, this simplifies things:

<style>
.square {
    /* width within the parent (could use vw instead of course) */
    width: 50%;
    /* set aspect ratio */
    height: 50vw;
}
</style>
<div class="square">
  <h1>Square</h1>
  <p>This div will maintain its aspect ratio.</p>
</div>

I've put together a modified demo here: https://codepen.io/tcmulder/pen/MdojRG?editors=1100

You could also set max-height, max-width, and/or min-height, min-width if you don't want it to grow ridiculously big or small, since it's based on the browser's width now and not the container and will grow/shrink indefinitely.

Note you can also scale the content inside the element if you set the font size to a vw measurement and all the innards to em measurements, and here's a demo for that: https://codepen.io/tcmulder/pen/VBJqLV?editors=1100

Limit Get-ChildItem recursion depth

Use this to limit the depth to 2:

Get-ChildItem \*\*\*,\*\*,\*

The way it works is that it returns the children at each depth 2,1 and 0.


Explanation:

This command

Get-ChildItem \*\*\*

returns all items with a depth of two subfolders. Adding \* adds an additional subfolder to search in.

In line with the OP question, to limit a recursive search using get-childitem you are required to specify all the depths that can be searched.

How to use fetch in typescript

A few examples follow, going from basic through to adding transformations after the request and/or error handling:

Basic:

// Implementation code where T is the returned data shape
function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json<T>()
    })

}

// Consumer
api<{ title: string; message: string }>('v1/posts/1')
  .then(({ title, message }) => {
    console.log(title, message)
  })
  .catch(error => {
    /* show error message */
  })

Data transformations:

Often you may need to do some tweaks to the data before its passed to the consumer, for example, unwrapping a top level data attribute. This is straight forward:

function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json<{ data: T }>()
    })
    .then(data => { /* <-- data inferred as { data: T }*/
      return data.data
    })
}

// Consumer - consumer remains the same
api<{ title: string; message: string }>('v1/posts/1')
  .then(({ title, message }) => {
    console.log(title, message)
  })
  .catch(error => {
    /* show error message */
  })

Error handling:

I'd argue that you shouldn't be directly error catching directly within this service, instead, just allowing it to bubble, but if you need to, you can do the following:

function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json<{ data: T }>()
    })
    .then(data => {
      return data.data
    })
    .catch((error: Error) => {
      externalErrorLogging.error(error) /* <-- made up logging service */
      throw error /* <-- rethrow the error so consumer can still catch it */
    })
}

// Consumer - consumer remains the same
api<{ title: string; message: string }>('v1/posts/1')
  .then(({ title, message }) => {
    console.log(title, message)
  })
  .catch(error => {
    /* show error message */
  })

Edit

There has been some changes since writing this answer a while ago. As mentioned in the comments, response.json<T> is no longer valid. Not sure, couldn't find where it was removed.

For later releases, you can do:

// Standard variation
function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json() as Promise<T>
    })
}


// For the "unwrapping" variation

function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json() as Promise<{ data: T }>
    })
    .then(data => {
        return data.data
    })
}

Git - Won't add files?

In such cases, please check for rules in global .gitignore file and make sure that your folder does not fit into those.

How to save an image locally using Python whose URL address I already know?

Use a simple python wget module to download the link. Usage below:

import wget
wget.download('http://www.digimouth.com/news/media/2011/09/google-logo.jpg')

Pass parameter from a batch file to a PowerShell script

Add the parameter declaration at the top of ps1 file

test.ps1

param(
  # Our preferred encoding
  [parameter(Mandatory=$false)]
  [ValidateSet("UTF8","Unicode","UTF7","ASCII","UTF32","BigEndianUnicode")]
  [string]$Encoding = "UTF8"
)

write ("Encoding : {0}" -f $Encoding)

Result

C:\temp> .\test.ps1 -Encoding ASCII
Encoding : ASCII

Spring: @Component versus @Bean

You can use @Bean to make an existing third-party class available to your Spring framework application context.

@Bean
public ViewResolver viewResolver() {

    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

    viewResolver.setPrefix("/WEB-INF/view/");
    viewResolver.setSuffix(".jsp");

    return viewResolver;
}

By using the @Bean annotation, you can wrap a third-party class (it may not have @Component and it may not use Spring), as a Spring bean. And then once it is wrapped using @Bean, it is as a singleton object and available in your Spring framework application context. You can now easily share/reuse this bean in your app using dependency injection and @Autowired.

So think of the @Bean annotation is a wrapper/adapter for third-party classes. You want to make the third-party classes available to your Spring framework application context.

By using @Bean in the code above, I'm explicitly declare a single bean because inside of the method, I'm explicitly creating the object using the new keyword. I'm also manually calling setter methods of the given class. So I can change the value of the prefix field. So this manual work is referred to as explicit creation. If I use the @Component for the same class, the bean registered in the Spring container will have default value for the prefix field.

On the other hand, when we annotate a class with @Component, no need for us to manually use the new keyword. It is handled automatically by Spring.

Creating and writing lines to a file

You'll need to deal with File System Object. See this OpenTextFile method sample.

How to get current value of RxJS Subject or Observable?

A Subject or Observable doesn't have a current value. When a value is emitted, it is passed to subscribers and the Observable is done with it.

If you want to have a current value, use BehaviorSubject which is designed for exactly that purpose. BehaviorSubject keeps the last emitted value and emits it immediately to new subscribers.

It also has a method getValue() to get the current value.

Why can't Visual Studio find my DLL?

To add to Oleg's answer:

I was able to find the DLL at runtime by appending Visual Studio's $(ExecutablePath) to the PATH environment variable in Configuration Properties->Debugging. This macro is exactly what's defined in the Configuration Properties->VC++ Directories->Executable Directories field*, so if you have that setup to point to any DLLs you need, simply adding this to your PATH makes finding the DLLs at runtime easy!

* I actually don't know if the $(ExecutablePath) macro uses the project's Executable Directories setting or the global Property Pages' Executable Directories setting. Since I have all of my libraries that I often use configured through the Property Pages, these directories show up as defaults for any new projects I create.

Force GUI update from UI Thread

It's very tempting to want to "fix" this and force a UI update, but the best fix is to do this on a background thread and not tie up the UI thread, so that it can still respond to events.

How do you disable browser Autocomplete on web form field / input tag?

I must have spent two days on this discussion before resorting to creating my own solution:

First, if it works for the task, ditch the input and use a textarea. To my knowledge, autofill/autocomplete has no business in a textarea, which is a great start in terms of what we're trying to achieve. Now you just have to change some of the default behaviors of that element to make it act like an input.

Next, you'll want to keep any long entries on the same line, like an input, and you'll want the textarea to scroll along the y-axis with the cursor. We also want to get rid of the resize box, since we're doing our best to mimic the behavior of an input, which doesn't come with a resize handle. We achieve all of this with some quick CSS:

_x000D_
_x000D_
#your-textarea {
  resize: none;
  overflow-y: hidden;
  white-space: nowrap;
}
_x000D_
_x000D_
_x000D_

Finally, you'll want to make sure the pesky scrollbar doesn't arrive to wreck the party (for those particularly long entries), so make sure your text-area doesn't show it:

_x000D_
_x000D_
#your-textarea::-webkit-scrollbar {
  display: none;
}
_x000D_
_x000D_
_x000D_

Easy peasy. We've had zero autocomplete issues with this solution.

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

I tried all the following solutions such as :

  1. Use sidekicks to delete WS.
  2. Use tf commands to delete remote server workspaces.
  3. Delete the TFS cache folder.

The following worked for me:

tf workspaces /remove:*

Change user-agent for Selenium web-driver

To build on Louis's helpful answer...

Setting the User Agent in PhantomJS

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
...
caps = DesiredCapabilities.PHANTOMJS
caps["phantomjs.page.settings.userAgent"] = "whatever you want"
driver = webdriver.PhantomJS(desired_capabilities=caps)

The only minor issue is that, unlike for Firefox and Chrome, this does not return your custom setting:

driver.execute_script("return navigator.userAgent")

So, if anyone figures out how to do that in PhantomJS, please edit my answer or add a comment below! Cheers.

Write and read a list from file

Let's define a list first:

lst=[1,2,3]

You can directly write your list to a file:

f=open("filename.txt","w")
f.write(str(lst))
f.close()

To read your list from text file first you read the file and store in a variable:

f=open("filename.txt","r")
lst=f.read()
f.close()

The type of variable lst is of course string. You can convert this string into array using eval function.

lst=eval(lst)

How to convert a pymongo.cursor.Cursor into a dict?

I suggest create a list and append dictionary into it.

x   = []
cur = db.dbname.find()
for i in cur:
    x.append(i)
print(x)

Now x is a list of dictionary, you can manipulate the same in usual python way.

Regex for string not ending with given suffix

The accepted answer is fine if you can use lookarounds. However, there is also another approach to solve this problem.

If we look at the widely proposed regex for this question:

.*[^a]$

We will find that it almost works. It does not accept an empty string, which might be a little inconvinient. However, this is a minor issue when dealing with just a one character. However, if we want to exclude whole string, e.g. "abc", then:

.*[^a][^b][^c]$

won't do. It won't accept ac, for example.

There is an easy solution for this problem though. We can simply say:

.{,2}$|.*[^a][^b][^c]$

or more generalized version:

.{,n-1}$|.*[^firstchar][^secondchar]$ where n is length of the string you want forbid (for abc it's 3), and firstchar, secondchar, ... are first, second ... nth characters of your string (for abc it would be a, then b, then c).

This comes from a simple observation that a string that is shorter than the text we won't forbid can not contain this text by definition. So we can either accept anything that is shorter("ab" isn't "abc"), or anything long enough for us to accept but without the ending.

Here's an example of find that will delete all files that are not .jpg:

find . -regex '.{,3}$|.*[^.][^j][^p][^g]$' -delete

How does the "position: sticky;" property work?

It seems like that the navbar to be stickied shouldn't be inside any div or section with other content. None of the solution were working for me until I took the navbar out of the div which the navbar shared with another topbar .I previously had topbar and navbar wrapped with a common div.

Remove Sub String by using Python

BeautifulSoup(text, features="html.parser").text 

For the people who were seeking deep info in my answer, sorry.

I'll explain it.

Beautifulsoup is a widely use python package that helps the user (developer) to interact with HTML within python.

The above like just take all the HTML text (text) and cast it to Beautifulsoup object - that means behind the sense its parses everything up (Every HTML tag within the given text)

Once done so, we just request all the text from within the HTML object.

re.sub erroring with "Expected string or bytes-like object"

As you stated in the comments, some of the values appeared to be floats, not strings. You will need to change it to strings before passing it to re.sub. The simplest way is to change location to str(location) when using re.sub. It wouldn't hurt to do it anyways even if it's already a str.

letters_only = re.sub("[^a-zA-Z]",  # Search for all non-letters
                          " ",          # Replace all non-letters with spaces
                          str(location))

How do I grant read access for a user to a database in SQL Server?

This is a two-step process:

  1. you need to create a login to SQL Server for that user, based on its Windows account

    CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
    
  2. you need to grant this login permission to access a database:

    USE (your database)
    CREATE USER (username) FOR LOGIN (your login name)
    

Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader database role to read all tables.

USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'

jQuery: select an element's class and id at the same time?

Just to add that the answer that Alex provided worked for me, and not the one that is highlighted as an answer.

This one didn't work for me

$('#country.save') 

But this one did:

$('#country .save') 

so my conclusion is to use the space. Now I don't know if it's to the new version of jQuery that I'm using (1.5.1), but anyway hope this helps to anyone with similar problem that I've had.

edit: Full credit for explanation (in the comment to Alex's answer) goes to Felix Kling who says:

The space is the descendant selector, i.e. A B means "Match all elements that match B which are a descendant of elements matching A". AB means "select all element that match A and B". So it really depends on what you want to achieve. #country.save and #country .save are not equivalent.

Is there a format code shortcut for Visual Studio?

Visual Studio with C# key bindings

To answer the specific question, in C# you are likely to be using the C# keyboard mapping scheme, which will use these hotkeys by default:

Ctrl+E, Ctrl+D to format the entire document.

Ctrl+E, Ctrl+F to format the selection.

You can change these in menu Tools ? Options ? Environment ? Keyboard (either by selecting a different "keyboard mapping scheme", or binding individual keys to the commands "Edit.FormatDocument" and "Edit.FormatSelection").

If you have not chosen to use the C# keyboard mapping scheme, then you may find the key shortcuts are different. For example, if you are not using the C# bindings, the keys are likely to be:

Ctrl + K + D (Entire document)

Ctrl + K + F (Selection only)

To find out which key bindings apply in your copy of Visual Studio, look in menu Edit ? Advanced menu - the keys are displayed to the right of the menu items, so it's easy to discover what they are on your system.


(Please do not edit this answer to change the key bindings above to what your system has!)

Iterating over JSON object in C#

dynamic dynJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynJson)
{
    Console.WriteLine("{0} {1} {2} {3}\n", item.id, item.displayName, 
        item.slug, item.imageUrl);
}

or

var list = JsonConvert.DeserializeObject<List<MyItem>>(json);

public class MyItem
{
    public string id;
    public string displayName;
    public string name;
    public string slug;
    public string imageUrl;
}

Is there a regular expression to detect a valid regular expression?

Good question.

True regular languages can not decide arbitrarily deeply nested well-formed parenthesis. If your alphabet contains '(' and ')' the goal is to decide if a string of these has well-formed matching parenthesis. Since this is a necessary requirement for regular expressions the answer is no.

However, if you loosen the requirement and add recursion you can probably do it. The reason is that the recursion can act as a stack letting you "count" the current nesting depth by pushing onto this stack.

Russ Cox wrote "Regular Expression Matching Can Be Simple And Fast" which is a wonderful treatise on regex engine implementation.

Keylistener in Javascript

Did you check the small Mousetrap library?

Mousetrap is a simple library for handling keyboard shortcuts in JavaScript.

Has Facebook sharer.php changed to no longer accept detailed parameters?

Your problem is caused by the lack of markers OpenGraph, as you say it is not possible that you implement for some reason.

For you, the only solution is to use the PHP Facebook API.

  1. First you must create the application in your facebook account.
  2. When creating the application you will have two key data for your code:

    YOUR_APP_ID 
    YOUR_APP_SECRET
    
  3. Download the Facebook PHP SDK from here.

  4. You can start with this code for share content from your site:

    <?php
      // Remember to copy files from the SDK's src/ directory to a
      // directory in your application on the server, such as php-sdk/
      require_once('php-sdk/facebook.php');
    
      $config = array(
        'appId' => 'YOUR_APP_ID',
        'secret' => 'YOUR_APP_SECRET',
        'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
      );
    
      $facebook = new Facebook($config);
      $user_id = $facebook->getUser();
    ?>
    <html>
      <head></head>
      <body>
    
      <?php
        if($user_id) {
    
          // We have a user ID, so probably a logged in user.
          // If not, we'll get an exception, which we handle below.
          try {
            $ret_obj = $facebook->api('/me/feed', 'POST',
                                        array(
                                          'link' => 'www.example.com',
                                          'message' => 'Posting with the PHP SDK!'
                                     ));
            echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
    
            // Give the user a logout link 
            echo '<br /><a href="' . $facebook->getLogoutUrl() . '">logout</a>';
          } catch(FacebookApiException $e) {
            // If the user is logged out, you can have a 
            // user ID even though the access token is invalid.
            // In this case, we'll get an exception, so we'll
            // just ask the user to login again here.
            $login_url = $facebook->getLoginUrl( array(
                           'scope' => 'publish_stream'
                           )); 
            echo 'Please <a href="' . $login_url . '">login.</a>';
            error_log($e->getType());
            error_log($e->getMessage());
          }   
        } else {
    
          // No user, so print a link for the user to login
          // To post to a user's wall, we need publish_stream permission
          // We'll use the current URL as the redirect_uri, so we don't
          // need to specify it here.
          $login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
          echo 'Please <a href="' . $login_url . '">login.</a>';
    
        } 
    
      ?>      
    
      </body> 
    </html>
    

You can find more examples in the Facebook Developers site:

https://developers.facebook.com/docs/reference/php

Opening a SQL Server .bak file (Not restoring!)

The only workable solution is to restore the .bak file. The contents and the structure of those files are not documented and therefore, there's really no way (other than an awful hack) to get this to work - definitely not worth your time and the effort!

The only tool I'm aware of that can make sense of .bak files without restoring them is Red-Gate SQL Compare Professional (and the accompanying SQL Data Compare) which allow you to compare your database structure against the contents of a .bak file. Red-Gate tools are absolutely marvelous - highly recommended and well worth every penny they cost!

And I just checked their web site - it does seem that you can indeed restore a single table from out of a .bak file with SQL Compare Pro ! :-)

How to determine an interface{} value's "real" type?

Type switches can also be used with reflection stuff:

var str = "hello!"
var obj = reflect.ValueOf(&str)

switch obj.Elem().Interface().(type) {
case string:
    log.Println("obj contains a pointer to a string")
default:
    log.Println("obj contains something else")
}

Can't run Curl command inside my Docker Container

Ran into this same issue while using the CURL command inside my Dockerfile. As Gilles pointed out, we have to install curl first. These are the commands to be added in the 'Dockerfile'.

FROM ubuntu:16.04

# Install prerequisites
RUN apt-get update && apt-get install -y \
curl
CMD /bin/bash

Using HTTPS with REST in Java

Something to keep in mind is that this error isn't only due to self signed certs. The new Entrust CA certs fail with the same error, and the right thing to do is to update the server with the appropriate root certs, not to disable this important security feature.

Javascript string replace with regex to strip off illegal characters

I tend to look at it from the inverse perspective which may be what you intended:

What characters do I want to allow?

This is because there could be lots of characters that make in into a string somehow that blow stuff up that you wouldn't expect.

For example this one only allows for letters and numbers removing groups of invalid characters replacing them with a hypen:

"This¢£«±Ÿ÷could&*()\/<>be!@#$%^bad".replace(/([^a-z0-9]+)/gi, '-');
//Result: "This-could-be-bad"

Any difference between await Promise.all() and multiple await?

First difference - Fail Fast

I agree with @zzzzBov's answer, but the "fail fast" advantage of Promise.all is not the only difference. Some users in the comments have asked why using Promise.all is worth it when it's only faster in the negative scenario (when some task fails). And I ask, why not? If I have two independent async parallel tasks and the first one takes a very long time to resolve but the second is rejected in a very short time, why leave the user to wait for the longer call to finish to receive an error message? In real-life applications we must consider the negative scenario. But OK - in this first difference you can decide which alternative to use: Promise.all vs. multiple await.

Second difference - Error Handling

But when considering error handling, YOU MUST use Promise.all. It is not possible to correctly handle errors of async parallel tasks triggered with multiple awaits. In the negative scenario you will always end with UnhandledPromiseRejectionWarning and PromiseRejectionHandledWarning, regardless of where you use try/ catch. That is why Promise.all was designed. Of course someone could say that we can suppress those errors using process.on('unhandledRejection', err => {}) and process.on('rejectionHandled', err => {}) but this is not good practice. I've found many examples on the internet that do not consider error handling for two or more independent async parallel tasks at all, or consider it but in the wrong way - just using try/ catch and hoping it will catch errors. It's almost impossible to find good practice in this.

Summary

TL;DR: Never use multiple await for two or more independent async parallel tasks, because you will not be able to handle errors correctly. Always use Promise.all() for this use case.

Async/ await is not a replacement for Promises, it's just a pretty way to use promises. Async code is written in "sync style" and we can avoid multiple thens in promises.

Some people say that when using Promise.all() we can't handle task errors separately, and that we can only handle the error from the first rejected promise (separate handling can be useful e.g. for logging). This is not a problem - see "Addition" heading at the bottom of this answer.

Examples

Consider this async task...

const task = function(taskNum, seconds, negativeScenario) {
  return new Promise((resolve, reject) => {
    setTimeout(_ => {
      if (negativeScenario)
        reject(new Error('Task ' + taskNum + ' failed!'));
      else
        resolve('Task ' + taskNum + ' succeed!');
    }, seconds * 1000)
  });
};

When you run tasks in the positive scenario there is no difference between Promise.all and multiple awaits. Both examples end with Task 1 succeed! Task 2 succeed! after 5 seconds.

// Promise.all alternative
const run = async function() {
  // tasks run immediate in parallel and wait for both results
  let [r1, r2] = await Promise.all([
    task(1, 5, false),
    task(2, 5, false)
  ]);
  console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: Task 1 succeed! Task 2 succeed!
// multiple await alternative
const run = async function() {
  // tasks run immediate in parallel
  let t1 = task(1, 5, false);
  let t2 = task(2, 5, false);
  // wait for both results
  let r1 = await t1;
  let r2 = await t2;
  console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: Task 1 succeed! Task 2 succeed!

However, when the first task takes 10 seconds and succeeds, and the second task takes 5 seconds but fails, there are differences in the errors issued.

// Promise.all alternative
const run = async function() {
  let [r1, r2] = await Promise.all([
      task(1, 10, false),
      task(2, 5, true)
  ]);
  console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// multiple await alternative
const run = async function() {
  let t1 = task(1, 10, false);
  let t2 = task(2, 5, true);
  let r1 = await t1;
  let r2 = await t2;
  console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
// at 10th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!

We should already notice here that we are doing something wrong when using multiple awaits in parallel. Let's try handling the errors:

// Promise.all alternative
const run = async function() {
  let [r1, r2] = await Promise.all([
    task(1, 10, false),
    task(2, 5, true)
  ]);
  console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Caught error', err); });
// at 5th sec: Caught error Error: Task 2 failed!

As you can see, to successfully handle errors, we need to add just one catch to the run function and add code with catch logic into the callback. We do not need to handle errors inside the run function because async functions do this automatically - promise rejection of the task function causes rejection of the run function.

To avoid a callback we can use "sync style" (async/ await + try/ catch)
try { await run(); } catch(err) { }
but in this example it's not possible, because we can't use await in the main thread - it can only be used in async functions (because nobody wants to block main thread). To test if handling works in "sync style" we can call the run function from another async function or use an IIFE (Immediately Invoked Function Expression: MDN):

(async function() { 
  try { 
    await run(); 
  } catch(err) { 
    console.log('Caught error', err); 
  }
})();

This is the only correct way to run two or more async parallel tasks and handle errors. You should avoid the examples below.

Bad Examples

// multiple await alternative
const run = async function() {
  let t1 = task(1, 10, false);
  let t2 = task(2, 5, true);
  let r1 = await t1;
  let r2 = await t2;
  console.log(r1 + ' ' + r2);
};

We can try to handle errors in the code above in several ways...

try { run(); } catch(err) { console.log('Caught error', err); };
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled 

... nothing got caught because it handles sync code but run is async.

run().catch(err => { console.log('Caught error', err); });
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: Caught error Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)

... huh? We see firstly that the error for task 2 was not handled and later that it was caught. Misleading and still full of errors in console, it's still unusable this way.

(async function() { try { await run(); } catch(err) { console.log('Caught error', err); }; })();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: Caught error Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)

... the same as above. User @Qwerty in his deleted answer asked about this strange behavior where an error seems to be caught but are also unhandled. We catch error the because run() is rejected on the line with the await keyword and can be caught using try/ catch when calling run(). We also get an unhandled error because we are calling an async task function synchronously (without the await keyword), and this task runs and fails outside the run() function.
It is similar to when we are not able to handle errors by try/ catch when calling some sync function which calls setTimeout:

function test() {
  setTimeout(function() { 
    console.log(causesError); 
    }, 0);
}; 
try { 
  test(); 
} catch(e) { 
  /* this will never catch error */ 
}`.

Another poor example:

const run = async function() {
  try {
    let t1 = task(1, 10, false);
    let t2 = task(2, 5, true);
    let r1 = await t1;
    let r2 = await t2;
  }
  catch (err) {
    return new Error(err);
  }
  console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Caught error', err); });
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)

... "only" two errors (3rd one is missing) but nothing is caught.

Addition (handling separate task errors and also first-fail error)

const run = async function() {
  let [r1, r2] = await Promise.all([
    task(1, 10, true).catch(err => { console.log('Task 1 failed!'); throw err; }),
    task(2, 5, true).catch(err => { console.log('Task 2 failed!'); throw err; })
  ]);
  console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Run failed (does not matter which task)!'); });
// at 5th sec: Task 2 failed!
// at 5th sec: Run failed (does not matter which task)!
// at 10th sec: Task 1 failed!

... note that in this example I rejected both tasks to better demonstrate what happens (throw err is used to fire final error).

Android: remove left margin from actionbar's custom layout

If you are adding the Toolbar via XML, you can simply add XML attributes to remove content insets.

<android.support.v7.widget.Toolbar
    xmlns:app="schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/primaryColor"
    android:contentInsetLeft="0dp"
    android:contentInsetStart="0dp"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp"
    android:contentInsetRight="0dp"
    android:contentInsetEnd="0dp"
    app:contentInsetRight="0dp"
    app:contentInsetEnd="0dp" />

How do I add to the Windows PATH variable using setx? Having weird problems

Run cmd as administrator, then:

setx /M PATH "%PATH%;<your-new-path>"

The /M option sets the variable at SYSTEM scope. The default behaviour is to set it for the USER.

TL;DR

The truncation issue happens because when you echo %PATH% it will show the concatenation of SYSTEM and USER values. So when you add it in your second argument to setx, it will be fitting SYSTEM and USER values inside the USER var. When you echo again, things will be doubled.

Additionally, the /M option requires administrator privilege, so you need to open your terminal with "run as administrator", otherwise setx will complain with "access to registry path is denied".

Last thing to note: You won't see the new value when you echo %PATH% just after setting it this way, you need to close cmd and open again.

If you want to check the actual values stored in registry check this question.

Console output in a Qt GUI app?

In your .pro add

CONFIG          += console

How to "perfectly" override a dict?

All you will have to do is

class BatchCollection(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(*args, **kwargs)

OR

class BatchCollection(dict):
    def __init__(self, inpt={}):
        super(BatchCollection, self).__init__(inpt)

A sample usage for my personal use

### EXAMPLE
class BatchCollection(dict):
    def __init__(self, inpt={}):
        dict.__init__(*args, **kwargs)

    def __setitem__(self, key, item):
        if (isinstance(key, tuple) and len(key) == 2
                and isinstance(item, collections.Iterable)):
            # self.__dict__[key] = item
            super(BatchCollection, self).__setitem__(key, item)
        else:
            raise Exception(
                "Valid key should be a tuple (database_name, table_name) "
                "and value should be iterable")

Note: tested only in python3

$(this).attr("id") not working

What are you expecting $(this) to refer to?

Do you mean sel.attr("id"); perhaps?

Global environment variables in a shell script

#!/bin/bash
export FOO=bar

or

#!/bin/bash
FOO=bar
export FOO

man export:

The shell shall give the export attribute to the variables corresponding to the specified names, which shall cause them to be in the environment of subsequently executed commands. If the name of a variable is followed by = word, then the value of that variable shall be set to word.

Pandas KeyError: value not in index

Use reindex to get all columns you need. It'll preserve the ones that are already there and put in empty columns otherwise.

p = p.reindex(columns=['1Sun', '2Mon', '3Tue', '4Wed', '5Thu', '6Fri', '7Sat'])

So, your entire code example should look like this:

df = pd.read_csv(CsvFileName)

p = df.pivot_table(index=['Hour'], columns='DOW', values='Changes', aggfunc=np.mean).round(0)
p.fillna(0, inplace=True)

columns = ["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]
p = p.reindex(columns=columns)
p[columns] = p[columns].astype(int)

Class name does not name a type in C++

The problem is that you need to include B.h in your A.h file. The problem is that in the definition of A, the compiler still doesn't know what B is. You should include all the definitions of all the types you are using.

What's the name for hyphen-separated case?

This casing can also be called a "slug", and the process of turning a phrase into it "slugify".

https://hexdocs.pm/slugify/Slug.html

How can I check for "undefined" in JavaScript?

If it is undefined, it will not be equal to a string that contains the characters "undefined", as the string is not undefined.

You can check the type of the variable:

if (typeof(something) != "undefined") ...

Sometimes you don't even have to check the type. If the value of the variable can't evaluate to false when it's set (for example if it's a function), then you can just evalue the variable. Example:

if (something) {
  something(param);
}

How to access parent Iframe from JavaScript

Simply call window.frameElement from your framed page. If the page is not in a frame then frameElement will be null.

The other way (getting the window element inside a frame is less trivial) but for sake of completeness:

/**
 * @param f, iframe or frame element
 * @return Window object inside the given frame
 * @effect will append f to document.body if f not yet part of the DOM
 * @see Window.frameElement
 * @usage myFrame.document = getFramedWindow(myFrame).document;
 */
function getFramedWindow(f)
{
    if(f.parentNode == null)
        f = document.body.appendChild(f);
    var w = (f.contentWindow || f.contentDocument);
    if(w && w.nodeType && w.nodeType==9)
        w = (w.defaultView || w.parentWindow);
    return w;
}

How to write character & in android strings.xml

Mac and Android studio users:

Type your char such as & in the string.xml or layout and choose "Option" and "return" keys. Please refer the screen shot

Event system in Python

I created an EventManager class (code at the end). The syntax is the following:

#Create an event with no listeners assigned to it
EventManager.addEvent( eventName = [] )

#Create an event with listeners assigned to it
EventManager.addEvent( eventName = [fun1, fun2,...] )

#Create any number event with listeners assigned to them
EventManager.addEvent( eventName1 = [e1fun1, e1fun2,...], eventName2 = [e2fun1, e2fun2,...], ... )

#Add or remove listener to an existing event
EventManager.eventName += extra_fun
EventManager.eventName -= removed_fun

#Delete an event
del EventManager.eventName

#Fire the event
EventManager.eventName()

Here is an Example:

def hello(name):
    print "Hello {}".format(name)
    
def greetings(name):
    print "Greetings {}".format(name)

EventManager.addEvent( salute = [greetings] )
EventManager.salute += hello

print "\nInitial salute"
EventManager.salute('Oscar')

print "\nNow remove greetings"
EventManager.salute -= greetings
EventManager.salute('Oscar')

Output:

Initial salute
Greetings Oscar
Hello Oscar

Now remove greetings
Hello Oscar

EventManger Code:

class EventManager:
    
    class Event:
        def __init__(self,functions):
            if type(functions) is not list:
                raise ValueError("functions parameter has to be a list")
            self.functions = functions
            
        def __iadd__(self,func):
            self.functions.append(func)
            return self
            
        def __isub__(self,func):
            self.functions.remove(func)
            return self
            
        def __call__(self,*args,**kvargs):
            for func in self.functions : func(*args,**kvargs)
            
    @classmethod
    def addEvent(cls,**kvargs):
        """
        addEvent( event1 = [f1,f2,...], event2 = [g1,g2,...], ... )
        creates events using **kvargs to create any number of events. Each event recieves a list of functions,
        where every function in the list recieves the same parameters.
        
        Example:
        
        def hello(): print "Hello ",
        def world(): print "World"
        
        EventManager.addEvent( salute = [hello] )
        EventManager.salute += world
        
        EventManager.salute()
        
        Output:
        Hello World
        """
        for key in kvargs.keys():
            if type(kvargs[key]) is not list:
                raise ValueError("value has to be a list")
            else:
                kvargs[key] = cls.Event(kvargs[key])
        
        cls.__dict__.update(kvargs)

How to use border with Bootstrap

As of Bootstrap 3, you can use Panel classes:

<div class="panel panel-default">Surrounded by border</div>

In Bootstrap 4, you can use Border classes:

<div class="border border-secondary">Surrounded by border</div>

HTML - how to make an entire DIV a hyperlink?

Why don't you just do this

<a href="yoururl.html"><div>...</div></a>

That should work fine and will prompt the "clickable item" cursor change, which the aforementioned solution will not do.

How to make a HTML Page in A4 paper size page(s)?

A4 size is 210x297mm

So you can set the HTML page to fit those sizes with CSS:

html,body{
    height:297mm;
    width:210mm;
}

libxml install error using pip

These two packages need to be installed separately and usually can't be installed using pip...Therefore, for FreeBSD:

Download a compressed snapshot of the Ports Collection into /var/db/portsnap:
# portsnap fetch
When running Portsnap for the first time, extract the snapshot into /usr/ports:
# portsnap extract
After the first use of Portsnap has been completed as shown above, /usr/ports can be updated as needed by running:
# portsnap fetch
# portsnap update

Now Install:
cd /usr/ports/textproc/libxml2
make install clean

cd /usr/ports/textproc/libxslt
make install clean

You should be good to go...

Command to find information about CPUs on a UNIX machine

Firstly, it probably depends which version of Solaris you're running, but also what hardware you have.

On SPARC at least, you have psrinfo to show you processor information, which run on its own will show you the number of CPUs the machine sees. psrinfo -p shows you the number of physical processors installed. From that you can deduce the number of threads/cores per physical processors.

prtdiag will display a fair bit of info about the hardware in your machine. It looks like on a V240 you do get memory channel info from prtdiag, but you don't on a T2000. I guess that's an architecture issue between UltraSPARC IIIi and UltraSPARC T1.

What is the fastest way to compare two sets in Java?

I think method reference with equals method can be used. We assume that the object type without a shadow of a doubt has its own comparison method. Plain and simple example is here,

Set<String> set = new HashSet<>();
set.addAll(Arrays.asList("leo","bale","hanks"));

Set<String> set2 = new HashSet<>();
set2.addAll(Arrays.asList("hanks","leo","bale"));

Predicate<Set> pred = set::equals;
boolean result = pred.test(set2);
System.out.println(result);   // true

How to represent the double quotes character (") in regex?

you need to use backslash before ". like \"

From the doc here you can see that

A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.

and " (double quote) is a escacpe sequence

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");

How to remove index.php from URLs?

I tried everything on the post but nothing had worked. I then changed the .htaccess snippet that ErJab put up to read:

RewriteRule ^(.*)$ 'folder_name'/index.php/$1 [L]

The above line fixed it for me. where *folder_name* is the magento root folder.

Hope this helps!

Define an <img>'s src attribute in CSS

They are right. IMG is a content element and CSS is about design. But, how about when you use some content elements or properties for design purposes? I have IMG across my web pages that must change if i change the style (the CSS).

Well this is a solution for defining IMG presentation (no really the image) in CSS style.
1: create a 1x1 transparent gif or png.
2: Assign propery "src" of IMG to that image.
3: Define final presentation with "background-image" in the CSS style.

It works like a charm :)

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

On CentOS Linux release 7.5.1804, we were able to make this work by editing /etc/selinux/config and changing the setting of SELINUX like so:

SELINUX=disabled

Open page in new window without popup blocking

A browser will only open a tab/popup without the popup blocker warning if the command to open the tab/popup comes from a trusted event. That means the user has to actively click somewhere to open a popup.

In your case, the user performs a click so you have the trusted event. You do lose that trusted context, however, by performing the Ajax request. Your success handler does not have that event anymore. The only way to circumvent this is to perform a synchronous Ajax request which will block your browser while it runs, but will preserve the event context.

In jQuery this should do the trick:

$.ajax({
 url: 'http://yourserver/',
 data: 'your image',
 success: function(){window.open(someUrl);},
 async: false
});

Here is your answer: Open new tab without popup blocker after ajax call on user click

Where is the Docker daemon log?

If your OS is using systemd then you can view docker daemon log with:

sudo journalctl -fu docker.service

How to add List<> to a List<> in asp.net

  1. Use Concat or Union extension methods. You have to make sure that you have this direction using System.Linq; in order to use LINQ extensions methods.

  2. Use the AddRange method.

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

It looks like someone might have revoked the permissions on sys.configurations for the public role. Or denied access to this view to this particular user. Or the user has been created after the public role was removed from the sys.configurations tables.

Provide SELECT permission to public user sys.configurations object.

Difference between HashMap and Map in Java..?

Map<K,V> is an interface, HashMap<K,V> is a class that implements Map.

you can do

Map<Key,Value> map = new HashMap<Key,Value>();

Here you have a link to the documentation of each one: Map, HashMap.

How to convert a negative number to positive?

The inbuilt function abs() would do the trick.

positivenum = abs(negativenum)

X-Frame-Options on apache

See X-Frame-Options header on error response

You can simply add following line to .htaccess

Header always unset X-Frame-Options

Print the stack trace of an exception

Throwable.printStackTrace(..) can take a PrintWriter or PrintStream argument:

} catch (Exception ex) {
    ex.printStackTrace(new java.io.PrintStream(yourOutputStream));
}

That said, consider using a logger interface like SLF4J with an logging implementation like LOGBack or log4j.

Do we have router.reload in vue-router?

For rerender you can use in parent component

<template>
  <div v-if="renderComponent">content</div>
</template>
<script>
export default {
   data() {
      return {
        renderComponent: true,
      };
    },
    methods: {
      forceRerender() {
        // Remove my-component from the DOM
        this.renderComponent = false;

        this.$nextTick(() => {
          // Add the component back in
          this.renderComponent = true;
        });
      }
    }
}
</script>

How would I create a UIAlertView in Swift?

Below is the reusable code for alert view and action sheet, Just write one line to show alert anywhere in application

class AlertView{

    static func show(title:String? = nil,message:String?,preferredStyle: UIAlertControllerStyle = .alert,buttons:[String] = ["Ok"],completionHandler:@escaping (String)->Void){
        let alert = UIAlertController(title: title, message: message, preferredStyle: preferredStyle)

        for button in buttons{

            var style = UIAlertActionStyle.default
            let buttonText = button.lowercased().replacingOccurrences(of: " ", with: "")
            if buttonText == "cancel"{
                style = .cancel
            }
            let action = UIAlertAction(title: button, style: style) { (_) in
                completionHandler(button)
            }
            alert.addAction(action)
        }

        DispatchQueue.main.async {
            if let app = UIApplication.shared.delegate as? AppDelegate, let rootViewController = app.window?.rootViewController {
                rootViewController.present(alert, animated: true, completion: nil)
            }

        }
    }
}

Usage :

class ViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        AlertView.show(title: "Alert", message: "Are you sure ?", preferredStyle: .alert, buttons: ["Yes","No"]) { (button) in
            print(button)
        }
    }

}

find path of current folder - cmd

Use This Code

@echo off
:: Get the current directory

for /f "tokens=* delims=/" %%A in ('cd') do set CURRENT_DIR=%%A

echo CURRENT_DIR%%A 

(echo this To confirm this code works fine)

SQL Server Express CREATE DATABASE permission denied in database 'master'

After I performed the following instructions in SSMS, everything works fine:

create login [IIS APPPOOL\MyWebAPP] from windows;

exec sp_addsrvrolemember N'IIS APPPOOL\MyWebAPP', sysadmin

Any way of using frames in HTML5?

I know your class is over, but in professional coding, let this be a lesson:

  • "Deprecated" means "avoid use; it's going to be removed in the future"
  • Deprecated things still work - just don't expect support or future-proofing
  • If the requirement requires it, and you can't negotiate it away, just use the deprecated construct.
    • If you're really concerned, develop the alternative implementation on the side and keep it ready for the inevitable failure
    • Charge for the extra work now. By requesting a deprecated feature, they are asking you to double the work. You're going to see it again anyway, so might as well front-load it.
    • When the failure happens, let the interested party know that this was what you feared; that you prepared for it, but it'll take some time
    • Deploy your solution as quickly as you can (there will be bugs)
    • Gain rep for preventing excessive downtime.

JOptionPane Input to int

This because the input that the user inserts into the JOptionPane is a String and it is stored and returned as a String.

Java cannot convert between strings and number by itself, you have to use specific functions, just use:

int ans = Integer.parseInt(JOptionPane.showInputDialog(...))

Using GCC to produce readable assembly?

Use the -S (note: capital S) switch to GCC, and it will emit the assembly code to a file with a .s extension. For example, the following command:

gcc -O2 -S -c foo.c

Port 443 in use by "Unable to open process" with PID 4

Just change the sll port in httpd-ssl.conf file. It would be under C:\xampp\apache\conf\extra. Find "443" and replace it with other values(e.g 8181), then start your apache again

How to fix/convert space indentation in Sublime Text?

I actually found it's better for my sanity to have user preferences to be defined like so:

"translate_tabs_to_spaces": true,
"tab_size": 2,
"indent_to_bracket": true,
"detect_indentation": false

The detect_indentation: false is especially important, as it forces Sublime to honor these settings in every file, as opposed to the View -> Indentation settings.

If you want to get fancy, you can also define a keyboard shortcut to automatically re-indent your code (YMMV) by pasting the following in Sublime -> Preferences -> Key Binding - User:

[
  { "keys": ["ctrl+i"], "command": "reindent" }
]

and to visualize the whitespace:

"indent_guide_options": ["draw_active"],
"trim_trailing_white_space_on_save": true,
"ensure_newline_at_eof_on_save": true,
"draw_white_space": "all",
"rulers": [120],

Random strings in Python

In python3.6+ you can use the secrets module:

The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.

In particularly, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.

In testing generation of 768bit security tokens I found:

  • random.choices() - 0.000246 secs
  • secrets.choice() - 0.003529 secs

The secrets modules is slower but outside of testing it is what you should be using for cryptographic purposes:

import string, secrets

def random_string(size):        
        letters = string.ascii_lowercase+string.ascii_uppercase+string.digits            
        return ''.join(secrets.choice(letters) for i in range(size))

print(random_string(768))

Angular 4 default radio button checked by default

getting following error

_x000D_
_x000D_
It happens:  Error: 
      ngModel cannot be used to register form controls with a parent formGroup directive.  Try using
      formGroup's partner directive "formControlName" instead.  Example:
_x000D_
_x000D_
_x000D_

How to open a new file in vim in a new window

from inside vim, use one of the following

open a new window below the current one:

:new filename.ext

open a new window beside the current one:

:vert new filename.ext

How to submit an HTML form without redirection

You need Ajax to make it happen. Something like this:

$(document).ready(function(){
    $("#myform").on('submit', function(){
        var name = $("#name").val();
        var email = $("#email").val();
        var password = $("#password").val();
        var contact = $("#contact").val();

        var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
        if(name=='' || email=='' || password=='' || contact=='')
        {
            alert("Please fill in all fields");
        }
        else
        {
            // Ajax code to submit form.
            $.ajax({
                type: "POST",
                url: "ajaxsubmit.php",
                data: dataString,
                cache: false,
                success: function(result){
                    alert(result);
                }
           });
        }
        return false;
    });
});

execute function after complete page load

This way you can handle the both cases - if the page is already loaded or not:

document.onreadystatechange = function(){
    if (document.readyState === "complete") {
       myFunction();
    }
    else {
       window.onload = function () {
          myFunction();
       };
    };
}

Codeigniter - no input file specified

I found the answer to this question here..... The problem was hosting server... I thank all who tried .... Hope this will help others

Godaddy Installation Tips

Eclipse Error: "Failed to connect to remote VM"

Increase the memory value of the properties

  • MEM_PERM_SIZE_64BIT
  • MEM_MAX_PERM_SIZE_64BIT

in setDomainEnv.cmd file from %weblogic_home%\user_projects\domains\your_domain\bin

jQuery - Check if DOM element already exists

Guess you forgot to append the item to DOM.

Check it HERE.

StringIO in Python3

On Python 3 numpy.genfromtxt expects a bytes stream. Use the following:

numpy.genfromtxt(io.BytesIO(x.encode()))

Creating a blurring overlay view

You can use UIVisualEffectView to achieve this effect. This is a native API that has been fine-tuned for performance and great battery life, plus it's easy to implement.

Swift:

//only apply the blur if the user hasn't disabled transparency effects
if !UIAccessibility.isReduceTransparencyEnabled {
    view.backgroundColor = .clear

    let blurEffect = UIBlurEffect(style: .dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    //always fill the view
    blurEffectView.frame = self.view.bounds
    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

    view.addSubview(blurEffectView) //if you have more UIViews, use an insertSubview API to place it where needed
} else {
    view.backgroundColor = .black
}

Objective-C:

//only apply the blur if the user hasn't disabled transparency effects
if (!UIAccessibilityIsReduceTransparencyEnabled()) {
    self.view.backgroundColor = [UIColor clearColor];

    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    //always fill the view
    blurEffectView.frame = self.view.bounds;
    blurEffectView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    [self.view addSubview:blurEffectView]; //if you have more UIViews, use an insertSubview API to place it where needed
} else {
    self.view.backgroundColor = [UIColor blackColor];
}

If you are presenting this view controller modally to blur the underlying content, you'll need to set the modal presentation style to Over Current Context and set the background color to clear to ensure the underlying view controller will remain visible once this is presented overtop.

Unsupported major.minor version 52.0 in my app

Gradle Scripts >> build.gradle (Module app)

Change buildToolsVersion "24.0.0" to buildToolsVersion "23.0.3"

source : experience

How do I ignore an error on 'git pull' about my local changes would be overwritten by merge?

This problem is because you have made changes locally to file/s and the same file/s exists with changes in the Git repository, so before pull/push you will need stash local changes:

To overwrite local changes of a single file:

git reset file/to/overwrite
git checkout file/to/overwrite

To overwrite all the local changes (changes in all files):

git stash
git pull
git stash pop

Also this problem may be because of you are on a branch which is not merged with the master branch.

Set an empty DateTime variable

There's no such thing as an empty date per se, do you mean something like:

DateTime? myDateTime = null;

package R does not exist

Below are worked for me.

  1. In AndroidManifest.xml file, check whether the package name is correctly typed.
  2. import com.example.appName.R; (import package _name.R;)

If the first step is not worked try the second one.

How to use variables in SQL statement in Python?

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))

Note that the parameters are passed as a tuple.

The database API does proper escaping and quoting of variables. Be careful not to use the string formatting operator (%), because

  1. it does not do any escaping or quoting.
  2. it is prone to Uncontrolled string format attacks e.g. SQL injection.

List all sequences in a Postgres db 8.1 with SQL

Get sequences by each column of each table via parsing of DEFAULT clause. This method provides info about to which column sequences are linked and does not use dependencies which may not exist for some sequences. Even pg_get_serial_sequence(sch.nspname||'.'||tbl.relname, col.attname) function found not all sequences for me!

Solution:

SELECT
    seq_sch.nspname  AS sequence_schema
  , seq.relname      AS sequence_name
  , seq_use."schema" AS used_in_schema
  , seq_use."table"  AS used_in_table
  , seq_use."column" AS used_in_column
FROM pg_class seq
  INNER JOIN pg_namespace seq_sch ON seq_sch.oid = seq.relnamespace
  LEFT JOIN (
              SELECT
                  sch.nspname AS "schema"
                , tbl.relname AS "table"
                , col.attname AS "column"
                , regexp_split_to_array(
                      TRIM(LEADING 'nextval(''' FROM
                           TRIM(TRAILING '''::regclass)' FROM
                                pg_get_expr(def.adbin, tbl.oid, TRUE)
                           )
                      )
                      , '\.'
                  )           AS column_sequence
              FROM pg_class tbl --the table
                INNER JOIN pg_namespace sch ON sch.oid = tbl.relnamespace
                --schema
                INNER JOIN pg_attribute col ON col.attrelid = tbl.oid
                --columns
                INNER JOIN pg_attrdef def ON (def.adrelid = tbl.oid AND def.adnum = col.attnum) --default values for columns
              WHERE tbl.relkind = 'r' --regular relations (tables) only
                    AND col.attnum > 0 --regular columns only
                    AND def.adsrc LIKE 'nextval(%)' --sequences only
            ) seq_use ON (seq_use.column_sequence [1] = seq_sch.nspname AND seq_use.column_sequence [2] = seq.relname)
WHERE seq.relkind = 'S' --sequences only
ORDER BY sequence_schema, sequence_name;

Note that 1 sequence can be used in multiple tables, so it can be listed in multiple rows here.

How can I represent an infinite number in Python?

In python2.x there was a dirty hack that served this purpose (NEVER use it unless absolutely necessary):

None < any integer < any string

Thus the check i < '' holds True for any integer i.

It has been reasonably deprecated in python3. Now such comparisons end up with

TypeError: unorderable types: str() < int()

JavaScript to scroll long page to DIV

There is a jQuery plugin for the general case of scrolling to a DOM element, but if performance is an issue (and when is it not?), I would suggest doing it manually. This involves two steps:

  1. Finding the position of the element you are scrolling to.
  2. Scrolling to that position.

quirksmode gives a good explanation of the mechanism behind the former. Here's my preferred solution:

function absoluteOffset(elem) {
    return elem.offsetParent && elem.offsetTop + absoluteOffset(elem.offsetParent);
}

It uses casting from null to 0, which isn't proper etiquette in some circles, but I like it :) The second part uses window.scroll. So the rest of the solution is:

function scrollToElement(elem) {
    window.scroll(absoluteOffset(elem));
}

Voila!

Leap year calculation

Leap years are arbitrary, and the system used to describe them is a man made construct. There is no why.

What I mean is there could have been a leap year every 28 years and we would have an extra week in those leap years ... but the powers that be decided to make it a day every 4 years to catch up.

It also has to do with the earth taking a pesky 365.25 days to go round the sun etc. Of course it isn't really 365.25 is it slightly less (365.242222...), so to correct for this discrepancy they decided drop the leap years that are divisible by 100.

how does multiplication differ for NumPy Matrix vs Array classes?

Reference from http://docs.scipy.org/doc/scipy/reference/tutorial/linalg.html

..., the use of the numpy.matrix class is discouraged, since it adds nothing that cannot be accomplished with 2D numpy.ndarray objects, and may lead to a confusion of which class is being used. For example,

>>> import numpy as np
>>> from scipy import linalg
>>> A = np.array([[1,2],[3,4]])
>>> A
    array([[1, 2],
           [3, 4]])
>>> linalg.inv(A)
array([[-2. ,  1. ],
      [ 1.5, -0.5]])
>>> b = np.array([[5,6]]) #2D array
>>> b
array([[5, 6]])
>>> b.T
array([[5],
      [6]])
>>> A*b #not matrix multiplication!
array([[ 5, 12],
      [15, 24]])
>>> A.dot(b.T) #matrix multiplication
array([[17],
      [39]])
>>> b = np.array([5,6]) #1D array
>>> b
array([5, 6])
>>> b.T  #not matrix transpose!
array([5, 6])
>>> A.dot(b)  #does not matter for multiplication
array([17, 39])

scipy.linalg operations can be applied equally to numpy.matrix or to 2D numpy.ndarray objects.

How do I get rid of the "cannot empty the clipboard" error?

I copied a picture (instead of text) that I had in my excel 2007 file and that solved the problem for me. The picture copied to the (then empty) clipboard. I could then copy cells normally even after clearing the clipboard of the picture. I think a graph object should also do the trick.

Why is there no xrange function in Python3?

Python 3's range type works just like Python 2's xrange. I'm not sure why you're seeing a slowdown, since the iterator returned by your xrange function is exactly what you'd get if you iterated over range directly.

I'm not able to reproduce the slowdown on my system. Here's how I tested:

Python 2, with xrange:

Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)
18.631936646865853

Python 3, with range is a tiny bit faster:

Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)
17.31399508687869

I recently learned that Python 3's range type has some other neat features, such as support for slicing: range(10,100,2)[5:25:5] is range(20, 60, 10)!

Operation must use an updatable query. (Error 3073) Microsoft Access

There is no error in the code. But the error is Thrown because of the following reason.

 - Please check weather you have given Read-write permission to MS-Access database file.

 - The Database file where it is stored (say in Folder1) is read-only..? 

suppose you are stored the database (MS-Access file) in read only folder, while running your application the connection is not force-fully opened. Hence change the file permission / its containing folder permission like in C:\Program files all most all c drive files been set read-only so changing this permission solves this Problem.

Java, "Variable name" cannot be resolved to a variable

If you look at the scope of the variable 'hoursWorked' you will see that it is a member of the class (declared as private int)

The two variables you are having trouble with are passed as parameters to the constructor.

The error message is because 'hours' is out of scope in the setter.

Custom fonts and XML layouts (Android)

I might have a simple answer for the question without extending the TextView and implementing a long code.

Code :

 TextView tv = (TextView) findViewById(R.id.textview1);
    tv.setTypeface(Typeface.createFromAsset(getAssets(), "font.ttf"));

Place the custom font file in assets folder as usual and try this. It works for me. I just dont understand why peter has given such a huge code for this simple thing or he has given his answer in old version.

How does one sum only those rows in excel not filtered out?

When you use autofilter to filter results, Excel doesn't even bother to hide them: it just sets the height of the row to zero (up to 2003 at least, not sure on 2007).

So the following custom function should give you a starter to do what you want (tested with integers, haven't played with anything else):

Function SumVis(r As Range)
    Dim cell As Excel.Range
    Dim total As Variant

    For Each cell In r.Cells
        If cell.Height <> 0 Then
            total = total + cell.Value
        End If
    Next

    SumVis = total
End Function

Edit:

You'll need to create a module in the workbook to put the function in, then you can just call it on your sheet like any other function (=SumVis(A1:A14)). If you need help setting up the module, let me know.

Android Studio Checkout Github Error "CreateProcess=2" (Windows)

I found what I think is a faster solution. Install Git for Windows from here: http://git-scm.com/download/win

That automatically adds its path to the system variable during installation if you tell the installer to do so (it asks for that). So you don't have to edit anything manually.

Just close and restart Android Studio if it's open and you're ready to go.

wizard sample

PHP: How to use array_filter() to filter array keys?

With this function you can filter a multidimensional array

function filter_array_keys($array,$filter_keys=array()){

    $l=array(&$array);
    $c=1;
    //This first loop will loop until the count var is stable//
    for($r=0;$r<$c;$r++){
        //This loop will loop thru the child element list//
        $keys = array_keys($l[$r]);

        for($z=0;$z<count($l[$r]);$z++){
            $object = &$l[$r][$keys[$z]];

            if(is_array($object)){
                $i=0;
                $keys_on_array=array_keys($object);
                $object=array_filter($object,function($el) use(&$i,$keys_on_array,$filter_keys){
                    $key = $keys_on_array[$i];
                    $i++;

                    if(in_array($key,$filter_keys) || is_int($key))return false;                
                    return true;                        
                });
            }

            if(is_array($l[$r][$keys[$z]])){
                $l[] = &$l[$r][$keys[$z]];
                $c++;
            }//IF           
        }//FOR
    }//FOR  

    return $l[0];

}

pyplot axes labels for subplots

The methods in the other answers will not work properly when the yticks are large. The ylabel will either overlap with ticks, be clipped on the left or completely invisible/outside of the figure.

I've modified Hagne's answer so it works with more than 1 column of subplots, for both xlabel and ylabel, and it shifts the plot to keep the ylabel visible in the figure.

def set_shared_ylabel(a, xlabel, ylabel, labelpad = 0.01, figleftpad=0.05):
    """Set a y label shared by multiple axes
    Parameters
    ----------
    a: list of axes
    ylabel: string
    labelpad: float
        Sets the padding between ticklabels and axis label"""

    f = a[0,0].get_figure()
    f.canvas.draw() #sets f.canvas.renderer needed below

    # get the center position for all plots
    top = a[0,0].get_position().y1
    bottom = a[-1,-1].get_position().y0

    # get the coordinates of the left side of the tick labels
    x0 = 1
    x1 = 1
    for at_row in a:
        at = at_row[0]
        at.set_ylabel('') # just to make sure we don't and up with multiple labels
        bboxes, _ = at.yaxis.get_ticklabel_extents(f.canvas.renderer)
        bboxes = bboxes.inverse_transformed(f.transFigure)
        xt = bboxes.x0
        if xt < x0:
            x0 = xt
            x1 = bboxes.x1
    tick_label_left = x0

    # shrink plot on left to prevent ylabel clipping
    # (x1 - tick_label_left) is the x coordinate of right end of tick label,
    # basically how much padding is needed to fit tick labels in the figure
    # figleftpad is additional padding to fit the ylabel
    plt.subplots_adjust(left=(x1 - tick_label_left) + figleftpad)

    # set position of label, 
    # note that (figleftpad-labelpad) refers to the middle of the ylabel
    a[-1,-1].set_ylabel(ylabel)
    a[-1,-1].yaxis.set_label_coords(figleftpad-labelpad,(bottom + top)/2, transform=f.transFigure)

    # set xlabel
    y0 = 1
    for at in axes[-1]:
        at.set_xlabel('')  # just to make sure we don't and up with multiple labels
        bboxes, _ = at.xaxis.get_ticklabel_extents(fig.canvas.renderer)
        bboxes = bboxes.inverse_transformed(fig.transFigure)
        yt = bboxes.y0
        if yt < y0:
            y0 = yt
    tick_label_bottom = y0

    axes[-1, -1].set_xlabel(xlabel)
    axes[-1, -1].xaxis.set_label_coords((left + right) / 2, tick_label_bottom - labelpad, transform=fig.transFigure)

It works for the following example, while Hagne's answer won't draw ylabel (since it's outside of the canvas) and KYC's ylabel overlaps with the tick labels:

import matplotlib.pyplot as plt
import itertools

fig, axes = plt.subplots(3, 4, sharey='row', sharex=True, squeeze=False)
fig.subplots_adjust(hspace=.5)
for i, a in enumerate(itertools.chain(*axes)):
    a.plot([0,4**i], [0,4**i])
    a.set_title(i)
set_shared_ylabel(axes, 'common X', 'common Y')
plt.show()

Alternatively, if you are fine with colorless axis, I've modified Julian Chen's solution so ylabel won't overlap with tick labels.

Basically, we just have to set ylims of the colorless so it matches the largest ylims of the subplots so the colorless tick labels sets the correct location for the ylabel.

Again, we have to shrink the plot to prevent clipping. Here I've hard coded the amount to shrink, but you can play around to find a number that works for you or calculate it like in the method above.

import matplotlib.pyplot as plt
import itertools

fig, axes = plt.subplots(3, 4, sharey='row', sharex=True, squeeze=False)
fig.subplots_adjust(hspace=.5)
miny = maxy = 0
for i, a in enumerate(itertools.chain(*axes)):
    a.plot([0,4**i], [0,4**i])
    a.set_title(i)
    miny = min(miny, a.get_ylim()[0])
    maxy = max(maxy, a.get_ylim()[1])

# add a big axes, hide frame
# set ylim to match the largest range of any subplot
ax_invis = fig.add_subplot(111, frameon=False)
ax_invis.set_ylim([miny, maxy])

# hide tick and tick label of the big axis
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
plt.xlabel("common X")
plt.ylabel("common Y")

# shrink plot to prevent clipping
plt.subplots_adjust(left=0.15)
plt.show()

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

How to delete files older than X hours

You could to this trick: create a file 1 hour ago, and use the -newer file argument.

(Or use touch -t to create such a file).

ssl_error_rx_record_too_long and Apache SSL

In my case I had to change the <VirtualHost *> back to <VirtualHost *:80> (which is the default on Ubuntu). Otherwise, the port 443 wasn't using SSL and was sending plain HTML back to the browser.

You can check whether this is your case quite easily: just connect to your server http://www.example.com:443. If you see plain HTML, your Apache is not using SSL on port 443 at all, most probably due to a VirtualHost misconfiguration.

Cheers!

Getters \ setters for dummies

Although often we are used to seeing objects with public properties without any access control, JavaScript allows us to accurately describe properties. In fact, we can use descriptors in order to control how a property can be accessed and which logic we can apply to it. Consider the following example:

var employee = {
    first: "Boris",
    last: "Sergeev",
    get fullName() {
        return this.first + " " + this.last;
    },
    set fullName(value) {
        var parts = value.toString().split(" ");
        this.first = parts[0] || "";
        this.last = parts[1] || "";
    },
    email: "[email protected]"
};

The final result:

console.log(employee.fullName); //Boris Sergeev
employee.fullName = "Alex Makarenko";

console.log(employee.first);//Alex
console.log(employee.last);//Makarenko
console.log(employee.fullName);//Alex Makarenko

Add tooltip to font awesome icon

Simply use title in tag like

<i class="fa fa-edit" title="Edit Mode"></i>

This will show 'Edit Mode' when hover that icon.

Difference between a user and a schema in Oracle?

User: Access to resource of the database. Like a key to enter a house.

Schema: Collection of information about database objects. Like Index in your book which contains the short information about the chapter.

Look here for details

Bootstrap 3.0: How to have text and input on same line?

In Bootstrap 4 for Horizontal element you can use .row with .col-*-* classes to specify the width of your labels and controls. see this link.

And if you want to display a series of labels, form controls, and buttons on a single horizontal row you can use .form-inline for more info this link

How do I undo a checkout in git?

You probably want git checkout master, or git checkout [branchname].

Swipe ListView item From right to left show delete button

An app is available that demonstrates a listview that combines both swiping-to-delete and dragging to reorder items. The code is based on Chet Haase's code for swiping-to-delete and Daniel Olshansky's code for dragging-to-reorder.

Chet's code deletes an item immediately. I improved on this by making it function more like Gmail where swiping reveals a bottom view that indicates that the item is deleted but provides an Undo button where the user has the possibility to undo the deletion. Chet's code also has a bug in it. If you have less items in the listview than the height of the listview is and you delete the last item, the last item appears to not be deleted. This was fixed in my code.

Daniel's code requires pressing long on an item. Many users find this unintuitive as it tends to be a hidden function. Instead, I modified the code to allow for a "Move" button. You simply press on the button and drag the item. This is more in line with the way the Google News app works when you reorder news topics.

The source code along with a demo app is available at: https://github.com/JohannBlake/ListViewOrderAndSwipe

Chet and Daniel are both from Google.

Chet's video on deleting items can be viewed at: https://www.youtube.com/watch?v=YCHNAi9kJI4

Daniel's video on reordering items can be viewed at: https://www.youtube.com/watch?v=_BZIvjMgH-Q

A considerable amount of work went into gluing all this together to provide a seemless UI experience, so I'd appreciate a Like or Up Vote. Please also star the project in Github.

"X does not name a type" error in C++

On a related note, if you had:

    class User; // let the compiler know such a class will be defined

    class MyMessageBox
    {
    public:
        User* myUser;
    };

    class User
    {
    public:
        // also ok, since it's now defined
        MyMessageBox dataMsgBox;
    };

Then that would also work, because the User is defined in MyMessageBox as a pointer

What's the difference between process.cwd() vs __dirname?

As per node js doc process.cwd()

cwd is a method of global object process, returns a string value which is the current working directory of the Node.js process.

As per node js doc __dirname

The directory name of current script as a string value. __dirname is not actually a global but rather local to each module.

Let me explain with example,

suppose we have a main.js file resides inside C:/Project/main.js and running node main.js both these values return same file

or simply with following folder structure

Project 
+-- main.js
+--lib
   +-- script.js

main.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

suppose we have another file script.js files inside a sub directory of project ie C:/Project/lib/script.js and running node main.js which require script.js

main.js

require('./lib/script.js')
console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

script.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project\lib
console.log(__dirname===process.cwd())
// false

How many characters can a Java String have?

The heap part gets worse, my friends. UTF-16 isn't guaranteed to be limited to 16 bits and can expand to 32

How to set standard encoding in Visual Studio

The Problem is Windows and Microsoft applications put byte order marks at the beginning of all your files so other applications often break or don't read these UTF-8 encoding marks. I perfect example of this problem was triggering quirsksmode in old IE web browsers when encoding in UTF-8 as browsers often display web pages based on what encoding falls at the start of the page. It makes a mess when other applications view those UTF-8 Visual Studio pages.

I usually do not recommend Visual Studio Extensions, but I do this one to fix that issue:

Fix File Encoding: https://vlasovstudio.com/fix-file-encoding/

The FixFileEncoding above install REMOVES the byte order mark and forces VS to save ALL FILES without signature in UTF-8. After installing go to Tools > Option then choose "FixFileEncoding". It should allow you to set all saves as UTF-8 . Add "cshtml to the list of files to always save in UTF-8 without the byte order mark as so: ".(htm|html|cshtml)$)".

Now open one of your files in Visual Studio. To verify its saving as UTF-8 go to File > Save As, then under the Save button choose "Save With Encoding". It should choose "UNICODE (Save without Signature)" by default from the list of encodings. Now when you save that page it should always save as UTF-8 without byte order mark at the beginning of the file when saving in Visual Studio.

Getting current unixtimestamp using Moment.js

Try any of these

valof = moment().valueOf();            // xxxxxxxxxxxxx
getTime = moment().toDate().getTime(); // xxxxxxxxxxxxx
unixTime =  moment().unix();           // xxxxxxxxxx
formatTimex =  moment().format('x');   // xxxxxxxxxx
unixFormatX = moment().format('X');    // xxxxxxxxxx

How to convert a PIL Image into a numpy array?

You're not saying how exactly putdata() is not behaving. I'm assuming you're doing

>>> pic.putdata(a)
Traceback (most recent call last):
  File "...blablabla.../PIL/Image.py", line 1185, in putdata
    self.im.putdata(data, scale, offset)
SystemError: new style getargs format but argument is not a tuple

This is because putdata expects a sequence of tuples and you're giving it a numpy array. This

>>> data = list(tuple(pixel) for pixel in pix)
>>> pic.putdata(data)

will work but it is very slow.

As of PIL 1.1.6, the "proper" way to convert between images and numpy arrays is simply

>>> pix = numpy.array(pic)

although the resulting array is in a different format than yours (3-d array or rows/columns/rgb in this case).

Then, after you make your changes to the array, you should be able to do either pic.putdata(pix) or create a new image with Image.fromarray(pix).

Why do we always prefer using parameters in SQL statements?

In Sql when any word contain @ sign it means it is variable and we use this variable to set value in it and use it on number area on the same sql script because it is only restricted on the single script while you can declare lot of variables of same type and name on many script. We use this variable in stored procedure lot because stored procedure are pre-compiled queries and we can pass values in these variable from script, desktop and websites for further information read Declare Local Variable, Sql Stored Procedure and sql injections.

Also read Protect from sql injection it will guide how you can protect your database.

Hope it help you to understand also any question comment me.

How to select a CRAN mirror in R

If you need to set the mirror in a non-interactive way (for example doing an rbundler install in a deploy script) you can do it in this way:

First manually run:

chooseCRANmirror()

Pick the mirror number that is best for you and remember it. Then to automate the selection:

R -e 'chooseCRANmirror(graphics=FALSE, ind=87);library(rbundler);bundle()'

Where 87 is the number of the mirror you would like to use. This snippet also installs the rbundle for you. You can omit that if you like.

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

Indeed you cannot save changes inside a foreach loop in C# using Entity Framework.

context.SaveChanges() method acts like a commit on a regular database system (RDMS).

Just make all changes (which Entity Framework will cache) and then save all of them at once calling SaveChanges() after the loop (outside of it), like a database commit command.

This works if you can save all changes at once.

How to enable MySQL Query Log?

There is bug in MySQL 5.6 version. Even mysqld show as :

    Default options are read from the following files in the given order:
C:\Windows\my.ini C:\Windows\my.cnf C:\my.ini C:\my.cnf c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.ini c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.cnf 

Realy settings are reading in following order :

    Default options are read from the following files in the given order:
C:\ProgramData\MySQL\MySQL Server 5.6\my.ini C:\Windows\my.ini C:\Windows\my.cnf C:\my.ini C:\my.cnf c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.ini c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.cnf

Check file: "C:\ProgramData\MySQL\MySQL Server 5.6\my.ini"

Hope it help somebody.

Using $_POST to get select option value from HTML

You can access values in the $_POST array by their key. $_POST is an associative array, so to access taskOption you would use $_POST['taskOption'];.

Make sure to check if it exists in the $_POST array before proceeding though.

<form method="post" action="process.php">
  <select name="taskOption">
    <option value="first">First</option>
    <option value="second">Second</option>
    <option value="third">Third</option>
  </select>
  <input type="submit" value="Submit the form"/>
</form>

process.php

<?php
   $option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
   if ($option) {
      echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
   } else {
     echo "task option is required";
     exit; 
   }

Initializing a two dimensional std::vector

The general syntax, as depicted already is:

std::vector<std::vector<int> > v (A_NUMBER, std::vector <int> (OTHER_NUMBER, DEFAULT_VALUE))  

Here, the vector 'v' can be visualised as a two dimensional array, with 'A_NUMBER' of rows, with 'OTHER_NUMBER' of columns with their initial value set to 'DEFAULT_VALUE'.

Also it can be written like this:

std::vector <int> line(OTHER_NUMBER, DEFAULT_VALUE)
std::vector<std::vector<int> > v(A_NUMBER, line)

Inputting values in a 2-D vector is similar to inputting values in a 2-D array:

for(int i = 0; i < A_NUMBER; i++) {
     for(int j = 0; j < OTHER_NUMBER; j++) {
         std::cin >> v[i][j]
     }
}

Examples have already been stated in other answers....!

7-zip commandline

Instead of the option a use option x, this will create the directories but only for extraction, not compression.

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

In my app I created a WidgetChooser widget so I can choose between widgets without conditional logic:

WidgetChooser(
      condition: true,
      trueChild: Text('This widget appears if the condition is true.'),
      falseChild: Text('This widget appears if the condition is false.'),
    );

This is the source for the WidgetChooser widget:

import 'package:flutter/widgets.dart';

class WidgetChooser extends StatelessWidget {
  final bool condition;
  final Widget trueChild;
  final Widget falseChild;

  WidgetChooser({@required this.condition, @required this.trueChild, @required this.falseChild});

  @override
  Widget build(BuildContext context) {
    if (condition) {
      return trueChild;
    } else {
      return falseChild;
    }
  }
}

How to revert a "git rm -r ."?

To regain some single files or folders one may use the following

git reset -- path/to/file
git checkout -- path/to/file

This will first recreate the index entries for path/to/file and recreate the file as it was in the last commit, i.e.HEAD.

Hint: one may pass a commit hash to both commands to recreate files from an older commit. See git reset --help and git checkout --help for details.

How to get "their" changes in the middle of conflicting Git rebase?

You want to use:

git checkout --ours foo/bar.java
git add foo/bar.java

If you rebase a branch feature_x against main (i.e. running git rebase main while on branch feature_x), during rebasing ours refers to main and theirs to feature_x.

As pointed out in the git-rebase docs:

Note that a rebase merge works by replaying each commit from the working branch on top of the branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped.

For further details read this thread.

TypeError: Missing 1 required positional argument: 'self'

You need to instantiate a class instance here.

Use

p = Pump()
p.getPumps()

Small example -

>>> class TestClass:
        def __init__(self):
            print("in init")
        def testFunc(self):
            print("in Test Func")


>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func

Download files in laravel using Response::download

File downloads are super simple in Laravel 5.

As @Ashwani mentioned Laravel 5 allows file downloads with response()->download() to return file for download. We no longer need to mess with any headers. To return a file we simply:

return response()->download(public_path('file_path/from_public_dir.pdf'));

from within the controller.


Reusable Download Route/Controller

Now let's make a reusable file download route and controller so we can server up any file in our public/files directory.

Create the controller:

php artisan make:controller --plain DownloadsController

Create the route in app/Http/routes.php:

Route::get('/download/{file}', 'DownloadsController@download');

Make download method in app/Http/Controllers/DownloadsController:

class DownloadsController extends Controller
{
  public function download($file_name) {
    $file_path = public_path('files/'.$file_name);
    return response()->download($file_path);
  }
}

Now simply drops some files in the public/files directory and you can server them up by linking to /download/filename.ext:

<a href="/download/filename.ext">File Name</a> // update to your own "filename.ext"

If you pulled in Laravel Collective's Html package you can use the Html facade:

{!! Html::link('download/filename.ext', 'File Name') !!}

How can I wait for a thread to finish with .NET?

Add

t1.Join();    // Wait until thread t1 finishes

after you start it, but that won't accomplish much as it's essentialy the same result as running on the main thread!

I can highly recommended reading Joe Albahari's Threading in C# free e-book, if you want to gain an understanding of threading in .NET.

Python json.loads shows ValueError: Extra data

As you can see in the following example, json.loads (and json.load) does not decode multiple json object.

>>> json.loads('{}')
{}
>>> json.loads('{}{}') # == json.loads(json.dumps({}) + json.dumps({}))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\json\__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 368, in decode
    raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 3 - line 1 column 5 (char 2 - 4)

If you want to dump multiple dictionaries, wrap them in a list, dump the list (instead of dumping dictionaries multiple times)

>>> dict1 = {}
>>> dict2 = {}
>>> json.dumps([dict1, dict2])
'[{}, {}]'
>>> json.loads(json.dumps([dict1, dict2]))
[{}, {}]

PHP, Get tomorrows date from date

First, coming up with correct abstractions is always a key. key to readability, maintainability, and extendability.

Here, quite obvious candidate is an ISO8601DateTime. There are at least two implementations: first one is a parsed datetime from a string, and the second one is tomorrow. Hence, there are two classes that can be used, and their combination results in (almost) desired outcome:

new Tomorrow(new FromISO8601('2013-01-22'));

Both objects are an ISO8601 datetime, so their textual representation is not exactly what you need. So the final stroke is to make them take a date-form:

new Date(
    new Tomorrow(
        new FromISO8601('2013-01-22')
    )
);

Since you need a textual representation, not just an object, you invoke a value() method.

For more about this approach, take a look at this post.

What's the difference between lists enclosed by square brackets and parentheses in Python?

They are not lists, they are a list and a tuple. You can read about tuples in the Python tutorial. While you can mutate lists, this is not possible with tuples.

In [1]: x = (1, 2)

In [2]: x[0] = 3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/user/<ipython console> in <module>()

TypeError: 'tuple' object does not support item assignment

How to get current foreground activity context in android?

Update 3: There is an official api added for this, please use ActivityLifecycleCallbacks instead.

Permission denied at hdfs

I had similar situation and here is my approach which is somewhat different:

 HADOOP_USER_NAME=hdfs hdfs dfs -put /root/MyHadoop/file1.txt /

What you actually do is you read local file in accordance to your local permissions but when placing file on HDFS you are authenticated like user hdfs. You can do this with other ID (beware of real auth schemes configuration but this is usually not a case).

Advantages:

  1. Permissions are kept on HDFS.
  2. You don't need sudo.
  3. You don't need actually appropriate local user 'hdfs' at all.
  4. You don't need to copy anything or change permissions because of previous points.

console.log showing contents of array object

I warmly recommend this snippet to ensure, accidentally left code pieces don't fail on clients browsers:

/* neutralize absence of firebug */
if ((typeof console) !== 'object' || (typeof console.info) !== 'function') {
    window.console = {};
    window.console.info = window.console.log = window.console.warn = function(msg) {};
    window.console.trace = window.console.error = window.console.assert = function(msg) {};
}

rather than defining an empty function, this snippet is also a good starting point for rolling your own console surrogate if needed, i.e. dumping those infos into a .debug Container, show alerts (could get plenty) or such...

If you do use firefox+firebug, console.dir() is best for dumping array output, see here.

react-router getting this.props.location in child components

(Update) V5.1 & Hooks (Requires React >= 16.8)

You can use useHistory, useLocation and useRouteMatch in your component to get match, history and location .

const Child = () => {
  const location = useLocation();
  const history = useHistory();
  const match = useRouteMatch("write-the-url-you-want-to-match-here");

  return (
    <div>{location.pathname}</div>
  )
}

export default Child

(Update) V4 & V5

You can use withRouter HOC in order to inject match, history and location in your component props.

class Child extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (
      <div>{location.pathname}</div>
    )
  }
}

export default withRouter(Child)

(Update) V3

You can use withRouter HOC in order to inject router, params, location, routes in your component props.

class Child extends React.Component {

  render() {
    const { router, params, location, routes } = this.props

    return (
      <div>{location.pathname}</div>
    )
  }
}

export default withRouter(Child)

Original answer

If you don't want to use the props, you can use the context as described in React Router documentation

First, you have to set up your childContextTypes and getChildContext

class App extends React.Component{

  getChildContext() {
    return {
      location: this.props.location
    }
  }

  render() {
    return <Child/>;
  }
}

App.childContextTypes = {
    location: React.PropTypes.object
}

Then, you will be able to access to the location object in your child components using the context like this

class Child extends React.Component{

   render() {
     return (
       <div>{this.context.location.pathname}</div>
     )
   }

}

Child.contextTypes = {
    location: React.PropTypes.object
 }

Pyspark: display a spark data frame in a table format

As mentioned by @Brent in the comment of @maxymoo's answer, you can try

df.limit(10).toPandas()

to get a prettier table in Jupyter. But this can take some time to run if you are not caching the spark dataframe. Also, .limit() will not keep the order of original spark dataframe.

Redirect all output to file using Bash on Linux?

I had trouble with a crashing program *cough PHP cough* Upon crash the shell it was ran in reports the crash reason, Segmentation fault (core dumped)

To avoid this output not getting logged, the command can be run in a subshell that will capture and direct these kind of output:

sh -c 'your_command' > your_stdout.log 2> your_stderr.err
# or
sh -c 'your_command' > your_stdout.log 2>&1

Angularjs -> ng-click and ng-show to show a div

I implemented it something this way

Controller function:

app.controller("aboutController", function(){
this.selected = true;
this.toggle = function(){
  this.selected = this.selected?false:true;
}
});

HTML:

<div ng-controller="aboutController as about">
 <div ng-click="about.toggle()">Click Me to toggle the Fruits Name</div>
 <div ng-show ="about.selected">Apple is a delicious fruit</div>
</div>

How to host google web fonts on my own server?

It is legally allowed as long as you stick to the terms of the font's license - usually the OFL.

You'll need a set of web font formats, and the Font Squirrel Webfont Generator can produce these.

But the OFL required the fonts be renamed if they are modified, and using the generator means modifying them.

How do I make bootstrap table rows clickable?

You can use in this way using bootstrap css. Just remove the active class if already assinged to any row and reassign to the current row.

    $(".table tr").each(function () {
        $(this).attr("class", "");
    });
    $(this).attr("class", "active");

How to validate IP address in Python?

I have to give a great deal of credit to Markus Jarderot for his post - the majority of my post is inspired from his.

I found that Markus' answer still fails some of the IPv6 examples in the Perl script referenced by his answer.

Here is my regex that passes all of the examples in that Perl script:

r"""^
     \s* # Leading whitespace
     # Zero-width lookaheads to reject too many quartets
     (?:
        # 6 quartets, ending IPv4 address; no wildcards
        (?:[0-9a-f]{1,4}(?::(?!:))){6}
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 0-5 quartets, wildcard, ending IPv4 address
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
        (?:::(?!:))
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 0-4 quartets, wildcard, 0-1 quartets, ending IPv4 address
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:[0-9a-f]{1,4}(?::(?!:)))?
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 0-3 quartets, wildcard, 0-2 quartets, ending IPv4 address
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:[0-9a-f]{1,4}(?::(?!:))){0,2}
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 0-2 quartets, wildcard, 0-3 quartets, ending IPv4 address
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:[0-9a-f]{1,4}(?::(?!:))){0,3}
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 0-1 quartets, wildcard, 0-4 quartets, ending IPv4 address
        (?:[0-9a-f]{1,4}){0,1}
        (?:::(?!:))
        (?:[0-9a-f]{1,4}(?::(?!:))){0,4}
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # wildcard, 0-5 quartets, ending IPv4 address
        (?:::(?!:))
        (?:[0-9a-f]{1,4}(?::(?!:))){0,5}
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 8 quartets; no wildcards
        (?:[0-9a-f]{1,4}(?::(?!:))){7}[0-9a-f]{1,4}
      |
        # 0-7 quartets, wildcard
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,6}[0-9a-f]{1,4})?
        (?:::(?!:))
      |
        # 0-6 quartets, wildcard, 0-1 quartets
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,5}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:[0-9a-f]{1,4})?
      |
        # 0-5 quartets, wildcard, 0-2 quartets
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
      |
        # 0-4 quartets, wildcard, 0-3 quartets
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
      |
        # 0-3 quartets, wildcard, 0-4 quartets
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
      |
        # 0-2 quartets, wildcard, 0-5 quartets
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
      |
        # 0-1 quartets, wildcard, 0-6 quartets
        (?:[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,5}[0-9a-f]{1,4})?
      |
        # wildcard, 0-7 quartets
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,6}[0-9a-f]{1,4})?
     )
     (?:/(?:1(?:2[0-7]|[01]\d)|\d\d?))? # With an optional CIDR routing prefix (0-128)
     \s* # Trailing whitespace
    $"""

I also put together a Python script to test all of those IPv6 examples; it's here on Pastebin because it was too large to post here.

You can run the script with test result and example arguments in the form of "[result]=[example]", so like:

python script.py Fail=::1.2.3.4: pass=::127.0.0.1 false=::: True=::1

or you can simply run all of the tests by specifying no arguments, so like:

python script.py

Anyway, I hope this helps somebody else!

Getting value of HTML Checkbox from onclick/onchange events

The short answer:

Use the click event, which won't fire until after the value has been updated, and fires when you want it to:

<label><input type='checkbox' onclick='handleClick(this);'>Checkbox</label>

function handleClick(cb) {
  display("Clicked, new value = " + cb.checked);
}

Live example | Source

The longer answer:

The change event handler isn't called until the checked state has been updated (live example | source), but because (as Tim Büthe points out in the comments) IE doesn't fire the change event until the checkbox loses focus, you don't get the notification proactively. Worse, with IE if you click a label for the checkbox (rather than the checkbox itself) to update it, you can get the impression that you're getting the old value (try it with IE here by clicking the label: live example | source). This is because if the checkbox has focus, clicking the label takes the focus away from it, firing the change event with the old value, and then the click happens setting the new value and setting focus back on the checkbox. Very confusing.

But you can avoid all of that unpleasantness if you use click instead.

I've used DOM0 handlers (onxyz attributes) because that's what you asked about, but for the record, I would generally recommend hooking up handlers in code (DOM2's addEventListener, or attachEvent in older versions of IE) rather than using onxyz attributes. That lets you attach multiple handlers to the same element and lets you avoid making all of your handlers global functions.


An earlier version of this answer used this code for handleClick:

function handleClick(cb) {
  setTimeout(function() {
    display("Clicked, new value = " + cb.checked);
  }, 0);
}

The goal seemed to be to allow the click to complete before looking at the value. As far as I'm aware, there's no reason to do that, and I have no idea why I did. The value is changed before the click handler is called. In fact, the spec is quite clear about that. The version without setTimeout works perfectly well in every browser I've tried (even IE6). I can only assume I was thinking about some other platform where the change isn't done until after the event. In any case, no reason to do that with HTML checkboxes.

How to change proxy settings in Android (especially in Chrome)

Found one solution for WIFI (works for Android 4.3, 4.4):

  1. Connect to WIFI network (e.g. 'Alex')
  2. Settings->WIFI
  3. Long tap on connected network's name (e.g. on 'Alex')
  4. Modify network config-> Show advanced options
  5. Set proxy settings

undefined reference to boost::system::system_category() when compiling

When using CMAKE and find_package, make sure it is :

find_package(Boost COMPONENTS system ...)

and not

find_package(boost COMPONENTS system ...)

Some people may have lost hours for that ...

Manage toolbar's navigation and back button from fragment in android

(Kotlin) In the activity hosting the fragment(s):

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        android.R.id.home -> {
            onBackPressed()
            return true
        }
    }
    return super.onOptionsItemSelected(item)
}

I have found that when I add fragments to a project, they show the action bar home button by default, to remove/disable it put this in onViewCreated() (use true to enable it if it is not showing):

val actionBar = this.requireActivity().actionBar
    actionBar?.setDisplayHomeAsUpEnabled(false)

Position buttons next to each other in the center of page

jsfiddle: http://jsfiddle.net/mgtoz4d3/

I added a container which contains both buttons. Try this:

CSS:

#button1{
    width: 300px;
    height: 40px;
}
#button2{
    width: 300px;
    height: 40px;
}
#container{
    text-align: center;
}

HTML:

<img src="kingstonunilogo.jpg" alt="uni logo" style="width:180px;height:160px">
<br><br>
<div id="container">
    <button type="button home-button" id="button1" >Home</button>
    <button type="button contact-button" id="button2">Contact Us</button>
</div>

How to install and run Typescript locally in npm?

You can now use ts-node, which makes your life as simple as

npm install -D ts-node
npm install -D typescript

ts-node script.ts

Why is Tkinter Entry's get function returning nothing?

You could also use a StringVar variable, even if it's not strictly necessary:

v = StringVar()

e = Entry(master, textvariable=v)
e.pack()

v.set("a default value")
s = v.get()

For more information, see this page on effbot.org.

Print all day-dates between two dates

import datetime

d1 = datetime.date(2008,8,15)
d2 = datetime.date(2008,9,15)
diff = d2 - d1
for i in range(diff.days + 1):
    print (d1 + datetime.timedelta(i)).isoformat()

Getting RSA private key from PEM BASE64 Encoded private key file

Parsing PKCS1 (only PKCS8 format works out of the box on Android) key turned out to be a tedious task on Android because of the lack of ASN1 suport, yet solvable if you include Spongy castle jar to read DER Integers.

String privKeyPEM = key.replace(
"-----BEGIN RSA PRIVATE KEY-----\n", "")
    .replace("-----END RSA PRIVATE KEY-----", "");

// Base64 decode the data

byte[] encodedPrivateKey = Base64.decode(privKeyPEM, Base64.DEFAULT);

try {
    ASN1Sequence primitive = (ASN1Sequence) ASN1Sequence
        .fromByteArray(encodedPrivateKey);
    Enumeration<?> e = primitive.getObjects();
    BigInteger v = ((DERInteger) e.nextElement()).getValue();

    int version = v.intValue();
    if (version != 0 && version != 1) {
        throw new IllegalArgumentException("wrong version for RSA private key");
    }
    /**
     * In fact only modulus and private exponent are in use.
     */
    BigInteger modulus = ((DERInteger) e.nextElement()).getValue();
    BigInteger publicExponent = ((DERInteger) e.nextElement()).getValue();
    BigInteger privateExponent = ((DERInteger) e.nextElement()).getValue();
    BigInteger prime1 = ((DERInteger) e.nextElement()).getValue();
    BigInteger prime2 = ((DERInteger) e.nextElement()).getValue();
    BigInteger exponent1 = ((DERInteger) e.nextElement()).getValue();
    BigInteger exponent2 = ((DERInteger) e.nextElement()).getValue();
    BigInteger coefficient = ((DERInteger) e.nextElement()).getValue();

    RSAPrivateKeySpec spec = new RSAPrivateKeySpec(modulus, privateExponent);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey pk = kf.generatePrivate(spec);
} catch (IOException e2) {
    throw new IllegalStateException();
} catch (NoSuchAlgorithmException e) {
    throw new IllegalStateException(e);
} catch (InvalidKeySpecException e) {
    throw new IllegalStateException(e);
}

Cocoa Touch: How To Change UIView's Border Color And Thickness?

I wanted to add this to @marczking's answer (Option 1) as a comment, but my lowly status on StackOverflow is preventing that.

I did a port of @marczking's answer to Objective C. Works like charm, thanks @marczking!

UIView+Border.h:

#import <UIKit/UIKit.h>

IB_DESIGNABLE
@interface UIView (Border)

-(void)setBorderColor:(UIColor *)color;
-(void)setBorderWidth:(CGFloat)width;
-(void)setCornerRadius:(CGFloat)radius;

@end

UIView+Border.m:

#import "UIView+Border.h"

@implementation UIView (Border)
// Note: cannot use synthesize in a Category

-(void)setBorderColor:(UIColor *)color
{
    self.layer.borderColor = color.CGColor;
}

-(void)setBorderWidth:(CGFloat)width
{
    self.layer.borderWidth = width;
}

-(void)setCornerRadius:(CGFloat)radius
{
    self.layer.cornerRadius = radius;
    self.layer.masksToBounds = radius > 0;
}

@end

Equals(=) vs. LIKE

This is a copy/paste of another answer of mine for question SQL 'like' vs '=' performance:

A personal example using mysql 5.5: I had an inner join between 2 tables, one of 3 million rows and one of 10 thousand rows.

When using a like on an index as below(no wildcards), it took about 30 seconds:

where login like '12345678'

using 'explain' I get:

enter image description here

When using an '=' on the same query, it took about 0.1 seconds:

where login ='12345678'

Using 'explain' I get:

enter image description here

As you can see, the like completely cancelled the index seek, so query took 300 times more time.

How to write an async method with out parameter?

Here's the code of @dcastro's answer modified for C# 7.0 with named tuples and tuple deconstruction, which streamlines the notation:

public async void Method1()
{
    // Version 1, named tuples:
    // just to show how it works
    /*
    var tuple = await GetDataTaskAsync();
    int op = tuple.paramOp;
    int result = tuple.paramResult;
    */

    // Version 2, tuple deconstruction:
    // much shorter, most elegant
    (int op, int result) = await GetDataTaskAsync();
}

public async Task<(int paramOp, int paramResult)> GetDataTaskAsync()
{
    //...
    return (1, 2);
}

For details about the new named tuples, tuple literals and tuple deconstructions see: https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/

what is an illegal reflective access

There is an Oracle article I found regarding Java 9 module system

By default, a type in a module is not accessible to other modules unless it’s a public type and you export its package. You expose only the packages you want to expose. With Java 9, this also applies to reflection.

As pointed out in https://stackoverflow.com/a/50251958/134894, the differences between the AccessibleObject#setAccessible for JDK8 and JDK9 are instructive. Specifically, JDK9 added

This method may be used by a caller in class C to enable access to a member of declaring class D if any of the following hold:

  • C and D are in the same module.
  • The member is public and D is public in a package that the module containing D exports to at least the module containing C.
  • The member is protected static, D is public in a package that the module containing D exports to at least the module containing C, and C is a subclass of D.
  • D is in a package that the module containing D opens to at least the module containing C. All packages in unnamed and open modules are open to all modules and so this method always succeeds when D is in an unnamed or open module.

which highlights the significance of modules and their exports (in Java 9)

AsyncTask Android example

Concept and code here

I have created a simple example for using AsyncTask of Android. It starts with onPreExecute(), doInBackground(), publishProgress() and finally onProgressUpdate().

In this, doInBackground() works as a background thread, while other works in the UI Thread. You can't access an UI element in doInBackground(). The sequence is the same as I have mentioned.

However, if you need to update any widget from doInBackground, you can publishProgress from doInBackground which will call onProgressUpdate to update your UI widget.

class TestAsync extends AsyncTask<Void, Integer, String> {
    String TAG = getClass().getSimpleName();

    protected void onPreExecute() {
        super.onPreExecute();
        Log.d(TAG + " PreExceute","On pre Exceute......");
    }

    protected String doInBackground(Void...arg0) {
        Log.d(TAG + " DoINBackGround", "On doInBackground...");

        for (int i=0; i<10; i++){
            Integer in = new Integer(i);
            publishProgress(i);
        }
        return "You are at PostExecute";
    }

    protected void onProgressUpdate(Integer...a) {
        super.onProgressUpdate(a);
        Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);
    }

    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.d(TAG + " onPostExecute", "" + result);
    }
}

Call it like this in your activity:

new TestAsync().execute();

Developer Reference Here

How to easily initialize a list of Tuples?

c# 7.0 lets you do this:

  var tupleList = new List<(int, string)>
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

If you don't need a List, but just an array, you can do:

  var tupleList = new(int, string)[]
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

And if you don't like "Item1" and "Item2", you can do:

  var tupleList = new List<(int Index, string Name)>
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

or for an array:

  var tupleList = new (int Index, string Name)[]
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

which lets you do: tupleList[0].Index and tupleList[0].Name

Framework 4.6.2 and below

You must install System.ValueTuple from the Nuget Package Manager.

Framework 4.7 and above

It is built into the framework. Do not install System.ValueTuple. In fact, remove it and delete it from the bin directory.

note: In real life, I wouldn't be able to choose between cow, chickens or airplane. I would be really torn.

Insert Data Into Tables Linked by Foreign Key

You can do it in one sql statement for existing customers, 3 statements for new ones. All you have to do is be an optimist and act as though the customer already exists:

insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);

If the customer does not exist, you'll get an sql exception which text will be something like:

null value in column "customer_id" violates not-null constraint

(providing you made customer_id non-nullable, which I'm sure you did). When that exception occurs, insert the customer into the customer table and redo the insert into the order table:

insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);

Unless your business is growing at a rate that will make "where to put all the money" your only real problem, most of your inserts will be for existing customers. So, most of the time, the exception won't occur and you'll be done in one statement.

Darken background image on hover

If you want to darken the image, use an overlay element with rgba and opacity properties which will darken your image...

Demo

<div><span></span></div>

div {
    background-image: url(http://im.tech2.in.com/gallery/2012/dec/stockimage_070930177527_640x360.jpg);
    height: 400px;
    width: 400px;
}

div span {
    display: block;
    height: 100%;
    width: 100%;
    opacity: 0;
    background: rgba(0,0,0,.5);
    -moz-transition: all 1s;
    -webkit-transition: all 1s;
    transition: all 1s;
}

div:hover span {
    opacity: 1;
}

Note: Am also using CSS3 transitions for smooth dark effect


If anyone one to save an extra element in the DOM than you can use :before or :after pseudo as well..

Demo 2

div {
    background-image: url(http://im.tech2.in.com/gallery/2012/dec/stockimage_070930177527_640x360.jpg);
    height: 400px;
    width: 400px;
}

div:after {
    content: "";
    display: block;
    height: 100%;
    width: 100%;
    opacity: 0;
    background: rgba(0,0,0,.5);
    -moz-transition: all 1s;
    -webkit-transition: all 1s;
    transition: all 1s;
}

div:hover:after {
    opacity: 1;
}

Using some content over the darkened overlay of the image

Here am using CSS Positioning techniques with z-index to overlay content over the darkened div element. Demo 3

div {
    background-image: url(http://im.tech2.in.com/gallery/2012/dec/stockimage_070930177527_640x360.jpg);
    height: 400px;
    width: 400px;
    position: relative;
}

div:after {
    content: "";
    display: block;
    height: 100%;
    width: 100%;
    opacity: 0;
    background: rgba(0,0,0,.5);
    -moz-transition: all 1s;
    -webkit-transition: all 1s;
    transition: all 1s;
    top: 0;
    left: 0;
    position: absolute;
}

div:hover:after {
    opacity: 1;
}

div p {
    color: #fff;
    z-index: 1;
    position: relative;
}

Explain the concept of a stack frame in a nutshell

Programmers may have questions about stack frames not in a broad term (that it is a singe entity in the stack that serves just one function call and keeps return address, arguments and local variables) but in a narrow sense – when the term stack frames is mentioned in context of compiler options.

Whether the author of the question has meant it or not, but the concept of a stack frame from the aspect of compiler options is a very important issue, not covered by the other replies here.

For example, Microsoft Visual Studio 2015 C/C++ compiler has the following option related to stack frames:

  • /Oy (Frame-Pointer Omission)

GCC have the following:

  • -fomit-frame-pointer (Don't keep the frame pointer in a register for functions that don't need one. This avoids the instructions to save, set up and restore frame pointers; it also makes an extra register available in many functions)

Intel C++ Compiler have the following:

  • -fomit-frame-pointer (Determines whether EBP is used as a general-purpose register in optimizations)

which has the following alias:

  • /Oy

Delphi has the following command-line option:

  • -$W+ (Generate Stack Frames)

In that specific sense, from the compiler’s perspective, a stack frame is just the entry and exit code for the routine, that pushes an anchor to the stack – that can also be used for debugging and for exception handling. Debugging tools may scan the stack data and use these anchors for backtracing, while locating call sites in the stack, i.e. to display names of the functions in the order they have been called hierarchically. For Intel architecture, it is push ebp; mov ebp, esp or enter for entry and mov esp, ebp; pop ebp or leave for exit.

That’s why it is very important to understand for a programmer what a stack frame is in when it comes to compiler options – because the compiler can control whether to generate this code or not.

In some cases, the stack frame (entry and exit code for the routine) can be omitted by the compiler, and the variables will directly be accessed via the stack pointer (SP/ESP/RSP) rather than the convenient base pointer (BP/ESP/RSP). Conditions for omission of the stack frame, for example:

  • the function is a leaf function (i.e. an end-entity that doesn’t call other functions);
  • there are no try/finally or try/except or similar constructs, i.e. no exceptions are used;
  • no routines are called with outgoing parameters on the stack;
  • the function has no parameters;
  • the function has no inline assembly code;
  • etc...

Omitting stack frames (entry and exit code for the routine) can make code smaller and faster, but it may also negatively affect the debuggers’ ability to backtrace the data in the stack and to display it to the programmer. These are the compiler options that determine under which conditions a function should have the entry and exit code, for example: (a) always, (b) never, (c) when needed (specifying the conditions).

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

On a rather unrelated note: more performance hacks!

  • [the first «conjecture» has been finally debunked by @ShreevatsaR; removed]

  • When traversing the sequence, we can only get 3 possible cases in the 2-neighborhood of the current element N (shown first):

    1. [even] [odd]
    2. [odd] [even]
    3. [even] [even]

    To leap past these 2 elements means to compute (N >> 1) + N + 1, ((N << 1) + N + 1) >> 1 and N >> 2, respectively.

    Let`s prove that for both cases (1) and (2) it is possible to use the first formula, (N >> 1) + N + 1.

    Case (1) is obvious. Case (2) implies (N & 1) == 1, so if we assume (without loss of generality) that N is 2-bit long and its bits are ba from most- to least-significant, then a = 1, and the following holds:

    (N << 1) + N + 1:     (N >> 1) + N + 1:
    
            b10                    b1
             b1                     b
           +  1                   + 1
           ----                   ---
           bBb0                   bBb
    

    where B = !b. Right-shifting the first result gives us exactly what we want.

    Q.E.D.: (N & 1) == 1 ? (N >> 1) + N + 1 == ((N << 1) + N + 1) >> 1.

    As proven, we can traverse the sequence 2 elements at a time, using a single ternary operation. Another 2× time reduction.

The resulting algorithm looks like this:

uint64_t sequence(uint64_t size, uint64_t *path) {
    uint64_t n, i, c, maxi = 0, maxc = 0;

    for (n = i = (size - 1) | 1; i > 2; n = i -= 2) {
        c = 2;
        while ((n = ((n & 3)? (n >> 1) + n + 1 : (n >> 2))) > 2)
            c += 2;
        if (n == 2)
            c++;
        if (c > maxc) {
            maxi = i;
            maxc = c;
        }
    }
    *path = maxc;
    return maxi;
}

int main() {
    uint64_t maxi, maxc;

    maxi = sequence(1000000, &maxc);
    printf("%llu, %llu\n", maxi, maxc);
    return 0;
}

Here we compare n > 2 because the process may stop at 2 instead of 1 if the total length of the sequence is odd.

[EDIT:]

Let`s translate this into assembly!

MOV RCX, 1000000;



DEC RCX;
AND RCX, -2;
XOR RAX, RAX;
MOV RBX, RAX;

@main:
  XOR RSI, RSI;
  LEA RDI, [RCX + 1];

  @loop:
    ADD RSI, 2;
    LEA RDX, [RDI + RDI*2 + 2];
    SHR RDX, 1;
    SHRD RDI, RDI, 2;    ror rdi,2   would do the same thing
    CMOVL RDI, RDX;      Note that SHRD leaves OF = undefined with count>1, and this doesn't work on all CPUs.
    CMOVS RDI, RDX;
    CMP RDI, 2;
  JA @loop;

  LEA RDX, [RSI + 1];
  CMOVE RSI, RDX;

  CMP RAX, RSI;
  CMOVB RAX, RSI;
  CMOVB RBX, RCX;

  SUB RCX, 2;
JA @main;



MOV RDI, RCX;
ADD RCX, 10;
PUSH RDI;
PUSH RCX;

@itoa:
  XOR RDX, RDX;
  DIV RCX;
  ADD RDX, '0';
  PUSH RDX;
  TEST RAX, RAX;
JNE @itoa;

  PUSH RCX;
  LEA RAX, [RBX + 1];
  TEST RBX, RBX;
  MOV RBX, RDI;
JNE @itoa;

POP RCX;
INC RDI;
MOV RDX, RDI;

@outp:
  MOV RSI, RSP;
  MOV RAX, RDI;
  SYSCALL;
  POP RAX;
  TEST RAX, RAX;
JNE @outp;

LEA RAX, [RDI + 59];
DEC RDI;
SYSCALL;

Use these commands to compile:

nasm -f elf64 file.asm
ld -o file file.o

See the C and an improved/bugfixed version of the asm by Peter Cordes on Godbolt. (editor's note: Sorry for putting my stuff in your answer, but my answer hit the 30k char limit from Godbolt links + text!)

How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2

I am researching the same thing and stumbled upon identityserver which implements OAuth and OpenID on top of ASP.NET. It integrates with ASP.NET identity and Membership Reboot with persistence support for Entity Framework.

So, to answer your question, check out their detailed document on how to setup an OAuth and OpenID server.

Twitter bootstrap collapse: change display of toggle button

I liked the CSS-only solution from PSL, but in my case I needed to include some HTML in the button, and the content CSS property is showing the raw HTML with tags in this case.

In case that could help someone else, I've forked his fiddle to cover my use case: http://jsfiddle.net/brunoalla/99j11h40/2/

HTML:

<div class="row-fluid summary">
    <div class="span11">
        <h2>MyHeading</h2>  
    </div>
    <div class="span1">
        <button class="btn btn-success collapsed" data-toggle="collapse" data-target="#intro">
            <span class="show-ctrl">
                <i class="fa fa-chevron-down"></i> Expand
            </span>
            <span class="hide-ctrl">
                <i class="fa fa-chevron-up"></i> Collapse
            </span>            
        </button>
    </div>
</div>
<div class="row-fluid summary">
    <div id="intro" class="collapse"> 
        Here comes the text...
    </div>
</div>

CSS:

button.btn .show-ctrl{
    display: none;
}
button.btn .hide-ctrl{
    display: block;
}
button.btn.collapsed .show-ctrl{
    display: block;
}
button.btn.collapsed .hide-ctrl{
    display: none;
}

Grant Select on a view not base table when base table is in a different database

I have had this problem. It appears that although permission to "View1" as part of schema "schema1" needs to be granted by the owner "dbo" if View1 uses dbo.table1.

Unless a schema gets used which is not part of dbo then this problem may not become apparent, and the regular solution of "Grant Select to user" would work.

How to represent empty char in Java Character class

If you want to replace a character in a String without leaving any empty space then you can achieve this by using StringBuilder. String is immutable object in java,you can not modify it.

String str = "Hello";
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(1); // to replace e character

How to place two forms on the same page?

Well you can have each form go to to a different page. (which is preferable)

Or have a different value for the a certain input and base posts on that:

switch($_POST['submit']) {
    case 'login': 
    //...
    break;
    case 'register':
    //...
    break;
}

Making a <button> that's a link in HTML

<a href="#"><button>Link Text</button></a>

You asked for a link that looks like a button, so use a link and a button :-) This will preserve default browser button styling. The button by itself does nothing, but clicking it activates its parent link.

Demo:

_x000D_
_x000D_
<a href="http://stackoverflow.com"><button>Link Text</button></a>
_x000D_
_x000D_
_x000D_

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

There's a huge difference. As has been mentioned, <%@ include is a static include, <jsp:include is a dynamic include. Think of it as a difference between a macro and a function call (if you are familiar with those terms). Another way of putting it, a static include is exactly the same thing as copy-pasting the exact content of the included file (the "code") at the location of the <%@ include statement (which is exactly what the JSP compiler will do.

A dynamic include will make a request (using the request dispatcher) that will execute the indicated page and then include the output from the page in the output of the calling page, in place of the <jsp:include statement.

The big difference here is that with a dynamic include, the included page will execute in it's own pageContext. And since it's a request, you can send parameters to the page the same way you can send parameters along with any other request. A static include, on the other hand, is just a piece of code that will execute inside the context of the calling page. If you statically include the same file more than once, the code in that file will exist in multiple locations on the calling page so something like

<%
int i = 0;
%>

would generate a compiler error (since the same variable can't be declared more than once).

Extract digits from string - StringUtils Java

   `String s="as234dfd423";
for(int i=0;i<s.length();i++)
 {
    char c=s.charAt(i);``
    char d=s.charAt(i);
     if ('a' <= c && c <= 'z')
         System.out.println("String:-"+c);
     else  if ('0' <= d && d <= '9')
           System.out.println("number:-"+d);
    }

output:-

number:-4
number:-3
number:-4
String:-d
String:-f
String:-d
number:-2
number:-3

How to call a method defined in an AngularJS directive?

You can specify a DOM attribute that can be used to allow the directive to define a function on the parent scope. The parent scope can then call this method like any other. Here's a plunker. And below is the relevant code.

clearfn is an attribute on the directive element into which the parent scope can pass a scope property which the directive can then set to a function that accomplish's the desired behavior.

<!DOCTYPE html>
<html ng-app="myapp">
  <head>
    <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <style>
      my-box{
        display:block;
        border:solid 1px #aaa;
        min-width:50px;
        min-height:50px;
        padding:.5em;
        margin:1em;
        outline:0px;
        box-shadow:inset 0px 0px .4em #aaa;
      }
    </style>
  </head>
  <body ng-controller="mycontroller">
    <h1>Call method on directive</h1>
    <button ng-click="clear()">Clear</button>
    <my-box clearfn="clear" contentEditable=true></my-box>
    <script>
      var app = angular.module('myapp', []);
      app.controller('mycontroller', function($scope){
      });
      app.directive('myBox', function(){
        return {
          restrict: 'E',
          scope: {
            clearFn: '=clearfn'
          },
          template: '',
          link: function(scope, element, attrs){
            element.html('Hello World!');
            scope.clearFn = function(){
              element.html('');
            };
          }
        }
      });
    </script>
  </body>
</html>