Programs & Examples On #Session fixation

Session Fixation is a security vulnerability which occurs after authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier. It gives an attacker the opportunity to steal authenticated sessions.

An Authentication object was not found in the SecurityContext - Spring 3.2.2

This could also happens if you put a @PreAuthorize or @PostAuthorize in a Bean in creation. I would recommend to move such annotations to methods of interest.

Is it better to use std::memcpy() or std::copy() in terms to performance?

My rule is simple. If you are using C++ prefer C++ libraries and not C :)

Use of #pragma in C

This is a preprocessor directive that can be used to turn on or off certain features.

It is of two types #pragma startup, #pragma exit and #pragma warn.

#pragma startup allows us to specify functions called upon program startup.

#pragma exit allows us to specify functions called upon program exit.

#pragma warn tells the computer to suppress any warning or not.

Many other #pragma styles can be used to control the compiler.

How to avoid Sql Query Timeout

While I would be tempted to blame my issues - I'm getting the same error with my query, which is much, much bigger and involves a lot of loops - on the network, I think this is not the case.

Unfortunately it's not that simple. Query runs for 3+ hours before getting that error and apparently it crashes at the same time if it's just a query in SSMS and a job on SQL Server (did not look into details of that yet, so not sure if it's the same error; definitely same spot, though).

So just in case someone comes here with similar problem, this thread: https://www.sqlservercentral.com/Forums/569962/The-semaphore-timeout-period-has-expired

suggest that it may equally well be a hardware issue or actual timeout.

My loops aren't even (they depend on sales level in given month) in terms of time required for each, so good month takes about 20 mins to calculate (query looks at 4 years).

That way it's entirely possible I need to optimise my query. I would even say it's likely, as some changes I did included new tables, which are heaps... So another round of indexing my data before tearing into VM config and hardware tests.

Being aware that this is old question: I'm on SQL Server 2012 SE, SSMS is 2018 Beta and VM the SQL Server runs on has exclusive use of 132GB of RAM (30% total), 8 cores, and 2TB of SSD SAN.

How to generate a number of most distinctive colors in R?

You can generate a set of colors like this:

myCol = c("pink1", "violet", "mediumpurple1", "slateblue1", "purple", "purple3",
          "turquoise2", "skyblue", "steelblue", "blue2", "navyblue",
          "orange", "tomato", "coral2", "palevioletred", "violetred", "red2",
          "springgreen2", "yellowgreen", "palegreen4",
          "wheat2", "tan", "tan2", "tan3", "brown",
          "grey70", "grey50", "grey30")

These colors are as distinct as possible. For those similar colors, they form a gradient so that you can easily tell the differences between them.

How to get day of the month?

LocalDate date = new Date(); date.lengthOfMonth()

or

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd");

DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMM");

String stringDate = formatter.format(date);

String month = monthFormatter.format(date);

Sorting a vector in descending order

According to my machine, sorting a long long vector of [1..3000000] using the first method takes around 4 seconds, while using the second takes about twice the time. That says something, obviously, but I don't understand why either. Just think this would be helpful.

Same thing reported here.

As said by Xeo, with -O3 they use about the same time to finish.

How to add action listener that listens to multiple buttons

You are declaring button1 in main method so you can not access it in actionPerform. You should make it global in class.

 JButton button1;
 public static void main(String[] args) {

    JFrame calcFrame = new JFrame();

    calcFrame.setSize(100, 100);
    calcFrame.setVisible(true);

    button1 = new JButton("1");
    button1.addActionListener(this);

    calcFrame.add(button1);
}

public void actionPerformed(ActionEvent e) {
    if(e.getSource() == button1)
}

Count the items from a IEnumerable<T> without iterating?

I would suggest calling ToList. Yes you are doing the enumeration early, but you still have access to your list of items.

How to select some rows with specific rownames from a dataframe?

Assuming that you have a data frame called students, you can select individual rows or columns using the bracket syntax, like this:

  • students[1,2] would select row 1 and column 2, the result here would be a single cell.
  • students[1,] would select all of row 1, students[,2] would select all of column 2.

If you'd like to select multiple rows or columns, use a list of values, like this:

  • students[c(1,3,4),] would select rows 1, 3 and 4,
  • students[c("stu1", "stu2"),] would select rows named stu1 and stu2.

Hope I could help.

How to redirect output to a file and stdout

tee is perfect for this, but this will also do the job

ls -lr / > output | cat output

Parse XLSX with Node and create json

**podria ser algo asi en react y electron**

 xslToJson = workbook => {
        //var data = [];
        var sheet_name_list = workbook.SheetNames[0];
        return XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list], {
            raw: false,
            dateNF: "DD-MMM-YYYY",
            header:1,
            defval: ""
        });
    };

    handleFile = (file /*:File*/) => {
        /* Boilerplate to set up FileReader */
        const reader = new FileReader();
        const rABS = !!reader.readAsBinaryString;

        reader.onload = e => {
            /* Parse data */
            const bstr = e.target.result;
            const wb = XLSX.read(bstr, { type: rABS ? "binary" : "array" });
            /* Get first worksheet */
            let arr = this.xslToJson(wb);

            console.log("arr ", arr)
            var dataNueva = []

            arr.forEach(data => {
                console.log("data renaes ", data)
            })
            // this.setState({ DataEESSsend: dataNueva })
            console.log("dataNueva ", dataNueva)

        };


        if (rABS) reader.readAsBinaryString(file);
        else reader.readAsArrayBuffer(file);
    };

    handleChange = e => {
        const files = e.target.files;
        if (files && files[0]) {
            this.handleFile(files[0]);
        }
    };

Spring @Value is not resolving to value from property file

Problem is due to problem in my applicationContext.xml vs spring-servlet.xml - it was scoping issue between the beans.

pedjaradenkovic kindly pointed me to an existing resource: Spring @Value annotation in @Controller class not evaluating to value inside properties file and Spring 3.0.5 doesn't evaluate @Value annotation from properties

JavaScript property access: dot notation vs. brackets?

Bracket notation can use variables, so it is useful in two instances where dot notation will not work:

1) When the property names are dynamically determined (when the exact names are not known until runtime).

2) When using a for..in loop to go through all the properties of an object.

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

Prevent typing non-numeric in input type number

You can accomplish this by preventing the keyPress event from occurring for non-numeric values

e.g (using jQuery)

$('.input-selector').on('keypress', function(e){
  return e.metaKey || // cmd/ctrl
    e.which <= 0 || // arrow keys
    e.which == 8 || // delete key
    /[0-9]/.test(String.fromCharCode(e.which)); // numbers
})

This accounts for all different types of input (e.g. input from the number pad has different codes than the keyboard) as well as backspace, arrow keys, control/cmd + r to reload etc

How do I rotate text in css?

Using writing-mode and transform.

.rotate {
     writing-mode: vertical-lr;
    -webkit-transform: rotate(-180deg);
    -moz-transform: rotate(-180deg);
}


<span class="rotate">Hello</span>

Excluding directory when creating a .tar.gz file

The correct command for exclude directory from compression is :

tar --exclude='./folder' --exclude='./upload/folder2' -zcvf backup.tar.gz backup/

Make sure to put --exclude before the source and destination items.

and you can check the contents of the tar.gz file without unzipping :

tar -tf backup.tar.gz

how to convert rgb color to int in java

Use getRGB(), it helps ( no complicated programs )

Returns an array of integer pixels in the default RGB color model (TYPE_INT_ARGB) and default sRGB color space, from a portion of the image data.

How do I automatically scroll to the bottom of a multiline text box?

This only worked for me...

txtSerialLogging->Text = "";

txtSerialLogging->AppendText(s);

I tried all the cases above, but the problem is in my case text s can decrease, increase and can also remain static for a long time. static means , static length(lines) but content is different.

So, I was facing one line jumping situation at the end when the length(lines) remains same for some times...

How do I handle the window close event in Tkinter?

i say a lot simpler way would be using the break command, like

import tkinter as tk
win=tk.Tk
def exit():
    break
btn= tk.Button(win, text="press to exit", command=exit)
win.mainloop()

OR use sys.exit()

import tkinter as tk
import sys
win=tk.Tk
def exit():
    sys.exit
btn= tk.Button(win, text="press to exit", command=exit)
win.mainloop()

How to remove element from an array in JavaScript?

You can also do this with reduce:

let arr = [1, 2, 3]

arr.reduce((xs, x, index) => {
        if (index == 0) {
            return xs
        } else {
            return xs.concat(x)
        }
    }, Array())

// Or if you like a oneliner
arr.reduce((xs, x, index) => index == 0 ? xs : xs.concat(x), Array())

Pretty-Printing JSON with PHP

I have used this:

echo "<pre>".json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)."</pre>";

Or use php headers as below:

header('Content-type: application/json; charset=UTF-8');
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

Android: How to turn screen on and off programmatically?

I had written this method to turn on the screen after screen lock. It works perfectly for me. Try it-

    private void unlockScreen() {
        Window window = this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    }

And call this method from onResume().

How do I read a large csv file with pandas?

Chunking shouldn't always be the first port of call for this problem.

  1. Is the file large due to repeated non-numeric data or unwanted columns?

    If so, you can sometimes see massive memory savings by reading in columns as categories and selecting required columns via pd.read_csv usecols parameter.

  2. Does your workflow require slicing, manipulating, exporting?

    If so, you can use dask.dataframe to slice, perform your calculations and export iteratively. Chunking is performed silently by dask, which also supports a subset of pandas API.

  3. If all else fails, read line by line via chunks.

    Chunk via pandas or via csv library as a last resort.

How to vertically align an image inside a div

Imagine you have

<div class="wrap">
    <img src="#">
</div>

And css:

.wrap {
    display: flex;
}
.wrap img {
    object-fit: contain;
}

Scale iFrame css width 100% like an image

None of these solutions worked for me inside a Weebly "add your own html" box. Not sure what they are doing with their code. But I found this solution at https://benmarshall.me/responsive-iframes/ and it works perfectly.

CSS

.iframe-container {
  overflow: hidden;
  padding-top: 56.25%;
  position: relative;
}

.iframe-container iframe {
   border: 0;
   height: 100%;
   left: 0;
   position: absolute;
   top: 0;
   width: 100%;
}

/* 4x3 Aspect Ratio */
.iframe-container-4x3 {
  padding-top: 75%;
}

HTML

<div class="iframe-container">
  <iframe src="https://player.vimeo.com/video/106466360" allowfullscreen></iframe>
</div>

Save current directory in variable using Bash?

for a relative answer, use .

test with:

$ myDir=.
$ ls $myDir
$ cd /
$ ls $myDir

The first ls will show you everything in the current directory, the second will show you everything in the root directory (/).

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

Get JSON Data from URL Using Android?

    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();

while ((sResponse = reader.readLine()) != null) {
    s = s.append(sResponse);
}
Gson gson = new Gson();

JSONObject jsonObject = new JSONObject(s.toString());
String link = jsonObject.getString("Result");

How to force a WPF binding to refresh?

I was fetching data from backend and updated the screen with just one line of code. It worked. Not sure, why we need to implement Interface. (windows 10, UWP)

    private void populateInCurrentScreen()
    {
        (this.FindName("Dets") as Grid).Visibility = Visibility.Visible;
        this.Bindings.Update();
    }

How to split a number into individual digits in c#?

Substring and Join methods are usable for this statement.

string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;

   for (int i = 0; i < no.Length; i++)
   {
     numberArray[i] = no.Substring(counter, 1); // 1 is split length
     counter++;
   }

Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5

Trying to make bootstrap modal wider

Always have handy the un-minified CSS for bootstrap so you can see what styles they have on their components, then create a CSS file AFTER it, if you don't use LESS and over-write their mixins or whatever

This is the default modal css for 768px and up:

@media (min-width: 768px) {
  .modal-dialog {
    width: 600px;
    margin: 30px auto;
  }
  ...
}

They have a class modal-lg for larger widths

@media (min-width: 992px) {
  .modal-lg {
    width: 900px;
  }
}

If you need something twice the 600px size, and something fluid, do something like this in your CSS after the Bootstrap css and assign that class to the modal-dialog.

@media (min-width: 768px) {
  .modal-xl {
    width: 90%;
   max-width:1200px;
  }
}

HTML

<div class="modal-dialog modal-xl">

Demo: http://jsbin.com/yefas/1

c# Image resizing to different size while preserving aspect ratio

I use the following method to calculate the desired image size:

using System.Drawing;
public static Size ResizeKeepAspect(this Size src, int maxWidth, int maxHeight, bool enlarge = false)
{
    maxWidth = enlarge ? maxWidth : Math.Min(maxWidth, src.Width);
    maxHeight = enlarge ? maxHeight : Math.Min(maxHeight, src.Height);

    decimal rnd = Math.Min(maxWidth / (decimal)src.Width, maxHeight / (decimal)src.Height);
    return new Size((int)Math.Round(src.Width * rnd), (int)Math.Round(src.Height * rnd));
}

This puts the problem of aspect ratio and dimensions in a separate method.

Altering a column to be nullable

Assuming SQL Server (based on your previous questions):

ALTER TABLE Merchant_Pending_Functions ALTER COLUMN NumberOfLocations INT NULL

Replace INT with your actual datatype.

How to compare datetime with only date in SQL Server

If you are on SQL Server 2008 or later you can use the date datatype:

SELECT *
FROM [User] U
WHERE CAST(U.DateCreated as DATE) = '2014-02-07'

It should be noted that if date column is indexed then this will still utilise the index and is SARGable. This is a special case for dates and datetimes.

enter image description here

You can see that SQL Server actually turns this into a > and < clause:

enter image description here

I've just tried this on a large table, with a secondary index on the date column as per @kobik's comments and the index is still used, this is not the case for the examples that use BETWEEN or >= and <:

SELECT *
FROM [User] U
WHERE CAST(U.DateCreated as DATE) = '2016-07-05'

showing index usage with secondary index

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

dt = dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.First()).CopyToDataTable();

Set background image according to screen resolution

Pure CSS approaches that work very well are discussed here. Two techniques are examined in particular and I personally prefer the second as it not CSS3 dependent, which suits my own needs better.

If most/all of your traffic has a CSS3 capable browser, the first method is quicker and cleaner to implement (copy/pasted by Mr. Zoidberg in another answer here for convenience, though I'd visit the source for further background on why it works).

An alternative method to CSS is to use the JavaScript library jQuery to detect resolution changes and adjust the image size accordingly. This article covers the jQuery technique and provides a live demo.

Supersized is a dedicated JavaScript library designed for static full screen images as well as full sized slideshows.

A good tip for full-screen images is to scale them with a correct ratio beforehand. I normally aim for a size of 1500x1000 when using supersized.js or 1680x1050 for other methods, setting the jpg quality for photographs to between 60-80% resulting in a file size in the region of 100kb or less if possible without compromising quality too much.

Android Studio is slow (how to speed up)?

It's not compiling that's hurting me here, it's the typing. I could disable all the smart features and be back to notepad++ like TomTsagk suggested in a comment. For today I need more cores and RAM.

Playing devil's advocate I'd argue that typing shouldn't require a 16Gb PC octacore PC. Liked Sajan Rana's advice but things are so slow here it felt mostly a placebo.

To be fair I am using 1.4RC1, which is just short of being in the stable branch. Turning the internet off helped a little. The new feature of simultaneous Design (Preview) and Text views working with XML layouts is very helpful.

No, it is ridiculous. Never leave the stable channel.

How do you find the sum of all the numbers in an array in Java?

/**
 * Sum of all elements from 1 to 1000
 */
final int sum = Stream.iterate(1, n -> n + 1).limit(1000).mapToInt(el -> el).sum();

how to check if string value is in the Enum list?

You can use the Enum.TryParse method:

Age age;
if (Enum.TryParse<Age>("New_Born", out age))
{
    // You now have the value in age 
}

Copy map values to vector in STL

#include <algorithm> // std::transform
#include <iterator>  // std::back_inserter
std::transform( 
    your_map.begin(), 
    your_map.end(),
    std::back_inserter(your_values_vector),
    [](auto &kv){ return kv.second;} 
);

Sorry that I didn't add any explanation - I thought that code is so simple that is doesn't require any explanation. So:

transform( beginInputRange, endInputRange, outputIterator, unaryOperation)

this function calls unaryOperation on every item from inputIterator range (beginInputRange-endInputRange). The value of operation is stored into outputIterator.

If we want to operate through whole map - we use map.begin() and map.end() as our input range. We want to store our map values into vector - so we have to use back_inserter on our vector: back_inserter(your_values_vector). The back_inserter is special outputIterator that pushes new elements at the end of given (as paremeter) collection. The last parameter is unaryOperation - it takes only one parameter - inputIterator's value. So we can use lambda: [](auto &kv) { [...] }, where &kv is just a reference to map item's pair. So if we want to return only values of map's items we can simply return kv.second:

[](auto &kv) { return kv.second; }

I think this explains any doubts.

Javascript call() & apply() vs bind()?

Use bind for future calls to the function. Both apply and call invoke the function.

bind() also allows for additional arguments to be perpended to the args array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

How to pip or easy_install tkinter on Windows

I'm posting as the top answer requotes the documentation which I didn't find useful.

tkinter comes packaged with python install on windows IFF you select it during the install window.

The solution is to repair the installation (via uninstall GUI is fine), and select to install tk this time. You may need to point at or redownload the binary in this process. Downloading directly from activestate did not work for me.

This is a common problem people have on windows as it's easy to not want to install TCL/TK if you don't know what it is, but Matplotlib etc require it.

What is the difference between Cygwin and MinGW?

Read these answered questions to understand the difference between Cygwin and MinGW.


Question #1: I want to create an application that I write source code once, compile it once and run it in any platforms (e.g. Windows, Linux and Mac OS X…).

Answer #1: Write your source code in JAVA. Compile the source code once and run it anywhere.


Question #2: I want to create an application that I write source code once but there is no problem that I compile the source code for any platforms separately (e.g. Windows, Linux and Mac OS X …).

Answer #2: Write your source code in C or C++. Use standard header files only. Use a suitable compiler for any platform (e.g. Visual Studio for Windows, GCC for Linux and XCode for Mac). Note that you should not use any advanced programming features to compile your source code in all platforms successfully. If you use none C or C++ standard classes or functions, your source code does not compile in other platforms.


Question #3: In answer of question #2, it is difficult using different compiler for each platform, is there any cross platform compiler?

Answer #3: Yes, Use GCC compiler. It is a cross platform compiler. To compile your source code in Windows use MinGW that provides GCC compiler for Windows and compiles your source code to native Windows program. Do not use any advanced programming features (like Windows API) to compile your source code in all platforms successfully. If you use Windows API functions, your source code does not compile in other platforms.


Question #4: C or C++ standard header files do not provide any advanced programming features like multi-threading. What can I do?

Answer #4: You should use POSIX (Portable Operating System Interface [for UNIX]) standard. It provides many advanced programming features and tools. Many operating systems fully or partly POSIX compatible (like Mac OS X, Solaris, BSD/OS and ...). Some operating systems while not officially certified as POSIX compatible, conform in large part (like Linux, FreeBSD, OpenSolaris and ...). Cygwin provides a largely POSIX-compliant development and run-time environment for Microsoft Windows.


Thus:

To use advantage of GCC cross platform compiler in Windows, use MinGW.

To use advantage of POSIX standard advanced programming features and tools in Windows, use Cygwin.

Cast received object to a List<object> or IEnumerable<object>

This Code worked for me

List<Object> collection = new List<Object>((IEnumerable<Object>)myObject);

Best way to check for IE less than 9 in JavaScript without library

bah to conditional comments! Conditional code all the way!!! (silly IE)

<script type="text/javascript">
/*@cc_on
   var IE_LT_9 = (@_jscript_version < 9);
@*/
</script>

Seriously though, just throwing this out there in case it suits you better... they're the same thing, this can just be in a .js file instead of inline HTML

Note: it is entirely coincidental that the jscript_version check is "9" here. Setting it to 8, 7, etc will NOT check "is IE8", you'd need to lookup the jscript versions for those browsers.

How to format string to money

Once you have your string in a double/decimal to get it into the correct formatting for a specific locale use

double amount = 1234.95;

amount.ToString("C") // whatever the executing computer thinks is the right fomat

amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ie"))    //  €1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("es-es"))    //  1.234,95 € 
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-GB"))    //  £1,234.95 

amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-au"))    //  $1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-us"))    //  $1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ca"))    //  $1,234.95

NotificationCenter issue on Swift 3

For all struggling around with the #selector in Swift 3 or Swift 4, here a full code example:

// WE NEED A CLASS THAT SHOULD RECEIVE NOTIFICATIONS
    class MyReceivingClass {

    // ---------------------------------------------
    // INIT -> GOOD PLACE FOR REGISTERING
    // ---------------------------------------------
    init() {
        // WE REGISTER FOR SYSTEM NOTIFICATION (APP WILL RESIGN ACTIVE)

        // Register without parameter
        NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handleNotification), name: .UIApplicationWillResignActive, object: nil)

        // Register WITH parameter
        NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handle(withNotification:)), name: .UIApplicationWillResignActive, object: nil)
    }

    // ---------------------------------------------
    // DE-INIT -> LAST OPTION FOR RE-REGISTERING
    // ---------------------------------------------
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    // either "MyReceivingClass" must be a subclass of NSObject OR selector-methods MUST BE signed with '@objc'

    // ---------------------------------------------
    // HANDLE NOTIFICATION WITHOUT PARAMETER
    // ---------------------------------------------
    @objc func handleNotification() {
        print("RECEIVED ANY NOTIFICATION")
    }

    // ---------------------------------------------
    // HANDLE NOTIFICATION WITH PARAMETER
    // ---------------------------------------------
    @objc func handle(withNotification notification : NSNotification) {
        print("RECEIVED SPECIFIC NOTIFICATION: \(notification)")
    }
}

In this example we try to get POSTs from AppDelegate (so in AppDelegate implement this):

// ---------------------------------------------
// WHEN APP IS GOING TO BE INACTIVE
// ---------------------------------------------
func applicationWillResignActive(_ application: UIApplication) {

    print("POSTING")

    // Define identifiyer
    let notificationName = Notification.Name.UIApplicationWillResignActive

    // Post notification
    NotificationCenter.default.post(name: notificationName, object: nil)
}

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

In case the error appears when upgrading from Laravel 6 to Laravel 7, the command composer require laravel/ui "^2.0" solves the problem (see https://laravel.com/docs/7.x/upgrade#authentication -scaffolding)

Make docker use IPv4 for port binding

By default, docker uses AF_INET6 sockets which can be used for both IPv4 and IPv6 connections. This causes netstat to report an IPv6 address for the listening address.

From RedHat https://access.redhat.com/solutions/3114021

Return values from the row above to the current row

To solve this problem in Excel, usually I would just type in the literal row number of the cell above, e.g., if I'm typing in Cell A7, I would use the formula =A6. Then if I copied that formula to other cells, they would also use the row of the previous cell.

Another option is to use Indirect(), which resolves the literal statement inside to be a formula. You could use something like:

=INDIRECT("A" & ROW() - 1)

The above formula will resolve to the value of the cell in column A and the row that is one less than that of the cell which contains the formula.

cout is not a member of std

Also remember that it must be:

#include "stdafx.h"
#include <iostream>

and not the other way around

#include <iostream>
#include "stdafx.h"

Whether a variable is undefined

http://constc.blogspot.com/2008/07/undeclared-undefined-null-in-javascript.html

Depends on how specific you want the test to be. You could maybe get away with

if(page_name){ string += "&page_name=" + page_name; }

Hide horizontal scrollbar on an iframe?

I'd suggest doing this with a combination of

  1. CSS overflow-y: hidden;
  2. scrolling="no" (for HTML4)
  3. and seamless="seamless" (for HTML5)*

* The seamless attribute has been removed from the standard, and no browsers support it.


_x000D_
_x000D_
.foo {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  overflow-y: hidden;_x000D_
}
_x000D_
<iframe src="https://bing.com" _x000D_
        class="foo" _x000D_
        scrolling="no" >_x000D_
</iframe>
_x000D_
_x000D_
_x000D_

CSS selector last row from main table

Your tables should have as immediate children just tbody and thead elements, with the rows within*. So, amend the HTML to be:

<table border="1" width="100%" id="test">
  <tbody>
    <tr>
     <td>
      <table border="1" width="100%">
        <tbody>
          <tr>
            <td>table 2</td>
          </tr>
        </tbody>
      </table>
     </td>
    </tr> 
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
  </tbody>
</table>

Then amend your selector slightly to this:

#test > tbody > tr:last-child { background:#ff0000; }

See it in action here. That makes use of the child selector, which:

...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.

So, you are targeting only direct children of tbody elements that are themselves direct children of your #test table.

Alternative solution

The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:

#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }

* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:

...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.

Does Internet Explorer 8 support HTML 5?

You can use this IE HTML5 shim script to gain a basic level of support for the new semantic elements in HTML5 such as <article>.

What is the difference between os.path.basename() and os.path.dirname()?

To summarize what was mentioned by Breno above

Say you have a variable with a path to a file

path = '/home/User/Desktop/myfile.py'

os.path.basename(path) returns the string 'myfile.py'

and

os.path.dirname(path) returns the string '/home/User/Desktop' (without a trailing slash '/')

These functions are used when you have to get the filename/directory name given a full path name.

In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py' you just have myfile.py), os.path.dirname(path) returns an empty string.

Pandas: Looking up the list of sheets in an excel file

Building on @dhwanil_shah 's answer, you do not need to extract the whole file. With zf.open it is possible to read from a zipped file directly.

import xml.etree.ElementTree as ET
import zipfile

def xlsxSheets(f):
    zf = zipfile.ZipFile(f)

    f = zf.open(r'xl/workbook.xml')

    l = f.readline()
    l = f.readline()
    root = ET.fromstring(l)
    sheets=[]
    for c in root.findall('{http://schemas.openxmlformats.org/spreadsheetml/2006/main}sheets/*'):
        sheets.append(c.attrib['name'])
    return sheets

The two consecutive readlines are ugly, but the content is only in the second line of the text. No need to parse the whole file.

This solution seems to be much faster than the read_excel version, and most likely also faster than the full extract version.

Repeat rows of a data.frame

A clean dplyr solution, taken from here

library(dplyr)
df <- tibble(x = 1:2, y = c("a", "b"))
df %>% slice(rep(1:n(), each = 2))

How do I use Linq to obtain a unique list of properties from a list of objects?

Using straight Linq, with the Distinct() extension:

var idList = (from x in yourList select x.ID).Distinct();

SQL MAX of multiple columns?

Well, you can use the CASE statement:

SELECT
    CASE
        WHEN Date1 >= Date2 AND Date1 >= Date3 THEN Date1
        WHEN Date2 >= Date1 AND Date2 >= Date3 THEN Date2
        WHEN Date3 >= Date1 AND Date3 >= Date2 THEN Date3
        ELSE                                        Date1
    END AS MostRecentDate

[For Microsoft SQL Server 2008 and above, you may consider Sven's simpler answer below.]

Programmatically navigate using React router

React-Router v2

For the most recent release (v2.0.0-rc5), the recommended navigation method is by directly pushing onto the history singleton. You can see that in action in the Navigating outside of Components doc.

Relevant excerpt:

import { browserHistory } from 'react-router';
browserHistory.push('/some/path');

If using the newer react-router API, you need to make use of the history from this.props when inside of components so:

this.props.history.push('/some/path');

It also offers pushState but that is deprecated per logged warnings.

If using react-router-redux, it offers a push function you can dispatch like so:

import { push } from 'react-router-redux';
this.props.dispatch(push('/some/path'));

However this may be only used to change the URL, not to actually navigate to the page.

What is mutex and semaphore in Java ? What is the main difference?

Mutex is basically mutual exclusion. Only one thread can acquire the resource at once. When one thread acquires the resource, no other thread is allowed to acquire the resource until the thread owning the resource releases. All threads waiting for acquiring resource would be blocked.

Semaphore is used to control the number of threads executing. There will be fixed set of resources. The resource count will gets decremented every time when a thread owns the same. When the semaphore count reaches 0 then no other threads are allowed to acquire the resource. The threads get blocked till other threads owning resource releases.

In short, the main difference is how many threads are allowed to acquire the resource at once ?

  • Mutex --its ONE.
  • Semaphore -- its DEFINED_COUNT, ( as many as semaphore count)

Why do people say that Ruby is slow?

Ruby performs well for developer productivity. Ruby by nature forces test driven development because of the lack of types. Ruby performs well when used as a high level wrapper for C libraries. Ruby also performs well during long running processes when it is JIT-compiled to machine code via JVM or Rbx VM. Ruby does not perform well when it is required to crunch numbers in a short time with pure ruby code.

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

For anyone looking for a UI option using IIS Manager.

  1. Open the Website in IIS Manager
  2. Go To Request Filtering and open the Request Filtering Window.
  3. Go to Verbs Tab and Add HTTP Verbs to "Allow Verb..." or "Deny Verb...". This allow to add the HTTP Verbs in the "Deny Verb.." Collection.

Request Filtering Window in IIS Manager Request Filtering Window in IIS Manager

Add Verb... or Deny Verb... enter image description here

How to make a Bootstrap accordion collapse when clicking the header div?

All you need to do is to to use...

  • data-toggle="collapse"
  • data-target="#ElementToExpandOnClick"

...on the element you want to click to trigger the collapse/expand effect.

The element with data-toggle="collapse" will be the element to trigger the effect. The data-target attribute indicates the element that will expand when the effect is triggered.

Optionally you can set the data-parent if you want to create an accordion effect instead of independent collapsible, e.g.:

  • data-parent="#accordion"

I would also add the following CSS to the elements with data-toggle="collapse" if they aren't <a> tags, e.g.:

.panel-heading {
    cursor: pointer;
}

Here's a jsfiddle with the modified html from the Bootstrap 3 documentation.

How to change JDK version for an Eclipse project

Click on the Add Library button. It brings your screen to point to the Java location.

Select "Directory", button right besides JRE home and point to the installed folder location.

Even though you want to just 1.5 compiler project, you can achieve it by changing compiler settings in Eclipse instead of removing 1.6 JRE and add 1.5 JRE.

GOTO -->JAVA--Compiler---> and change compiler level to `1.5` instead of `1.6`

As davidfmatheson suggested,

Just be careful, especially if you're setting this up for a team of people to work on. If anyone uses anything that is new or changed in 1.6, it will compile, but not run in an environment with JRE 1.5.

How to simplify a null-safe compareTo() implementation?

For the specific case where you know the data will not have nulls (always a good idea for strings) and the data is really large, you are still doing three comparisons before actually comparing the values, if you know for sure this is your case, you can optimize a tad bit. YMMV as readable code trumps minor optimization:

        if(o1.name != null && o2.name != null){
            return o1.name.compareToIgnoreCase(o2.name);
        }
        // at least one is null
        return (o1.name == o2.name) ? 0 : (o1.name != null ? 1 : -1);

How can I use iptables on centos 7?

If you do so, and you're using fail2ban, you will need to enable the proper filters/actions:

Put the following lines in /etc/fail2ban/jail.d/sshd.local

[ssh-iptables]
enabled  = true
filter   = sshd
action   = iptables[name=SSH, port=ssh, protocol=tcp]
logpath  = /var/log/secure
maxretry = 5
bantime = 86400

Enable and start fail2ban:

systemctl enable fail2ban
systemctl start fail2ban

Reference: http://blog.iopsl.com/fail2ban-on-centos-7-to-protect-ssh-part-ii/

Git merge with force overwrite

I had a similar issue, where I needed to effectively replace any file that had changes / conflicts with a different branch.

The solution I found was to use git merge -s ours branch.

Note that the option is -s and not -X. -s denotes the use of ours as a top level merge strategy, -X would be applying the ours option to the recursive merge strategy, which is not what I (or we) want in this case.

Steps, where oldbranch is the branch you want to overwrite with newbranch.

  • git checkout newbranch checks out the branch you want to keep
  • git merge -s ours oldbranch merges in the old branch, but keeps all of our files.
  • git checkout oldbranch checks out the branch that you want to overwrite
  • get merge newbranch merges in the new branch, overwriting the old branch

MySQL case sensitive query

To improve James' excellent answer:

It's better to put BINARY in front of the constant instead:

SELECT * FROM `table` WHERE `column` = BINARY 'value'

Putting BINARY in front of column will prevent the use of any index on that column.

How to draw a checkmark / tick using CSS?

Do some transforms with the letter L

_x000D_
_x000D_
.checkmark {_x000D_
  font-family: arial;_x000D_
  -ms-transform: scaleX(-1) rotate(-35deg); /* IE 9 */_x000D_
  -webkit-transform: scaleX(-1) rotate(-35deg); /* Chrome, Safari, Opera */_x000D_
  transform: scaleX(-1) rotate(-35deg);_x000D_
}
_x000D_
<div class="checkmark">L</div>
_x000D_
_x000D_
_x000D_

Convert HH:MM:SS string to seconds only in javascript

new Date(moment('23:04:33', "HH:mm")).getTime()

Output: 1499755980000 (in millisecond) ( 1499755980000/1000) (in second)

Note : this output calculate diff from 1970-01-01 12:0:0 to now and we need to implement the moment.js

Android ADB stop application command like "force-stop" for non rooted device

If you have a rooted device you can use kill command

Connect to your device with adb:

adb shell

Once the session is established, you have to escalade privileges:

su

Then

ps

will list running processes. Note down the PID of the process you want to terminate. Then get rid of it

kill PID

How do I count unique values inside a list

How about:

import pandas as pd
#List with all words
words=[]

#Code for adding words
words.append('test')


#When Input equals blank:
pd.Series(words).nunique()

It returns how many unique values are in a list

ASP.NET Temporary files cleanup

Just an update on more current OS's (Vista, Win7, etc.) - the temp file path has changed may be different based on several variables. The items below are not definitive, however, they are a few I have encountered:

"temp" environment variable setting - then it would be:

%temp%\Temporary ASP.NET Files

Permissions and what application/process (VS, IIS, IIS Express) is running the .Net compiler. Accessing the C:\WINDOWS\Microsoft.NET\Framework folders requires elevated permissions and if you are not developing under an account with sufficient permissions then this folder might be used:

c:\Users\[youruserid]\AppData\Local\Temp\Temporary ASP.NET Files

There are also cases where the temp folder can be set via config for a machine or site specific using this:

<compilation tempDirectory="d:\MyTempPlace" />

I even have a funky setup at work where we don't run Admin by default, plus the IT guys have login scripts that set %temp% and I get temp files in 3 different locations depending on what is compiling things! And I'm still not certain about how these paths get picked....sigh.

Still, dthrasher is correct, you can just delete these and VS and IIS will just recompile them as needed.

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

For two Entity Classes Customer and Order , hibernate will create two tables.

Possible Cases:

  1. mappedBy is not used in Customer.java and Order.java Class then->

    At customer side a new table will be created[name = CUSTOMER_ORDER] which will keep mapping of CUSTOMER_ID and ORDER_ID. These are primary keys of Customer and Order Tables. At Order side an additional column is required to save the corresponding Customer_ID record mapping.

  2. mappedBy is used in Customer.java [As given in problem statement] Now additional table[CUSTOMER_ORDER] is not created. Only one column in Order Table

  3. mappedby is used in Order.java Now additional table will be created by hibernate.[name = CUSTOMER_ORDER] Order Table will not have additional column [Customer_ID ] for mapping.

Any Side can be made Owner of the relationship. But its better to choose xxxToOne side.

Coding effect - > Only Owning side of entity can change relationship status. In below example BoyFriend class is owner of the relationship. even if Girlfriend wants to break-up , she can't.

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "BoyFriend21")
public class BoyFriend21 {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Boy_ID")
    @SequenceGenerator(name = "Boy_ID", sequenceName = "Boy_ID_SEQUENCER", initialValue = 10,allocationSize = 1)
    private Integer id;

    @Column(name = "BOY_NAME")
    private String name;

    @OneToOne(cascade = { CascadeType.ALL })
    private GirlFriend21 girlFriend;

    public BoyFriend21(String name) {
        this.name = name;
    }

    public BoyFriend21() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BoyFriend21(String name, GirlFriend21 girlFriend) {
        this.name = name;
        this.girlFriend = girlFriend;
    }

    public GirlFriend21 getGirlFriend() {
        return girlFriend;
    }

    public void setGirlFriend(GirlFriend21 girlFriend) {
        this.girlFriend = girlFriend;
    }
}

import org.hibernate.annotations.*;
import javax.persistence.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.List;

@Entity 
@Table(name = "GirlFriend21")
public class GirlFriend21 {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Girl_ID")
    @SequenceGenerator(name = "Girl_ID", sequenceName = "Girl_ID_SEQUENCER", initialValue = 10,allocationSize = 1)
    private Integer id;

    @Column(name = "GIRL_NAME")
    private String name;

    @OneToOne(cascade = {CascadeType.ALL},mappedBy = "girlFriend")
    private BoyFriend21 boyFriends = new BoyFriend21();

    public GirlFriend21() {
    }

    public GirlFriend21(String name) {
        this.name = name;
    }


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public GirlFriend21(String name, BoyFriend21 boyFriends) {
        this.name = name;
        this.boyFriends = boyFriends;
    }

    public BoyFriend21 getBoyFriends() {
        return boyFriends;
    }

    public void setBoyFriends(BoyFriend21 boyFriends) {
        this.boyFriends = boyFriends;
    }
}


import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.util.Arrays;

public class Main578_DS {

    public static void main(String[] args) {
        final Configuration configuration = new Configuration();
         try {
             configuration.configure("hibernate.cfg.xml");
         } catch (HibernateException e) {
             throw new RuntimeException(e);
         }
        final SessionFactory sessionFactory = configuration.buildSessionFactory();
        final Session session = sessionFactory.openSession();
        session.beginTransaction();

        final BoyFriend21 clinton = new BoyFriend21("Bill Clinton");
        final GirlFriend21 monica = new GirlFriend21("monica lewinsky");

        clinton.setGirlFriend(monica);
        session.save(clinton);

        session.getTransaction().commit();
        session.close();
    }
}

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.util.List;

public class Main578_Modify {

    public static void main(String[] args) {
        final Configuration configuration = new Configuration();
        try {
            configuration.configure("hibernate.cfg.xml");
        } catch (HibernateException e) {
            throw new RuntimeException(e);
        }
        final SessionFactory sessionFactory = configuration.buildSessionFactory();
        final Session session1 = sessionFactory.openSession();
        session1.beginTransaction();

        GirlFriend21 monica = (GirlFriend21)session1.load(GirlFriend21.class,10);  // Monica lewinsky record has id  10.
        BoyFriend21 boyfriend = monica.getBoyFriends();
        System.out.println(boyfriend.getName()); // It will print  Clinton Name
        monica.setBoyFriends(null); // It will not impact relationship

        session1.getTransaction().commit();
        session1.close();

        final Session session2 = sessionFactory.openSession();
        session2.beginTransaction();

        BoyFriend21 clinton = (BoyFriend21)session2.load(BoyFriend21.class,10);  // Bill clinton record

        GirlFriend21 girlfriend = clinton.getGirlFriend();
        System.out.println(girlfriend.getName()); // It will print Monica name.
        //But if Clinton[Who owns the relationship as per "mappedby" rule can break this]
        clinton.setGirlFriend(null);
        // Now if Monica tries to check BoyFriend Details, she will find Clinton is no more her boyFriend
        session2.getTransaction().commit();
        session2.close();

        final Session session3 = sessionFactory.openSession();
        session1.beginTransaction();

        monica = (GirlFriend21)session3.load(GirlFriend21.class,10);  // Monica lewinsky record has id  10.
        boyfriend = monica.getBoyFriends();

        System.out.println(boyfriend.getName()); // Does not print Clinton Name

        session3.getTransaction().commit();
        session3.close();
    }
}

SQL Server ON DELETE Trigger

Better to use:

DELETE tbl FROM tbl INNER JOIN deleted ON tbl.key=deleted.key

What is the best way to test for an empty string in Go?

As of now, the Go compiler generates identical code in both cases, so it is a matter of taste. GCCGo does generate different code, but barely anyone uses it so I wouldn't worry about that.

https://godbolt.org/z/fib1x1

How to get only filenames within a directory using c#?

You can simply use linq

Directory.EnumerateFiles(LoanFolder).Select(file => Path.GetFileName(file));

Note: EnumeratesFiles is more efficient compared to Directory.GetFiles as you can start enumerating the collection of names before the whole collection is returned.

JPanel Padding in Java

I will suppose your JPanel contains JTextField, for the sake of the demo.

Those components provides JTextComponent#setMargin() method which seems to be what you're looking for.

If you're looking for an empty border of any size around your text, well, use EmptyBorder

How to add an extra source directory for maven to compile and include in the build jar?

NOTE: This solution will just move the java source files to the target/classes directory and will not compile the sources.

Update the pom.xml as -

<project>   
 ....
    <build>
      <resources>
        <resource>
          <directory>src/main/config</directory>
        </resource>
      </resources>
     ...
    </build>
...
</project>

What are the ways to sum matrix elements in MATLAB?

You are trying to sum up all the elements of 2-D Array

In Matlab use

Array_Sum = sum(sum(Array_Name));

Text file with 0D 0D 0A line breaks

This typically stems from a bug in revision control system, or similar. This was a product from CVS, if a file was checked in from Windows to Unix server, and then checked out again...

In other words, it is just broken...

MVC 4 - Return error message from Controller - Show in View

Thanks for all the replies.

I was able to solve this by doing the following:

CONTROLLER:

[HttpPost]       
public ActionResult form_edit(FormModels model)
{
  model.error_msg = model.update_content(model);
  return RedirectToAction("Form_edit", "Form", model);
}

public ActionResult form_edit(FormModels model, string searchString,string id)
{
  string test = model.selectedvalue;
  var bal = new FormModels();
  bal.Countries = bal.get_contentdetails(searchString);
  bal.selectedvalue = id;
  bal.dd_text = "content_name";
  bal.dd_value = "content_id";

  test = model.error_msg;
  ViewBag.head = "Heading";

  if (model.error_msg != null)
  {
    ModelState.AddModelError("error_msg", test);
  }

  model.error_msg = "";
  return View(bal);
}   

VIEW:

@using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
  <table>
    <tr>
      <td>
        @ViewBag.error
        @Html.ValidationMessage("error_msg")
      </td>
    </tr>
    <tr>
      <th>
        @Html.DisplayNameFor(model => model.content_name)
        @Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
      </th>
    </tr>
  </table>
}

How can bcrypt have built-in salts?

This is from PasswordEncoder interface documentation from Spring Security,

 * @param rawPassword the raw password to encode and match
 * @param encodedPassword the encoded password from storage to compare with
 * @return true if the raw password, after encoding, matches the encoded password from
 * storage
 */
boolean matches(CharSequence rawPassword, String encodedPassword);

Which means, one will need to match rawPassword that user will enter again upon next login and matches it with Bcrypt encoded password that's stores in database during previous login/registration.

Prevent WebView from displaying "web page not available"

Finally, I solved this. (It works till now..)

My solution is like this...

  1. Prepare the layout to show when an error occurred instead of Web Page (a dirty 'page not found message') The layout has one button, "RELOAD" with some guide messages.

  2. If an error occurred, Remember using boolean and show the layout we prepare.

  3. If user click "RELOAD" button, set mbErrorOccured to false. And Set mbReloadPressed to true.
  4. if mbErrorOccured is false and mbReloadPressed is true, it means webview loaded page successfully. 'Cause if error occurred again, mbErrorOccured will be set true on onReceivedError(...)

Here is my full source. Check this out.

public class MyWebViewActivity extends ActionBarActivity implements OnClickListener {

    private final String TAG = MyWebViewActivity.class.getSimpleName();
    private WebView mWebView = null;
    private final String URL = "http://www.google.com";
    private LinearLayout mlLayoutRequestError = null;
    private Handler mhErrorLayoutHide = null;

    private boolean mbErrorOccured = false;
    private boolean mbReloadPressed = false;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);

        ((Button) findViewById(R.id.btnRetry)).setOnClickListener(this);
        mlLayoutRequestError = (LinearLayout) findViewById(R.id.lLayoutRequestError);
        mhErrorLayoutHide = getErrorLayoutHideHandler();

        mWebView = (WebView) findViewById(R.id.webviewMain);
        mWebView.setWebViewClient(new MyWebViewClient());
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        mWebView.setWebChromeClient(getChromeClient());
        mWebView.loadUrl(URL);
    }

    @Override
    public boolean onSupportNavigateUp() {
        return super.onSupportNavigateUp();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.btnRetry) {
            if (!mbErrorOccured) {
                return;
            }

            mbReloadPressed = true;
            mWebView.reload();
            mbErrorOccured = false;
        }
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
            return;
        }
        else {
            finish();
        }

        super.onBackPressed();
    }

    class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (mbErrorOccured == false && mbReloadPressed) {
                hideErrorLayout();
                mbReloadPressed = false;
            }

            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            mbErrorOccured = true;
            showErrorLayout();
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    }

    private WebChromeClient getChromeClient() {
        final ProgressDialog progressDialog = new ProgressDialog(MyWebViewActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);

        return new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }
        };
    }

    private void showErrorLayout() {
        mlLayoutRequestError.setVisibility(View.VISIBLE);
    }

    private void hideErrorLayout() {
        mhErrorLayoutHide.sendEmptyMessageDelayed(10000, 200);
    }

    private Handler getErrorLayoutHideHandler() {
        return new Handler() {
            @Override
            public void handleMessage(Message msg) {
                mlLayoutRequestError.setVisibility(View.GONE);
                super.handleMessage(msg);
            }
        };
    }
}

Addition:Here is layout....

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rLayoutWithWebView"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<WebView
    android:id="@+id/webviewMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<LinearLayout
    android:id="@+id/lLayoutRequestError"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:background="@color/white"
    android:gravity="center"
    android:orientation="vertical"
    android:visibility="gone" >

    <Button
        android:id="@+id/btnRetry"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:minWidth="120dp"
        android:text="RELOAD"
        android:textSize="20dp"
        android:textStyle="bold" />
</LinearLayout>

Is it safe to expose Firebase apiKey to the public?

It is oky to include them, and special care is required only for Firebase ML or when using Firebase Authentication

API keys for Firebase are different from typical API keys: Unlike how API keys are typically used, API keys for Firebase services are not used to control access to backend resources; that can only be done with Firebase Security Rules. Usually, you need to fastidiously guard API keys (for example, by using a vault service or setting the keys as environment variables); however, API keys for Firebase services are ok to include in code or checked-in config files.

Although API keys for Firebase services are safe to include in code, there are a few specific cases when you should enforce limits for your API key; for example, if you're using Firebase ML or using Firebase Authentication with the email/password sign-in method. Learn more about these cases later on this page.

For more informations, check the offical docs

What version of Python is on my Mac?

To check third version, we can use,

python3 --version

Arguments to main in C

Siamore, I keep seeing everyone using the command line to compile programs. I use x11 terminal from ide via code::blocks, a gnu gcc compiler on my linux box. I have never compiled a program from command line. So Siamore, if I want the programs name to be cp, do I initialize argv[0]="cp"; Cp being a string literal. And anything going to stdout goes on the command line??? The example you gave me Siamore I understood! Even though the string you entered was a few words long, it was still only one arg. Because it was encased in double quotations. So arg[0], the prog name, is actually your string literal with a new line character?? So I understand why you use if(argc!=3) print error. Because the prog name = argv[0] and there are 2 more args after that, and anymore an error has occured. What other reason would I use that? I really think that my lack of understanding about how to compile from the command line or terminal is my reason for lack understanding in this area!! Siamore, you have helped me understand cla's much better! Still don't fully understand but I am not oblivious to the concept. I'm gonna learn to compile from the terminal then re-read what you wrote. I bet, then I will fully understand! With a little more help from you lol

<> Code that I have not written myself, but from my book.

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;

    printf("The following arguments were passed to main(): ");
    for(i=1; i<argc; i++) printf("%s ", argv[i]);
    printf("\n");

    return 0;
} 

This is the output:

anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hey man
The follow arguments were passed to main(): hey man
anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hi how are you doing?
The follow arguments were passed to main(): hi how are you doing?

So argv is a table of string literals, and argc is the number of them. Now argv[0] is the name of the program. So if I type ./CLA to run the program ./CLA is argv[0]. The above program sets the command line to take an infinite amount of arguments. I can set them to only take 3 or 4 if I wanted. Like one or your examples showed, Siamore... if(argc!=3) printf("Some error goes here"); Thank you Siamore, couldn't have done it without you! thanks to the rest of the post for their time and effort also!

PS in case there is a problem like this in the future...you never know lol the problem was because I was using the IDE AKA Code::Blocks. If I were to run that program above it would print the path/directory of the program. Example: ~/Documents/C/CLA.c it has to be ran from the terminal and compiled using the command line. gcc -o CLA main.c and you must be in the directory of the file.

Not Able To Debug App In Android Studio

I was able to fix it by going to Run -> Edit Configurations, selecting my project, selecting the Debugger tab, then changing 'Debug type' from 'Auto' to 'Dual':enter image description here

How to use select/option/NgFor on an array of objects in Angular2

I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:

<select [(ngModel)]="simpleValue"> // value is a string or number
    <option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>

If you want to match on the actual object, I'd do it like this:

<select [(ngModel)]="objValue"> // value is an object
    <option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>

Sum the digits of a number

def sumOfDigits():

    n=int(input("enter digit:")) 
    sum=0
    while n!=0 :

        m=n%10
        n=n/10
        sum=int(sum+m)

    print(sum)

sumOfDigits()

Safe navigation operator (?.) or (!.) and null property paths

A new library called ts-optchain provides this functionality, and unlike lodash' solution, it also keeps your types safe, here is a sample of how it is used (taken from the readme):

import { oc } from 'ts-optchain';

interface I {
  a?: string;
  b?: {
    d?: string;
  };
  c?: Array<{
    u?: {
      v?: number;
    };
  }>;
  e?: {
    f?: string;
    g?: () => string;
  };
}

const x: I = {
  a: 'hello',
  b: {
    d: 'world',
  },
  c: [{ u: { v: -100 } }, { u: { v: 200 } }, {}, { u: { v: -300 } }],
};

// Here are a few examples of deep object traversal using (a) optional chaining vs
// (b) logic expressions. Each of the following pairs are equivalent in
// result. Note how the benefits of optional chaining accrue with
// the depth and complexity of the traversal.

oc(x).a(); // 'hello'
x.a;

oc(x).b.d(); // 'world'
x.b && x.b.d;

oc(x).c[0].u.v(); // -100
x.c && x.c[0] && x.c[0].u && x.c[0].u.v;

oc(x).c[100].u.v(); // undefined
x.c && x.c[100] && x.c[100].u && x.c[100].u.v;

oc(x).c[100].u.v(1234); // 1234
(x.c && x.c[100] && x.c[100].u && x.c[100].u.v) || 1234;

oc(x).e.f(); // undefined
x.e && x.e.f;

oc(x).e.f('optional default value'); // 'optional default value'
(x.e && x.e.f) || 'optional default value';

// NOTE: working with function value types can be risky. Additional run-time
// checks to verify that object types are functions before invocation are advised!
oc(x).e.g(() => 'Yo Yo')(); // 'Yo Yo'
((x.e && x.e.g) || (() => 'Yo Yo'))();

How to sum the values of one column of a dataframe in spark/scala

Using spark sql query..just incase if it helps anyone!

import org.apache.spark.sql.SparkSession 
import org.apache.spark.SparkConf 
import org.apache.spark.sql.functions._ 
import org.apache.spark.SparkContext 
import java.util.stream.Collectors

val conf = new SparkConf().setMaster("local[2]").setAppName("test")
val spark = SparkSession.builder.config(conf).getOrCreate()
val df = spark.sparkContext.parallelize(Seq(1, 2, 3, 4, 5, 6, 7)).toDF()

df.createOrReplaceTempView("steps")
val sum = spark.sql("select  sum(steps) as stepsSum from steps").map(row => row.getAs("stepsSum").asInstanceOf[Long]).collect()(0)
println("steps sum = " + sum) //prints 28

HTML: how to make 2 tables with different CSS

You need to assign different classes to each table.

Create a class in CSS with the dot '.' operator and write your properties inside each class. For example,

.table1 {
//some properties
}

.table2 {
//Some other properties
}

and use them in your html code.

Chaining multiple filter() in Django, is this a bug?

These two style of filtering are equivalent in most cases, but when query on objects base on ForeignKey or ManyToManyField, they are slightly different.

Examples from the documentation.

model
Blog to Entry is a one-to-many relation.

from django.db import models

class Blog(models.Model):
    ...

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    pub_date = models.DateField()
    ...

objects
Assuming there are some blog and entry objects here.
enter image description here

queries

Blog.objects.filter(entry__headline_contains='Lennon', 
    entry__pub_date__year=2008)
Blog.objects.filter(entry__headline_contains='Lennon').filter(
    entry__pub_date__year=2008)  
    

For the 1st query (single filter one), it match only blog1.

For the 2nd query (chained filters one), it filters out blog1 and blog2.
The first filter restricts the queryset to blog1, blog2 and blog5; the second filter restricts the set of blogs further to blog1 and blog2.

And you should realize that

We are filtering the Blog items with each filter statement, not the Entry items.

So, it's not the same, because Blog and Entry are multi-valued relationships.

Reference: https://docs.djangoproject.com/en/1.8/topics/db/queries/#spanning-multi-valued-relationships
If there is something wrong, please correct me.

Edit: Changed v1.6 to v1.8 since the 1.6 links are no longer available.

Sending data from HTML form to a Python script in Flask

The form tag needs some attributes set:

  1. action: The URL that the form data is sent to on submit. Generate it with url_for. It can be omitted if the same URL handles showing the form and processing the data.
  2. method="post": Submits the data as form data with the POST method. If not given, or explicitly set to get, the data is submitted in the query string (request.args) with the GET method instead.
  3. enctype="multipart/form-data": When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.

The input tag needs a name parameter.

Add a view to handle the submitted data, which is in request.form under the same key as the input's name. Any file inputs will be in request.files.

@app.route('/handle_data', methods=['POST'])
def handle_data():
    projectpath = request.form['projectFilepath']
    # your code
    # return a response

Set the form's action to that view's URL using url_for:

<form action="{{ url_for('handle_data') }}" method="post">
    <input type="text" name="projectFilepath">
    <input type="submit">
</form>

IEnumerable vs List - What to Use? How do they work?

IEnumerable describes behavior, while List is an implementation of that behavior. When you use IEnumerable, you give the compiler a chance to defer work until later, possibly optimizing along the way. If you use ToList() you force the compiler to reify the results right away.

Whenever I'm "stacking" LINQ expressions, I use IEnumerable, because by only specifying the behavior I give LINQ a chance to defer evaluation and possibly optimize the program. Remember how LINQ doesn't generate the SQL to query the database until you enumerate it? Consider this:

public IEnumerable<Animals> AllSpotted()
{
    return from a in Zoo.Animals
           where a.coat.HasSpots == true
           select a;
}

public IEnumerable<Animals> Feline(IEnumerable<Animals> sample)
{
    return from a in sample
           where a.race.Family == "Felidae"
           select a;
}

public IEnumerable<Animals> Canine(IEnumerable<Animals> sample)
{
    return from a in sample
           where a.race.Family == "Canidae"
           select a;
}

Now you have a method that selects an initial sample ("AllSpotted"), plus some filters. So now you can do this:

var Leopards = Feline(AllSpotted());
var Hyenas = Canine(AllSpotted());

So is it faster to use List over IEnumerable? Only if you want to prevent a query from being executed more than once. But is it better overall? Well in the above, Leopards and Hyenas get converted into single SQL queries each, and the database only returns the rows that are relevant. But if we had returned a List from AllSpotted(), then it may run slower because the database could return far more data than is actually needed, and we waste cycles doing the filtering in the client.

In a program, it may be better to defer converting your query to a list until the very end, so if I'm going to enumerate through Leopards and Hyenas more than once, I'd do this:

List<Animals> Leopards = Feline(AllSpotted()).ToList();
List<Animals> Hyenas = Canine(AllSpotted()).ToList();

Android getText from EditText field

You can simply get the text in editText by applying below code:

EditText editText=(EditText)findViewById(R.id.vnosZadeve);
String text=editText.getText().toString();

then you can toast string text!

Happy coding!

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

Jan 2020 Update

@Flimm has explained all the differences very well. Generally, we want to know the difference between all tools because we want to decide what's best for us. So, the next question would be: which one to use? I suggest you choose one of the two official ways to manage virtual environments:

Performing Breadth First Search recursively

Here is short Scala solution:

  def bfs(nodes: List[Node]): List[Node] = {
    if (nodes.nonEmpty) {
      nodes ++ bfs(nodes.flatMap(_.children))
    } else {
      List.empty
    }
  }

Idea of using return value as accumulator is well suited. Can be implemented in other languages in similar way, just make sure that your recursive function process list of nodes.

Test code listing (using @marco test tree):

import org.scalatest.FlatSpec

import scala.collection.mutable

class Node(val value: Int) {

  private val _children: mutable.ArrayBuffer[Node] = mutable.ArrayBuffer.empty

  def add(child: Node): Unit = _children += child

  def children = _children.toList

  override def toString: String = s"$value"
}

class BfsTestScala extends FlatSpec {

  //            1
  //          / | \
  //        2   3   4
  //      / |       | \
  //    5   6       7  8
  //  / |           | \
  // 9  10         11  12
  def tree(): Node = {
    val root = new Node(1)
    root.add(new Node(2))
    root.add(new Node(3))
    root.add(new Node(4))
    root.children(0).add(new Node(5))
    root.children(0).add(new Node(6))
    root.children(2).add(new Node(7))
    root.children(2).add(new Node(8))
    root.children(0).children(0).add(new Node(9))
    root.children(0).children(0).add(new Node(10))
    root.children(2).children(0).add(new Node(11))
    root.children(2).children(0).add(new Node(12))
    root
  }

  def bfs(nodes: List[Node]): List[Node] = {
    if (nodes.nonEmpty) {
      nodes ++ bfs(nodes.flatMap(_.children))
    } else {
      List.empty
    }
  }

  "BFS" should "work" in {
    println(bfs(List(tree())))
  }
}

Output:

List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)

How can I run code on a background thread on Android?

IF you need to:

  1. execute code on a background Thread

  2. execute code that DOES NOT touch/update the UI

  3. execute (short) code which will take at most a few seconds to complete

THEN use the following clean and efficient pattern which uses AsyncTask:

AsyncTask.execute(new Runnable() {
   @Override
   public void run() {
      //TODO your background code
   }
});

How to round a numpy array?

Numpy provides two identical methods to do this. Either use

np.round(data, 2)

or

np.around(data, 2)

as they are equivalent.

See the documentation for more information.


Examples:

>>> import numpy as np
>>> a = np.array([0.015, 0.235, 0.112])
>>> np.round(a, 2)
array([0.02, 0.24, 0.11])
>>> np.around(a, 2)
array([0.02, 0.24, 0.11])
>>> np.round(a, 1)
array([0. , 0.2, 0.1])

How can I push a specific commit to a remote, and not previous commits?

I believe you would have to "git revert" back to that commit and then push it. Or you could cherry-pick a commit into a new branch, and push that to the branch on the remote repository. Something like:

git branch onecommit
git checkout onecommit
git cherry-pick 7300a6130d9447e18a931e898b64eefedea19544 # From the other branch
git push origin {branch}

SQL distinct for 2 fields in a database

How about simply:

select distinct c1, c2 from t

or

select c1, c2, count(*)
from t
group by c1, c2

setting min date in jquery datepicker

$(function () {
    $('#datepicker').datepicker({
        dateFormat: 'yy-mm-dd',
        showButtonPanel: true,
        changeMonth: true,
        changeYear: true,
yearRange: '1999:2012',
        showOn: "button",
        buttonImage: "images/calendar.gif",
        buttonImageOnly: true,
        minDate: new Date(1999, 10 - 1, 25),
        maxDate: '+30Y',
        inline: true
    });
});

Just added year range option. It should solve the problem

How to prevent favicon.ico requests?

The easiest way to block these temporarily for testing purposes is to open up the inspect page in chrome by right-clicking anywhere on the page and clicking inspect or by pressing Ctrl+Shift+j and then going to the networking tab and then reloading the page which will send all the requests your page is supposed to make including that annoying favicon.ico. You can now simply right click the favicon.ico request and click "Block request URL".

screenshot of blocking a specific request URL for Chrome browser

All of the above answers are for devs who control the app source code. If you are a sysadmin, who's figuring our load-balancer or proxying configuration and is annoyed by this favicon.ico shenanigans, this simple trick does a better job. This answer is for Chrome, but I think there should be a similar alternative which you would figure out for Firefox/Opera/Tor/any other browser :)

Redirect within component Angular 2

callLog(){
    this.http.get('http://localhost:3000/getstudent/'+this.login.email+'/'+this.login.password)
    .subscribe(data => {
        this.getstud=data as string[];
        if(this.getstud.length!==0) {
            console.log(data)
            this.route.navigate(['home']);// used for routing after importing Router    
        }
    });
}

How to export library to Jar in Android Studio?

Here's yet another, slightly different answer with a few enhancements.

This code takes the .jar right out of the .aar. Personally, that gives me a bit more confidence that the bits being shipped via .jar are the same as the ones shipped via .aar. This also means that if you're using ProGuard, the output jar will be obfuscated as desired.

I also added a super "makeJar" task, that makes jars for all build variants.

task(makeJar) << {
    // Empty. We'll add dependencies for this task below
}

// Generate jar creation tasks for all build variants
android.libraryVariants.all { variant ->
    String taskName = "makeJar${variant.name.capitalize()}"

    // Create a jar by extracting it from the assembled .aar
    // This ensures that products distributed via .aar and .jar exactly the same bits
    task (taskName, type: Copy) {
        String archiveName = "${project.name}-${variant.name}"
        String outputDir = "${buildDir.getPath()}/outputs"

        dependsOn "assemble${variant.name.capitalize()}"
        from(zipTree("${outputDir}/aar/${archiveName}.aar"))
        into("${outputDir}/jar/")
        include('classes.jar')
        rename ('classes.jar', "${archiveName}-${variant.mergedFlavor.versionName}.jar")
    }

    makeJar.dependsOn tasks[taskName]
}

For the curious reader, I struggled to determine the correct variables and parameters that the com.android.library plugin uses to name .aar files. I finally found them in the Android Open Source Project here.

Git: Find the most recent common ancestor of two branches

You are looking for git merge-base. Usage:

$ git merge-base branch2 branch3
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

Writing a Python list of lists to a csv file

I got an error message when following the examples with a newline parameter in the csv.writer function. The following code worked for me.

 with open(strFileName, "w") as f:
    writer = csv.writer(f, delimiter=',',  quoting=csv.QUOTE_MINIMAL)
    writer.writerows(result)

Fill background color left to right CSS

A single css code on hover can do the trick: box-shadow: inset 100px 0 0 0 #e0e0e0;

A complete demo can be found in my fiddle:

https://jsfiddle.net/shuvamallick/3o0h5oka/

Allow 2 decimal places in <input type="number">

Use this code

<input type="number" step="0.01" name="amount" placeholder="0.00">

By default Step value for HTML5 Input elements is step="1".

How to allow CORS in react.js?

You just have to add cors to your backend server.js file in order to do cross-origin API Calls.

const cors = require('cors');
app.use(cors())

Updating state on props change in React Form

componentWillReceiveProps is being deprecated because using it "often leads to bugs and inconsistencies".

If something changes from the outside, consider resetting the child component entirely with key.

Providing a key prop to the child component makes sure that whenever the value of key changes from the outside, this component is re-rendered. E.g.,

<EmailInput
  defaultEmail={this.props.user.email}
  key={this.props.user.id}
/>

On its performance:

While this may sound slow, the performance difference is usually insignificant. Using a key can even be faster if the components have heavy logic that runs on updates since diffing gets bypassed for that subtree.

Javascript - get array of dates between 2 dates

I was recently working with moment.js, following did the trick..

function getDateRange(startDate, endDate, dateFormat) {
        var dates = [],
            end = moment(endDate),
            diff = endDate.diff(startDate, 'days');

        if(!startDate.isValid() || !endDate.isValid() || diff <= 0) {
            return;
        }

        for(var i = 0; i < diff; i++) {
            dates.push(end.subtract(1,'d').format(dateFormat));
        }

        return dates;
    };
    console.log(getDateRange(startDate, endDate, dateFormat));

Result would be:

["09/03/2015", "10/03/2015", "11/03/2015", "12/03/2015", "13/03/2015", "14/03/2015", "15/03/2015", "16/03/2015", "17/03/2015", "18/03/2015"]

What is the best way to dump entire objects to a log in C#?

You could use reflection and loop through all the object properties, then get their values and save them to the log. The formatting is really trivial (you could use \t to indent an objects properties and its values):

MyObject
    Property1 = value
    Property2 = value2
    OtherObject
       OtherProperty = value ...

Add Variables to Tuple

You can start with a blank tuple with something like t = (). You can add with +, but you have to add another tuple. If you want to add a single element, make it a singleton: t = t + (element,). You can add a tuple of multiple elements with or without that trailing comma.

>>> t = ()
>>> t = t + (1,)
>>> t
(1,)
>>> t = t + (2,)
>>> t
(1, 2)
>>> t = t + (3, 4, 5)
>>> t
(1, 2, 3, 4, 5)
>>> t = t + (6, 7, 8,)
>>> t
(1, 2, 3, 4, 5, 6, 7, 8)

Why can't I inherit static classes?

Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.

A class can be declared static, which indicates that it contains only static members. It is not possible to use the new keyword to create instances of a static class. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace that contains the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

Following are the main features of a static class:

  1. They only contain static members.

  2. They cannot be instantiated.

  3. They are sealed.

  4. They cannot contain Instance Constructors (C# Programming Guide).

Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can have a static constructor. For more information, see Static Constructors (C# Programming Guide).

TCPDF Save file to folder?

For who is having difficulties storing the file, the path has to be all the way through root. For example, mine was:

$pdf->Output('/home/username/public_html/app/admin/pdfs/filename.pdf', 'F');

How to create new folder?

You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:

newpath = r'C:\Program Files\arbitrary' 
if not os.path.exists(newpath):
    os.makedirs(newpath)

If you're trying to make an installer: Windows Installer does a lot of work for you.

Dynamically access object property using variable

ES5 // Check Deeply Nested Variables

This simple piece of code can check for deeply nested variable / value existence without having to check each variable along the way...

var getValue = function( s, context ){
    return Function.call( context || null, 'return ' + s )();
}

Ex. - a deeply nested array of objects:

a = [ 
    {
      b : [
          {
             a : 1,
             b : [
                 {
                    c : 1,
                    d : 2   // we want to check for this
                 }
             ]
           }
      ]
    } 
]

Instead of :

if(a && a[0] && a[0].b && a[0].b[0] && a[0].b[0].b && a[0].b[0].b[0] && a[0].b[0].b[0].d && a[0].b[0].b[0].d == 2 )  // true

We can now :

if( getValue('a[0].b[0].b[0].d') == 2 ) // true

Cheers!

Unable to connect PostgreSQL to remote database using pgAdmin

I didn't have to change my prostgresql.conf file but, i did have to do the following based on my psql via command line was connecting and pgAdmin not connecting on RDS with AWS.

I did have my RDS set to Publicly Accessible. I made sure my ACL and security groups were wide open and still problem so, I did the following: sudo find . -name *.conf then sudo nano ./data/pg_hba.conf then added to top of directives in pg_hba.conf file host all all 0.0.0.0/0 md5 and pgAdmin automatically logged me in.

This also worked in pg_hba.conf file host all all md5 without any IP address and this also worked with my IP address host all all <myip>/32 md5

As a side note, my RDS was in my default VPC. I had an identical RDS instance in my non-default VPC with identical security group, ACL and security group settings to my default VPC and I could not get it to work. Not sure why but, that's for another day.

Difference between Python's Generators and Iterators

What is the difference between iterators and generators? Some examples for when you would use each case would be helpful.

In summary: Iterators are objects that have an __iter__ and a __next__ (next in Python 2) method. Generators provide an easy, built-in way to create instances of Iterators.

A function with yield in it is still a function, that, when called, returns an instance of a generator object:

def a_function():
    "when called, returns generator object"
    yield

A generator expression also returns a generator:

a_generator = (i for i in range(0))

For a more in-depth exposition and examples, keep reading.

A Generator is an Iterator

Specifically, generator is a subtype of iterator.

>>> import collections, types
>>> issubclass(types.GeneratorType, collections.Iterator)
True

We can create a generator several ways. A very common and simple way to do so is with a function.

Specifically, a function with yield in it is a function, that, when called, returns a generator:

>>> def a_function():
        "just a function definition with yield in it"
        yield
>>> type(a_function)
<class 'function'>
>>> a_generator = a_function()  # when called
>>> type(a_generator)           # returns a generator
<class 'generator'>

And a generator, again, is an Iterator:

>>> isinstance(a_generator, collections.Iterator)
True

An Iterator is an Iterable

An Iterator is an Iterable,

>>> issubclass(collections.Iterator, collections.Iterable)
True

which requires an __iter__ method that returns an Iterator:

>>> collections.Iterable()
Traceback (most recent call last):
  File "<pyshell#79>", line 1, in <module>
    collections.Iterable()
TypeError: Can't instantiate abstract class Iterable with abstract methods __iter__

Some examples of iterables are the built-in tuples, lists, dictionaries, sets, frozen sets, strings, byte strings, byte arrays, ranges and memoryviews:

>>> all(isinstance(element, collections.Iterable) for element in (
        (), [], {}, set(), frozenset(), '', b'', bytearray(), range(0), memoryview(b'')))
True

Iterators require a next or __next__ method

In Python 2:

>>> collections.Iterator()
Traceback (most recent call last):
  File "<pyshell#80>", line 1, in <module>
    collections.Iterator()
TypeError: Can't instantiate abstract class Iterator with abstract methods next

And in Python 3:

>>> collections.Iterator()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Iterator with abstract methods __next__

We can get the iterators from the built-in objects (or custom objects) with the iter function:

>>> all(isinstance(iter(element), collections.Iterator) for element in (
        (), [], {}, set(), frozenset(), '', b'', bytearray(), range(0), memoryview(b'')))
True

The __iter__ method is called when you attempt to use an object with a for-loop. Then the __next__ method is called on the iterator object to get each item out for the loop. The iterator raises StopIteration when you have exhausted it, and it cannot be reused at that point.

From the documentation

From the Generator Types section of the Iterator Types section of the Built-in Types documentation:

Python’s generators provide a convenient way to implement the iterator protocol. If a container object’s __iter__() method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the __iter__() and next() [__next__() in Python 3] methods. More information about generators can be found in the documentation for the yield expression.

(Emphasis added.)

So from this we learn that Generators are a (convenient) type of Iterator.

Example Iterator Objects

You might create object that implements the Iterator protocol by creating or extending your own object.

class Yes(collections.Iterator):

    def __init__(self, stop):
        self.x = 0
        self.stop = stop

    def __iter__(self):
        return self

    def next(self):
        if self.x < self.stop:
            self.x += 1
            return 'yes'
        else:
            # Iterators must raise when done, else considered broken
            raise StopIteration

    __next__ = next # Python 3 compatibility

But it's easier to simply use a Generator to do this:

def yes(stop):
    for _ in range(stop):
        yield 'yes'

Or perhaps simpler, a Generator Expression (works similarly to list comprehensions):

yes_expr = ('yes' for _ in range(stop))

They can all be used in the same way:

>>> stop = 4             
>>> for i, y1, y2, y3 in zip(range(stop), Yes(stop), yes(stop), 
                             ('yes' for _ in range(stop))):
...     print('{0}: {1} == {2} == {3}'.format(i, y1, y2, y3))
...     
0: yes == yes == yes
1: yes == yes == yes
2: yes == yes == yes
3: yes == yes == yes

Conclusion

You can use the Iterator protocol directly when you need to extend a Python object as an object that can be iterated over.

However, in the vast majority of cases, you are best suited to use yield to define a function that returns a Generator Iterator or consider Generator Expressions.

Finally, note that generators provide even more functionality as coroutines. I explain Generators, along with the yield statement, in depth on my answer to "What does the “yield” keyword do?".

Binding Listbox to List<object> in WinForms

I haven 't seen it here so i post it because for me is the best way in winforms:

    List<object> objList = new List<object>();

    listBox.DataSource = objList ;

    listBox.Refresh();
    listBox.Update();            

Ruby on Rails: Clear a cached page

rake tmp:cache:clear might be what you're looking for.

Sorting by date & time in descending order?

If you mean you want to sort by date first then by names

SELECT id, name, form_id, DATE(updated_at) as date
  FROM wp_frm_items
  WHERE user_id = 11 && form_id=9
  ORDER BY updated_at DESC,name ASC

This will sort the records by date first, then by names

What are bitwise shift (bit-shift) operators and how do they work?

I am writing tips and tricks only. It may be useful in tests and exams.

  1. n = n*2: n = n<<1
  2. n = n/2: n = n>>1
  3. Checking if n is power of 2 (1,2,4,8,...): check !(n & (n-1))
  4. Getting xth bit of n: n |= (1 << x)
  5. Checking if x is even or odd: x&1 == 0 (even)
  6. Toggle the nth bit of x: x ^ (1<<n)

How to list all functions in a Python module?

Except dir(module) or help(module) mentioned in previous answers, you can also try:
- Open ipython
- import module_name
- type module_name, press tab. It'll open a small window with listing all functions in the python module.
It looks very neat.

Here is snippet listing all functions of hashlib module

(C:\Program Files\Anaconda2) C:\Users\lenovo>ipython
Python 2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jun 29 2016, 11:07:13) [MSC v.1500 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import hashlib

In [2]: hashlib.
             hashlib.algorithms            hashlib.new                   hashlib.sha256
             hashlib.algorithms_available  hashlib.pbkdf2_hmac           hashlib.sha384
             hashlib.algorithms_guaranteed hashlib.sha1                  hashlib.sha512
             hashlib.md5                   hashlib.sha224

Declare a dictionary inside a static class

Make the Dictionary a static, and never add to it outside of your static object's ctor. That seems to be a simpler solution than fiddling with the static/const rules in C#.

How do I pipe or redirect the output of curl -v?

This simple example shows how to capture curl output, and use it in a bash script

test.sh

function main
{
  \curl -vs 'http://google.com'  2>&1
  # note: add -o /tmp/ignore.png if you want to ignore binary output, by saving it to a file. 
}

# capture output of curl to a variable
OUT=$(main)

# search output for something using grep.
echo
echo "$OUT" | grep 302 
echo
echo "$OUT" | grep title 

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

Just add <mvc:default-servlet-handler /> to your DispatcherServlet configuration and you are done!

How to check for valid email address?

There is no point. Even if you can verify that the email address is syntactically valid, you'll still need to check that it was not mistyped, and that it actually goes to the person you think it does. The only way to do that is to send them an email and have them click a link to verify.

Therefore, a most basic check (e.g. that they didn't accidentally entered their street address) is usually enough. Something like: it has exactly one @ sign, and at least one . in the part after the @:

[^@]+@[^@]+\.[^@]+

You'd probably also want to disallow whitespace -- there are probably valid email addresses with whitespace in them, but I've never seen one, so the odds of this being a user error are on your side.

If you want the full check, have a look at this question.


Update: Here's how you could use any such regex:

import re

if not re.match(r"... regex here ...", email):
  # whatever

Python =3.4 has re.fullmatch which is preferable to re.match.

Note the r in front of the string; this way, you won't need to escape things twice.

If you have a large number of regexes to check, it might be faster to compile the regex first:

import re

EMAIL_REGEX = re.compile(r"... regex here ...")

if not EMAIL_REGEX.match(email):
  # whatever

Another option is to use the validate_email package, which actually contacts the SMTP server to verify that the address exists. This still doesn't guarantee that it belongs to the right person, though.

Is it better in C++ to pass by value or pass by constant reference?

This is what i normally work by when designing the interface of a non-template function:

  1. Pass by value if the function does not want to modify the parameter and the value is cheap to copy (int, double, float, char, bool, etc... Notice that std::string, std::vector, and the rest of the containers in the standard library are NOT)

  2. Pass by const pointer if the value is expensive to copy and the function does not want to modify the value pointed to and NULL is a value that the function handles.

  3. Pass by non-const pointer if the value is expensive to copy and the function wants to modify the value pointed to and NULL is a value that the function handles.

  4. Pass by const reference when the value is expensive to copy and the function does not want to modify the value referred to and NULL would not be a valid value if a pointer was used instead.

  5. Pass by non-const reference when the value is expensive to copy and the function wants to modify the value referred to and NULL would not be a valid value if a pointer was used instead.

Iterate over object attributes in python

Objects in python store their atributes (including functions) in a dict called __dict__. You can (but generally shouldn't) use this to access the attributes directly. If you just want a list, you can also call dir(obj), which returns an iterable with all the attribute names, which you could then pass to getattr.

However, needing to do anything with the names of the variables is usually bad design. Why not keep them in a collection?

class Foo(object):
    def __init__(self, **values):
        self.special_values = values

You can then iterate over the keys with for key in obj.special_values:

Javascript array search and remove string?

use:

array.splice(2, 1);

This removes one item from the array, starting at index 2 (3rd item)

How can I make Jenkins CI with Git trigger on pushes to master?

Generic Webhook Trigger Plugin can be configured with filters to achieve this.

When configured with

  • A variable named ref and expression $.ref.
  • A filter with text $ref and filter expression like ^refs/heads/master$.

Then that job will trigger for every push to master. No polling.

You probably want more values from the webhook to actually perform the build. Just add more variables, with JSONPath, to pick what you need.

There are some use cases here: https://github.com/jenkinsci/generic-webhook-trigger-plugin/tree/master/src/test/resources/org/jenkinsci/plugins/gwt/bdd

Installing a dependency with Bower from URL and specify version

Installs package from git and save to your bower.json dependency block.

  1. bower register package-name git-endpoint#version
  2. install package-name --save

(--save will save the package name version in the bower.json file inside the dependency block).

Reference

What is mod_php?

mod_php means PHP, as an Apache module.

Basically, when loading mod_php as an Apache module, it allows Apache to interpret PHP files (those are interpreted by mod_php).


EDIT : There are (at least) two ways of running PHP, when working with Apache :

  • Using CGI : a PHP process is launched by Apache, and it is that PHP process that interprets PHP code -- not Apache itself
  • Using PHP as an Apache module (called mod_php) : the PHP interpreter is then kind of "embedded" inside the Apache process : there is no external PHP process -- which means that Apache and PHP can communicate better.


And re-edit, after the comment : using CGI or mod_php is up to you : it's only a matter of configuration of your webserver.

To know which way is currently used on your server, you can check the output of phpinfo() : there should be something indicating whether PHP is running via mod_php (or mod_php5), or via CGI.

You might also want to take a look at the php_sapi_name() function : it returns the type of interface between web server and PHP.


If you check in your Apache's configuration files, when using mod_php, there should be a LoadModule line looking like this :

LoadModule php5_module        modules/libphp5.so

(The file name, on the right, can be different -- on Windows, for example, it should be a .dll)

Latest jQuery version on Google's CDN

If you wish to use jQuery CDN other than Google hosted jQuery library, you might consider using this and ensures uses the latest version of jQuery:

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

Initializing a list to a known number of elements in Python

Without knowing more about the problem domain, it's hard to answer your question. Unless you are certain that you need to do something more, the pythonic way to initialize a list is:

verts = []

Are you actually seeing a performance problem? If so, what is the performance bottleneck? Don't try to solve a problem that you don't have. It's likely that performance cost to dynamically fill an array to 1000 elements is completely irrelevant to the program that you're really trying to write.

The array class is useful if the things in your list are always going to be a specific primitive fixed-length type (e.g. char, int, float). But, it doesn't require pre-initialization either.

Getting all documents from one collection in Firestore

I prefer to hide all code complexity in my services... so, I generally use something like this:

In my events.service.ts

    async getEvents() {
        const snapchot = await this.db.collection('events').ref.get();
        return new Promise <Event[]> (resolve => {
            const v = snapchot.docs.map(x => {
                const obj = x.data();
                obj.id = x.id;
                return obj as Event;
            });
            resolve(v);
        });
    }

In my sth.page.ts

   myList: Event[];

   construct(private service: EventsService){}

   async ngOnInit() {
      this.myList = await this.service.getEvents();
   }

Enjoy :)

Node.js Logging

Winston is strong choice for most of the developers. I have been using winston for long. Recently I used winston with with papertrail which takes the application logging to next level.

Here is a nice screenshot from their site.

enter image description here

How its useful

  • you can manage logs from different systems at one place. this can be very useful when you have two backend communicating and can see logs from both at on place.

  • Logs are live. you can see realtime logs of your production server.

  • Powerful search and filter

  • you can create alerts to send you email if it encounters specific text in log.

and you can find more http://help.papertrailapp.com/kb/how-it-works/event-viewer/

A simple configuration using winston,winston-express and winston-papertrail node modules.

import winston from 'winston';
import expressWinston from 'express-winston';
//
// Requiring `winston-papertrail` will expose
// `winston.transports.Papertrail`
//
require('winston-papertrail').Papertrail;
// create winston transport for Papertrail
var winstonPapertrail = new winston.transports.Papertrail({
  host: 'logsX.papertrailapp.com',
  port: XXXXX
});
app.use(expressWinston.logger({
  transports: [winstonPapertrail],
  meta: true, // optional: control whether you want to log the meta data about the request (default to true)
  msg: "HTTP {{req.method}} {{req.url}}", // optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}"
  expressFormat: true, // Use the default Express/morgan request formatting. Enabling this will override any msg if true. Will only output colors with colorize set to true
  colorize: true, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red).
  ignoreRoute: function (req, res) { return false; } // optional: allows to skip some log messages based on request and/or response
}));

Shell equality operators (=, ==, -eq)

It depends on the Test Construct around the operator. Your options are double parentheses, double brackets, single brackets, or test.

If you use (()), you are testing arithmetic equality with == as in C:

$ (( 1==1 )); echo $?
0
$ (( 1==2 )); echo $?
1

(Note: 0 means true in the Unix sense and a failed test results in a non-zero number.)

Using -eq inside of double parentheses is a syntax error.

If you are using [] (or single brackets) or [[]] (or double brackets), or test you can use one of -eq, -ne, -lt, -le, -gt, or -ge as an arithmetic comparison.

$ [ 1 -eq 1 ]; echo $?
0
$ [ 1 -eq 2 ]; echo $?
1
$ test 1 -eq 1; echo $?
0

The == inside of single or double brackets (or the test command) is one of the string comparison operators:

$ [[ "abc" == "abc" ]]; echo $?
0
$ [[ "abc" == "ABC" ]]; echo $?
1

As a string operator, = is equivalent to ==. Also, note the whitespace around = or ==: it’s required.

While you can do [[ 1 == 1 ]] or [[ $(( 1+1 )) == 2 ]] it is testing the string equality — not the arithmetic equality.

So -eq produces the result probably expected that the integer value of 1+1 is equal to 2 even though the right-hand side is a string and has a trailing space:

$ [[ $(( 1+1 )) -eq  "2 " ]]; echo $?
0

While a string comparison of the same picks up the trailing space and therefore the string comparison fails:

$ [[ $(( 1+1 )) == "2 " ]]; echo $?
1

And a mistaken string comparison can produce a completely wrong answer. 10 is lexicographically less than 2, so a string comparison returns true or 0. So many are bitten by this bug:

$ [[ 10 < 2 ]]; echo $?
0

The correct test for 10 being arithmetically less than 2 is this:

$ [[ 10 -lt 2 ]]; echo $?
1

In comments, there is a question about the technical reason why using the integer -eq on strings returns true for strings that are not the same:

$ [[ "yes" -eq "no" ]]; echo $?
0

The reason is that Bash is untyped. The -eq causes the strings to be interpreted as integers if possible including base conversion:

$ [[ "0x10" -eq 16 ]]; echo $?
0
$ [[ "010" -eq 8 ]]; echo $?
0
$ [[ "100" -eq 100 ]]; echo $?
0

And 0 if Bash thinks it is just a string:

$ [[ "yes" -eq 0 ]]; echo $?
0
$ [[ "yes" -eq 1 ]]; echo $?
1

So [[ "yes" -eq "no" ]] is equivalent to [[ 0 -eq 0 ]]


Last note: Many of the Bash specific extensions to the Test Constructs are not POSIX and therefore may fail in other shells. Other shells generally do not support [[...]] and ((...)) or ==.

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

You will have to use the fluent API to do this.

Try adding the following to your DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{   
    modelBuilder.Entity<User>()
        .HasOptional(a => a.UserDetail)
        .WithOptionalDependent()
        .WillCascadeOnDelete(true);
}

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

Complete list of yahoo symbols/tickers/stocks is available for download(excel format) at below website. http://www.myinvestorshub.com/yahoo_stock_list.php

List updated to january 2016: http://investexcel.net/all-yahoo-finance-stock-tickers/

What is the best way to iterate over multiple lists at once?

You can use zip:

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
...   print x, y
... 
1 a
2 b
3 c

How do I determine k when using k-means clustering?

There is something called Rule of Thumb. It says that the number of clusters can be calculated by

k = (n/2)^0.5

where n is the total number of elements from your sample. You can check the veracity of this information on the following paper:

http://www.ijarcsms.com/docs/paper/volume1/issue6/V1I6-0015.pdf

There is also another method called G-means, where your distribution follows a Gaussian Distribution or Normal Distribution. It consists of increasing k until all your k groups follow a Gaussian Distribution. It requires a lot of statistics but can be done. Here is the source:

http://papers.nips.cc/paper/2526-learning-the-k-in-k-means.pdf

I hope this helps!

What is the difference between a web API and a web service?

In the context of ASP.Net a Web API is a Controller whose base class is ApiController and does not use Views. A Web Service is a class derived from WebService and has automatic WSDL generation. By default it is a SOAP api, but you can also use JSON by adding a ScriptServiceAttribute.

R dates "origin" must be supplied

So generally this has been solved, but you might get this error message because the date you use is not in the correct format.

I know this is an old post, but whenever I run this I get NA all the way down my date column. My dates are in this format 20150521 – NealC Jun 5 '15 at 16:06

If you have dates of this format just check the format of your dates with:

str(sides$date)

If the format is not a character, then convert it:

as.character(sides$date)

For as.Date, you won't need an origin any longer, because this is supplied for numeric values only. Thus you can use (assuming you have the format of NealC):

as.Date(as.character(sides$date),format="%Y%m%d")

I hope this might help some of you.

How do I put a clear button inside my HTML text input box like the iPhone does?

Firefox doesn't seem to support the clear search field functionality... I found this pure CSS solution that works nicely: Textbox with a clear button completely in CSS | Codepen | 2013. The magic happens at

.search-box:not(:valid) ~ .close-icon {
    display: none;
}

_x000D_
_x000D_
body {
    background-color: #f1f1f1;
    font-family: Helvetica,Arial,Verdana;

}
h2 {
    color: green;
    text-align: center;
}
.redfamily {
    color: red; 
}
.search-box,.close-icon,.search-wrapper {
    position: relative;
    padding: 10px;
}
.search-wrapper {
    width: 500px;
    margin: auto;
}
.search-box {
    width: 80%;
    border: 1px solid #ccc;
  outline: 0;
  border-radius: 15px;
}
.search-box:focus {
    box-shadow: 0 0 15px 5px #b0e0ee;
    border: 2px solid #bebede;
}
.close-icon {
    border:1px solid transparent;
    background-color: transparent;
    display: inline-block;
    vertical-align: middle;
  outline: 0;
  cursor: pointer;
}
.close-icon:after {
    content: "X";
    display: block;
    width: 15px;
    height: 15px;
    position: absolute;
    background-color: #FA9595;
    z-index:1;
    right: 35px;
    top: 0;
    bottom: 0;
    margin: auto;
    padding: 2px;
    border-radius: 50%;
    text-align: center;
    color: white;
    font-weight: normal;
    font-size: 12px;
    box-shadow: 0 0 2px #E50F0F;
    cursor: pointer;
}
.search-box:not(:valid) ~ .close-icon {
    display: none;
}
_x000D_
<h2>
    Textbox with a clear button completely in CSS <br> <span class="redfamily">< 0 lines of JavaScript ></span>
</h2>
<div class="search-wrapper">
    <form>
    <input type="text" name="focus" required class="search-box" placeholder="Enter search term" />
        <button class="close-icon" type="reset"></button>
    </form>
</div>
_x000D_
_x000D_
_x000D_

I needed more functionality and added this jQuery in my code:

$('.close-icon').click(function(){ /* my code */ });

How can I pass selected row to commandLink inside dataTable or ui:repeat?

Thanks to this site by Mkyong, the only solution that actually worked for us to pass a parameter was this

<h:commandLink action="#{user.editAction}">
    <f:param name="myId" value="#{param.id}" />
</h:commandLink>

with

public String editAction() {

  Map<String,String> params = 
            FacesContext.getExternalContext().getRequestParameterMap();
  String idString = params.get("myId");
  long id = Long.parseLong(idString);
  ...
}

Technically, that you cannot pass to the method itself directly, but to the JSF request parameter map.

Less than or equal to

You can use:

EQU - equal

NEQ - not equal

LSS - less than

LEQ - less than or equal

GTR - greater than

GEQ - greater than or equal

AVOID USING:

() ! ~ - * / % + - << >> & | = *= /= %= += -= &= ^= |= <<= >>=

This view is not constrained

From Android Studio v3 and up, Infer Constraint was removed from the dropdown.

Use the magic wand icon in the toolbar menu above the design preview; there is the "Infer Constraints" button. Click on this button, this will automatically add some lines in the text field and the red line will be removed.

enter image description here

character count using jquery

Use .length to count number of characters, and $.trim() function to remove spaces, and replace(/ /g,'') to replace multiple spaces with just one. Here is an example:

   var str = "      Hel  lo       ";
   console.log(str.length); 
   console.log($.trim(str).length); 
   console.log(str.replace(/ /g,'').length); 

Output:

20
7
5

Source: How to count number of characters in a string with JQuery

Converting 'ArrayList<String> to 'String[]' in Java

In Java 8, it can be done using

String[] arrayFromList = fromlist.stream().toArray(String[]::new);

browser.msie error after update to jQuery 1.9.1

Since $.browser is deprecated, here is an alternative solution:

/**
 * Returns the version of Internet Explorer or a -1
 * (indicating the use of another browser).
 */
function getInternetExplorerVersion()
{
    var rv = -1; // Return value assumes failure.

    if (navigator.appName == 'Microsoft Internet Explorer')
    {
        var ua = navigator.userAgent;
        var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat( RegExp.$1 );
    }

    return rv;
}

function checkVersion()
{
    var msg = "You're not using Internet Explorer.";
    var ver = getInternetExplorerVersion();

    if ( ver > -1 )
    {
        if ( ver >= 8.0 ) 
            msg = "You're using a recent copy of Internet Explorer."
        else
            msg = "You should upgrade your copy of Internet Explorer.";
    }

    alert( msg );
}

Source

However, the reason that its deprecated is because jQuery wants you to use feature detection instead.

An example:

$("p").html("This frame uses the W3C box model: <span>" +
        jQuery.support.boxModel + "</span>");

And last but not least, the most reliable way to check IE versions:

// ----------------------------------------------------------
// A short snippet for detecting versions of IE in JavaScript
// without resorting to user-agent sniffing
// ----------------------------------------------------------
// If you're not in IE (or IE version is less than 5) then:
//     ie === undefined
// If you're in IE (>=5) then you can determine which version:
//     ie === 7; // IE7
// Thus, to detect IE:
//     if (ie) {}
// And to detect the version:
//     ie === 6 // IE6
//     ie > 7 // IE8, IE9 ...
//     ie < 9 // Anything less than IE9
// ----------------------------------------------------------

// UPDATE: Now using Live NodeList idea from @jdalton

var ie = (function(){

    var undef,
        v = 3,
        div = document.createElement('div'),
        all = div.getElementsByTagName('i');

    while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
        all[0]
    );

    return v > 4 ? v : undef;

}());

HtmlEncode from Class Library

System.Net.WebUtility class is available starting from .NET 4.0 (You don't need System.Web.dll dependency).

angularjs - ng-repeat: access key and value from JSON array object

You've got an array of objects, so you'll need to use ng-repeat twice, like:

<ul ng-repeat="item in items">
  <li ng-repeat="(key, val) in item">
    {{key}}: {{val}}
  </li>
</ul>

Example: http://jsfiddle.net/Vwsej/

Edit:

Note that properties order in objects are not guaranteed.

<table>
    <tr>
        <th ng-repeat="(key, val) in items[0]">{{key}}</th>
    </tr>
    <tr ng-repeat="item in items">
        <td ng-repeat="(key, val) in item">{{val}}</td>
    </tr>
</table>

Example: http://jsfiddle.net/Vwsej/2/

How to align matching values in two columns in Excel, and bring along associated values in other columns

assuming the item numbers are unique, a VLOOKUP should get you the information you need.

first value would be =VLOOKUP(E1,A:B,2,FALSE), and the same type of formula to retrieve the second value would be =VLOOKUP(E1,C:D,2,FALSE). Wrap them in an IFERROR if you want to return anything other than #N/A if there is no corresponding value in the item column(s)

How to modify values of JsonObject / JsonArray directly?

public static JSONObject convertFileToJSON(String fileName, String username, List<String> list)
            throws FileNotFoundException, IOException, org.json.simple.parser.ParseException {
        JSONObject json = new JSONObject();
        String jsonStr = new String(Files.readAllBytes(Paths.get(fileName)));
        json = new JSONObject(jsonStr);
        System.out.println(json);
        JSONArray jsonArray = json.getJSONArray("users");
        JSONArray finalJsonArray = new JSONArray();
        /**
         * Get User form setNewUser method
         */
        //finalJsonArray.put(setNewUserPreference());
        boolean has = true;
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            finalJsonArray.put(jsonObject);
            String username2 = jsonObject.getString("userName");
            if (username2.equals(username)) {
                has = true;
            }
            System.out.println("user name  are :" + username2);
            JSONObject jsonObject2 = jsonObject.getJSONObject("languages");
            String eng = jsonObject2.getString("Eng");
            String fin = jsonObject2.getString("Fin");
            String ger = jsonObject2.getString("Ger");
            jsonObject2.put("Eng", "ChangeEnglishValueCheckForLongValue");
            System.out.println(" Eng : " + eng + "  Fin " + fin + "  ger : " + ger);
        }
        System.out.println("Final JSON Array \n" + json);
        jsonArray.put(setNewUserPreference());
        return json;
    }

Practical uses for AtomicInteger

There are two main uses of AtomicInteger:

  • As an atomic counter (incrementAndGet(), etc) that can be used by many threads concurrently

  • As a primitive that supports compare-and-swap instruction (compareAndSet()) to implement non-blocking algorithms.

    Here is an example of non-blocking random number generator from Brian Göetz's Java Concurrency In Practice:

    public class AtomicPseudoRandom extends PseudoRandom {
        private AtomicInteger seed;
        AtomicPseudoRandom(int seed) {
            this.seed = new AtomicInteger(seed);
        }
    
        public int nextInt(int n) {
            while (true) {
                int s = seed.get();
                int nextSeed = calculateNext(s);
                if (seed.compareAndSet(s, nextSeed)) {
                    int remainder = s % n;
                    return remainder > 0 ? remainder : remainder + n;
                }
            }
        }
        ...
    }
    

    As you can see, it basically works almost the same way as incrementAndGet(), but performs arbitrary calculation (calculateNext()) instead of increment (and processes the result before return).

Maintain image aspect ratio when changing height

This behavior is expected. flex container will stretch all its children by default. Image have no exception. (ie, parent will have align-items: stretch property )

To keep the aspect ratio we've two solutions:

  1. Either replace default align-items: stretch property to align-items: flex-start or align-self: center etc, http://jsfiddle.net/e394Lqnt/3/

or

  1. Set align property exclusively to the child itself: like, align-self: center or align-self: flex-start etc. http://jsfiddle.net/e394Lqnt/2/

Why is Maven downloading the maven-metadata.xml every time?

Look in your settings.xml (or, possibly your project's parent or corporate parent POM) for the <repositories> element. It will look something like the below.

<repositories>
    <repository>
        <id>central</id>
        <url>http://gotoNexus</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
        </snapshots>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
        </releases>
    </repository>
</repositories>

Note the <updatePolicy> element. The example tells Maven to contact the remote repo (Nexus in my case, Maven Central if you're not using your own remote repo) any time Maven needs to retrieve a snapshot artifact during a build, checking to see if there's a newer copy. The metadata is required for this. If there is a newer copy Maven downloads it to your local repo.

In the example, for releases, the policy is daily so it will check during your first build of the day. never is also a valid option, as described in Maven settings docs.

Plugins are resolved separately. You may have repositories configured for those as well, with different update policies if desired.

<pluginRepositories>
    <pluginRepository>
        <id>central</id>
        <url>http://gotoNexus</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
        </snapshots>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>never</updatePolicy>
        </releases>
    </pluginRepository>
</pluginRepositories>

Someone else mentioned the -o option. If you use that, Maven runs in "offline" mode. It knows it has a local repo only, and it won't contact the remote repo to refresh the artifacts no matter what update policies you use.

What is the default Jenkins password?

Similar to the Ubuntu answer above, the Windows admin default password is stored in {jenkins install dir}\secrets\initialAdminPassword file (default install location would it in C:\Program Files (x86)\Jenkins\secrets\initialAdminPassword )

How to read a text file?

It depends on what you are trying to do.

file, err := os.Open("file.txt")
fmt.print(file)

The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File), not file-content. To obtain file-content, you may READ from a file-descriptor.


To read all file content(in bytes) to memory, ioutil.ReadAll

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


  b, err := ioutil.ReadAll(file)
  fmt.Print(b)
}

But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read from *os.File

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


    buf := make([]byte, 32*1024) // define your buffer size here.

    for {
        n, err := file.Read(buf)

        if n > 0 {
            fmt.Print(buf[:n]) // your read buffer.
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Printf("read %d bytes: %v", n, err)
            break
        }
    }

}

Otherwise, you could also use the standard util package: bufio, try Scanner. A Scanner reads your file in tokens: separator.

By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {             // internally, it advances token based on sperator
        fmt.Println(scanner.Text())  // token in unicode-char
        fmt.Println(scanner.Bytes()) // token in bytes

    }
}

Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.

How to get the CUDA version?

If there is a version mismatch between nvcc and nvidia-smi then different versions of cuda are used as driver and run time environemtn.

To ensure same version of CUDA drivers are used what you need to do is to get CUDA on system path.

First run whereis cuda and find the location of cuda driver.

Then go to .bashrc and modify the path variable and set the directory precedence order of search using variable 'LD_LIBRARY_PATH'.

for instance

$ whereis cuda
cuda: /usr/lib/cuda /usr/include/cuda.h /usr/local/cuda

CUDA is installed at /usr/local/cuda, now we need to to .bashrc and add the path variable as:

vim  ~/.bashrc
export PATH="/usr/local/cuda/bin:${PATH}"

and after this line set the directory search path as:

export LD_LIBRARY_PATH="/usr/local/cuda/lib64:${LD_LIBRARY_PATH}"

Then save the .bashrc file. And refresh it as:

$ source ~/.bashrc

This will ensure you have nvcc -V and nvidia-smi to use the same version of drivers.

SQL: How do I SELECT only the rows with a unique value on certain column?

I'm a fan of NOT EXISTS

SELECT DISTINCT contract, activity FROM table t1
WHERE NOT EXISTS (
  SELECT * FROM table t2
  WHERE t2.contract = t1.contract AND t2.activity != t1.activity
)

How can I perform a reverse string search in Excel without using VBA?

This is the technique I've used with great success:

=TRIM(RIGHT(SUBSTITUTE(A1, " ", REPT(" ", 100)), 100))

To get the first word in a string, just change from RIGHT to LEFT

=TRIM(LEFT(SUBSTITUTE(A1, " ", REPT(" ", 100)), 100))

Also, replace A1 by the cell holding the text.

Real escape string and PDO

PDO offers an alternative designed to replace mysql_escape_string() with the PDO::quote() method.

Here is an excerpt from the PHP website:

<?php
    $conn = new PDO('sqlite:/home/lynn/music.sql3');

    /* Simple string */
    $string = 'Nice';
    print "Unquoted string: $string\n";
    print "Quoted string: " . $conn->quote($string) . "\n";
?>

The above code will output:

Unquoted string: Nice
Quoted string: 'Nice'

Truncate to three decimals in Python

Maybe this way:

def myTrunc(theNumber, theDigits):

    myDigits = 10 ** theDigits
    return (int(theNumber * myDigits) / myDigits)

Python read-only property

I am dissatisfied with the previous two answers to create read only properties because the first solution allows the readonly attribute to be deleted and then set and doesn't block the __dict__. The second solution could be worked around with testing - finding the value that equals what you set it two and changing it eventually.

Now, for the code.

def final(cls):
    clss = cls
    @classmethod
    def __init_subclass__(cls, **kwargs):
        raise TypeError("type '{}' is not an acceptable base type".format(clss.__name__))
    cls.__init_subclass__ = __init_subclass__
    return cls


def methoddefiner(cls, method_name):
    for clss in cls.mro():
        try:
            getattr(clss, method_name)
            return clss
        except(AttributeError):
            pass
    return None
            
            
def readonlyattributes(*attrs):
    """Method to create readonly attributes in a class
    
    Use as a decorator for a class. This function takes in unlimited 
    string arguments for names of readonly attributes and returns a
    function to make the readonly attributes readonly. 
    
    The original class's __getattribute__, __setattr__, and __delattr__ methods
    are redefined so avoid defining those methods in the decorated class
    
    You may create setters and deleters for readonly attributes, however
    if they are overwritten by the subclass, they lose access to the readonly
    attributes. 
    
    Any method which sets or deletes a readonly attribute within
    the class loses access if overwritten by the subclass besides the __new__
    or __init__ constructors.
    
    This decorator doesn't support subclassing of these classes
    """
    def classrebuilder(cls):
        def __getattribute__(self, name):
            if name == '__dict__':
                    from types import MappingProxyType
                    return MappingProxyType(super(cls, self).__getattribute__('__dict__'))
            return super(cls, self).__getattribute__(name)
        def __setattr__(self, name, value): 
                if name == '__dict__' or name in attrs:
                    import inspect
                    stack = inspect.stack()
                    try:
                        the_class = stack[1][0].f_locals['self'].__class__
                    except(KeyError):
                        the_class = None
                    the_method = stack[1][0].f_code.co_name
                    if the_class != cls: 
                         if methoddefiner(type(self), the_method) != cls:
                            raise AttributeError("Cannot set readonly attribute '{}'".format(name))                        
                return super(cls, self).__setattr__(name, value)
        def __delattr__(self, name):                
                if name == '__dict__' or name in attrs:
                    import inspect
                    stack = inspect.stack()
                    try:
                        the_class = stack[1][0].f_locals['self'].__class__
                    except(KeyError):
                        the_class = None
                    the_method = stack[1][0].f_code.co_name
                    if the_class != cls:
                        if methoddefiner(type(self), the_method) != cls:
                            raise AttributeError("Cannot delete readonly attribute '{}'".format(name))                        
                return super(cls, self).__delattr__(name)
        clss = cls
        cls.__getattribute__ = __getattribute__
        cls.__setattr__ = __setattr__
        cls.__delattr__ = __delattr__
        #This line will be moved when this algorithm will be compatible with inheritance
        cls = final(cls)
        return cls
    return classrebuilder

def setreadonlyattributes(cls, *readonlyattrs):
    return readonlyattributes(*readonlyattrs)(cls)


if __name__ == '__main__':
    #test readonlyattributes only as an indpendent module
    @readonlyattributes('readonlyfield')
    class ReadonlyFieldClass(object):
        def __init__(self, a, b):
            #Prevent initalization of the internal, unmodified PrivateFieldClass
            #External PrivateFieldClass can be initalized
            self.readonlyfield = a
            self.publicfield = b
            

    attr = None
    def main():
        global attr
        pfi = ReadonlyFieldClass('forbidden', 'changable')
        ###---test publicfield, ensure its mutable---###
        try:
            #get publicfield
            print(pfi.publicfield)
            print('__getattribute__ works')
            #set publicfield
            pfi.publicfield = 'mutable'
            print('__setattr__ seems to work')
            #get previously set publicfield
            print(pfi.publicfield)
            print('__setattr__ definitely works')
            #delete publicfield
            del pfi.publicfield 
            print('__delattr__ seems to work')
            #get publicfield which was supposed to be deleted therefore should raise AttributeError
            print(pfi.publlicfield)
            #publicfield wasn't deleted, raise RuntimeError
            raise RuntimeError('__delattr__ doesn\'t work')
        except(AttributeError):
            print('__delattr__ works')
        
        
        try:
            ###---test readonly, make sure its readonly---###
            #get readonlyfield
            print(pfi.readonlyfield)
            print('__getattribute__ works')
            #set readonlyfield, should raise AttributeError
            pfi.readonlyfield = 'readonly'
            #apparently readonlyfield was set, notify user
            raise RuntimeError('__setattr__ doesn\'t work')
        except(AttributeError):
            print('__setattr__ seems to work')
            try:
                #ensure readonlyfield wasn't set
                print(pfi.readonlyfield)
                print('__setattr__ works')
                #delete readonlyfield
                del pfi.readonlyfield
                #readonlyfield was deleted, raise RuntimeError
                raise RuntimeError('__delattr__ doesn\'t work')
            except(AttributeError):
                print('__delattr__ works')
        try:
            print("Dict testing")
            print(pfi.__dict__, type(pfi.__dict__))
            attr = pfi.readonlyfield
            print(attr)
            print("__getattribute__ works")
            if pfi.readonlyfield != 'forbidden':
                print(pfi.readonlyfield)
                raise RuntimeError("__getattr__ doesn't work")
            try:
                pfi.__dict__ = {}
                raise RuntimeError("__setattr__ doesn't work")
            except(AttributeError):
                print("__setattr__ works")
            del pfi.__dict__
            raise RuntimeError("__delattr__ doesn't work")
        except(AttributeError):
            print(pfi.__dict__)
            print("__delattr__ works")
            print("Basic things work")


main()
        

There is no point to making read only attributes except when your writing library code, code which is being distributed to others as code to use in order to enhance their programs, not code for any other purpose, like app development. The __dict__ problem is solved, because the __dict__ is now of the immutable types.MappingProxyType, so attributes cannot be changed through the __dict__. Setting or deleting __dict__ is also blocked. The only way to change read only properties is through changing the methods of the class itself.

Though I believe my solution is better than of the previous two, it could be improved. These are this code's weaknesses:

  1. Doesn't allow adding to a method in a subclass which sets or deletes a readonly attribute. A method defined in a subclass is automatically barred from accessing a readonly attribute, even by calling the superclass' version of the method.

  2. The class' readonly methods can be changed to defeat the read only restrictions.

However, there is not way without editing the class to set or delete a read only attribute. This isn't dependent on naming conventions, which is good because Python isn't so consistent with naming conventions. This provides a way to make read only attributes that cannot be changed with hidden loopholes without editing the class itself. Simply list the attributes to be read only when calling the decorator as arguments and they will become read only.

Credit to Brice's answer for getting the caller classes and methods.

How to set HTML5 required attribute in Javascript?

let formelems = document.querySelectorAll('input,textarea,select');
formelems.forEach((formelem) => {
  formelem.required = true;

});

If you wish to make all input, textarea, and select elements required.

How do you convert an entire directory with ffmpeg?

For giggles, here's solution in fish-shell:

for i in *.avi; ffmpeg -i "$i" (string split -r -m1 . $i)[1]".mp4"; end

Easiest way to flip a boolean value?

Just because my favorite odd ball way to toggle a bool is not listed...

bool x = true;
x = x == false;

works too. :)

(yes the x = !x; is clearer and easier to read)

Spring Boot default H2 jdbc connection (and H2 console)

This is how I got the H2 console working in spring-boot with H2. I am not sure if this is right but since no one else has offered a solution then I am going to suggest this is the best way to do it.

In my case, I chose a specific name for the database so that I would have something to enter when starting the H2 console (in this case, "AZ"). I think all of these are required though it seems like leaving out the spring.jpa.database-platform does not hurt anything.

In application.properties:

spring.datasource.url=jdbc:h2:mem:AZ;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

In Application.java (or some configuration):

@Bean
public ServletRegistrationBean h2servletRegistration() {
    ServletRegistrationBean registration = new ServletRegistrationBean(new WebServlet());
    registration.addUrlMappings("/console/*");
    return registration;
}

Then you can access the H2 console at {server}/console/. Enter this as the JDBC URL: jdbc:h2:mem:AZ

HTML Table width in percentage, table rows separated equally

This is definitely the cleanest answer to the question: https://stackoverflow.com/a/14025331/1008519. In combination with table-layout: fixed I often find <colgroup> a great tool to make columns act as you want (see codepen here):

_x000D_
_x000D_
table {_x000D_
 /* When set to 'fixed', all columns that do not have a width applied will get the remaining space divided between them equally */_x000D_
 table-layout: fixed;_x000D_
}_x000D_
.fixed-width {_x000D_
  width: 100px;_x000D_
}_x000D_
.col-12 {_x000D_
  width: 100%;_x000D_
}_x000D_
.col-11 {_x000D_
  width: 91.666666667%;_x000D_
}_x000D_
.col-10 {_x000D_
  width: 83.333333333%;_x000D_
}_x000D_
.col-9 {_x000D_
  width: 75%;_x000D_
}_x000D_
.col-8 {_x000D_
  width: 66.666666667%;_x000D_
}_x000D_
.col-7 {_x000D_
  width: 58.333333333%;_x000D_
}_x000D_
.col-6 {_x000D_
  width: 50%;_x000D_
}_x000D_
.col-5 {_x000D_
  width: 41.666666667%;_x000D_
}_x000D_
.col-4 {_x000D_
  width: 33.333333333%;_x000D_
}_x000D_
.col-3 {_x000D_
  width: 25%;_x000D_
}_x000D_
.col-2 {_x000D_
  width: 16.666666667%;_x000D_
}_x000D_
.col-1 {_x000D_
  width: 8.3333333333%;_x000D_
}_x000D_
_x000D_
/* Stylistic improvements from here */_x000D_
_x000D_
.align-left {_x000D_
  text-align: left;_x000D_
}_x000D_
.align-right {_x000D_
  text-align: right;_x000D_
}_x000D_
table {_x000D_
  width: 100%;_x000D_
}_x000D_
table > tbody > tr > td,_x000D_
table > thead > tr > th {_x000D_
  padding: 8px;_x000D_
  border: 1px solid gray;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" border="0">_x000D_
  <colgroup>_x000D_
    <col /> <!-- take up rest of the space -->_x000D_
    <col class="fixed-width" /> <!-- fixed width -->_x000D_
    <col class="col-3" /> <!-- percentage width -->_x000D_
    <col /> <!-- take up rest of the space -->_x000D_
  </colgroup>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th class="align-left">Title</th>_x000D_
      <th class="align-right">Count</th>_x000D_
      <th class="align-left">Name</th>_x000D_
      <th class="align-left">Single</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td class="align-left">This is a very looooooooooong title that may break into multiple lines</td>_x000D_
      <td class="align-right">19</td>_x000D_
      <td class="align-left">Lisa McArthur</td>_x000D_
      <td class="align-left">No</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td class="align-left">This is a shorter title</td>_x000D_
      <td class="align-right">2</td>_x000D_
      <td class="align-left">John Oliver Nielson McAllister</td>_x000D_
      <td class="align-left">Yes</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
_x000D_
_x000D_
<table cellpadding="0" cellspacing="0" border="0">_x000D_
  <!-- define everything with percentage width -->_x000D_
  <colgroup>_x000D_
    <col class="col-6" />_x000D_
    <col class="col-1" />_x000D_
    <col class="col-4" />_x000D_
    <col class="col-1" />_x000D_
  </colgroup>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th class="align-left">Title</th>_x000D_
      <th class="align-right">Count</th>_x000D_
      <th class="align-left">Name</th>_x000D_
      <th class="align-left">Single</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td class="align-left">This is a very looooooooooong title that may break into multiple lines</td>_x000D_
      <td class="align-right">19</td>_x000D_
      <td class="align-left">Lisa McArthur</td>_x000D_
      <td class="align-left">No</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td class="align-left">This is a shorter title</td>_x000D_
      <td class="align-right">2</td>_x000D_
      <td class="align-left">John Oliver Nielson McAllister</td>_x000D_
      <td class="align-left">Yes</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Modifying a query string without reloading the page

I've used the following JavaScript library with great success:

https://github.com/balupton/jquery-history

It supports the HTML5 history API as well as a fallback method (using #) for older browsers.

This library is essentially a polyfill around `history.pushState'.

How to get list of all installed packages along with version in composer?

To list the globally installed composer packages:

composer global show -i

how to make negative numbers into positive

floor a;
floor b;
a = -0.340515;

so what to do?

b = 65565 +a;
a = 65565 -b;

or

if(a < 0){
a = 65565-(65565+a);}

Normalize data in pandas

If you don't mind importing the sklearn library, I would recommend the method talked on this blog.

import pandas as pd
from sklearn import preprocessing

data = {'score': [234,24,14,27,-74,46,73,-18,59,160]}
cols = data.columns
df = pd.DataFrame(data)
df

min_max_scaler = preprocessing.MinMaxScaler()
np_scaled = min_max_scaler.fit_transform(df)
df_normalized = pd.DataFrame(np_scaled, columns = cols)
df_normalized

How to add a char/int to an char array in C?

Suggest replacing this:

char str[1024];
char tmp = '.';

strcat(str, tmp);

with this:

char str[1024] = {'\0'}; // set array to initial all NUL bytes
char tmp[] = "."; // create a string for the call to strcat()

strcat(str, tmp); // 

filters on ng-model in an input

I would suggest to watch model value and update it upon chage: http://plnkr.co/edit/Mb0uRyIIv1eK8nTg3Qng?p=preview

The only interesting issue is with spaces: In AngularJS 1.0.3 ng-model on input automatically trims string, so it does not detect that model was changed if you add spaces at the end or at start (so spaces are not automatically removed by my code). But in 1.1.1 there is 'ng-trim' directive that allows to disable this functionality (commit). So I've decided to use 1.1.1 to achieve exact functionality you described in your question.

Jackson: how to prevent field serialization

Starting with Jackson 2.6, a property can be marked as read- or write-only. It's simpler than hacking the annotations on both accessors and keeps all the information in one place:

public class User {
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String password;
}

Best way to store date/time in mongodb

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

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

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

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

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

How do I check if a C++ string is an int?

The accepted answer will give a false positive if the input is a number plus text, because "stol" will convert the firsts digits and ignore the rest.

I like the following version the most, since it's a nice one-liner that doesn't need to define a function and you can just copy and paste wherever you need it.

#include <string>

...

std::string s;

bool has_only_digits = (s.find_first_not_of( "0123456789" ) == std::string::npos);

EDIT: if you like this implementation but you do want to use it as a function, then this should do:

bool has_only_digits(const string s){
  return s.find_first_not_of( "0123456789" ) == string::npos;
}

MVC 4 @Scripts "does not exist"

I had a very similar error when upgrading a project from MVC3 to MVC4.

Compiler Error Message: CS0103: The name [blah] does not exist in the current context

In my case, I had outdated version numbers in several of my Web.Configs.

  1. I needed to update the System.Web.Mvc version number from "3.0.0.0" to "4.0.0.0" in every Web.Config in my project.
  2. I needed to update all of my System.Web.WebPages, System.Web.Helpers, and System.Web.Razor version numbers from "1.0.0.0" to "2.0.0.0" in every Web.Config in my project.

Ex:

<configSections>
  <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
  </sectionGroup>
</configSections>

...

<compilation debug="true" targetFramework="4.0">
  <assemblies>
    <add assembly="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <add assembly="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  </assemblies>
</compilation>

Be sure to review the Web.Configs in each of your Views directories.

You can read more about Upgrading an ASP.NET MVC 3 Project to ASP.NET MVC 4.

What is the strict aliasing rule?

This is the strict aliasing rule, found in section 3.10 of the C++03 standard (other answers provide good explanation, but none provided the rule itself):

If a program attempts to access the stored value of an object through an lvalue of other than one of the following types the behavior is undefined:

  • the dynamic type of the object,
  • a cv-qualified version of the dynamic type of the object,
  • a type that is the signed or unsigned type corresponding to the dynamic type of the object,
  • a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
  • an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union),
  • a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,
  • a char or unsigned char type.

C++11 and C++14 wording (changes emphasized):

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:

  • the dynamic type of the object,
  • a cv-qualified version of the dynamic type of the object,
  • a type similar (as defined in 4.4) to the dynamic type of the object,
  • a type that is the signed or unsigned type corresponding to the dynamic type of the object,
  • a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
  • an aggregate or union type that includes one of the aforementioned types among its elements or non-static data members (including, recursively, an element or non-static data member of a subaggregate or contained union),
  • a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,
  • a char or unsigned char type.

Two changes were small: glvalue instead of lvalue, and clarification of the aggregate/union case.

The third change makes a stronger guarantee (relaxes the strong aliasing rule): The new concept of similar types that are now safe to alias.


Also the C wording (C99; ISO/IEC 9899:1999 6.5/7; the exact same wording is used in ISO/IEC 9899:2011 §6.5 ¶7):

An object shall have its stored value accessed only by an lvalue expression that has one of the following types 73) or 88):

  • a type compatible with the effective type of the object,
  • a quali?ed version of a type compatible with the effective type of the object,
  • a type that is the signed or unsigned type corresponding to the effective type of the object,
  • a type that is the signed or unsigned type corresponding to a quali?ed version of the effective type of the object,
  • an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
  • a character type.

73) or 88) The intent of this list is to specify those circumstances in which an object may or may not be aliased.

Use superscripts in R axis labels

This is a quick example

plot(rnorm(30), xlab = expression(paste("4"^"th")))

SQL Server command line backup statement

I am using SQL Server 2005 Express, and I had to enable Named Pipes connection to be able to backup from the Windows Command. My final script is this:

@echo off
set DB_NAME=Your_DB_Name
set BK_FILE=D:\DB_Backups\%DB_NAME%.bak
set DB_HOSTNAME=Your_DB_Hostname
echo.
echo.
echo Backing up %DB_NAME% to %BK_FILE%...
echo.
echo.
sqlcmd -E -S np:\\%DB_HOSTNAME%\pipe\MSSQL$SQLEXPRESS\sql\query -d master -Q "BACKUP DATABASE [%DB_NAME%] TO DISK = N'%BK_FILE%' WITH INIT , NOUNLOAD , NAME = N'%DB_NAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
echo Done!
echo.

It's working just fine here!!

Convert UTC date time to local date time

I believe this is the best solution:

  let date = new Date(objDate);
  date.setMinutes(date.getTimezoneOffset());

This will update your date by the offset appropriately since it is presented in minutes.

Error inflating class fragment

For me it was after scrolling in the stack trace i found im missing the permission for android.permission.ACCESS_NETWORK_STATE

after adding this permission it was fixed

How do I create test and train samples from one dataframe with pandas?

I would use scikit-learn's own training_test_split, and generate it from the index

from sklearn.model_selection import train_test_split


y = df.pop('output')
X = df

X_train,X_test,y_train,y_test = train_test_split(X.index,y,test_size=0.2)
X.iloc[X_train] # return dataframe train

How do you run a command as an administrator from the Windows command line?

Browse to C:\windows\System32 and right click on cmd.exe and run as Administrator. Worked for me on Windows 7.

If you are trying to run a script with elevated privileges you could do the same for the script file or use the scheduler's run as a different user option to run the script.