Programs & Examples On #Onclientclick

The OnClientClick property is used to sets a client side script to be run when the Button control is clicked.

OnClick vs OnClientClick for an asp:CheckBox?

Because they are two different kinds of controls...

You see, your web browser doesn't know about server side programming. it only knows about it's own DOM and the event models that it uses... And for click events of objects rendered to it. You should examine the final markup that is actually sent to the browser from ASP.Net to see the differences your self.

<asp:CheckBox runat="server" OnClick="alert(this.checked);" />

renders to

<input type="check" OnClick="alert(this.checked);" />

and

<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />

renders to

<input type="check" OnClientClick="alert(this.checked);" />

Now, as near as i can recall, there are no browsers anywhere that support the "OnClientClick" event in their DOM...

When in doubt, always view the source of the output as it is sent to the browser... there's a whole world of debug information that you can see.

Get text of label with jquery

for the line you wrote

var g = $('<%=Label1.ClientID%>').val(); // Also I tried .text() and .html()

you missed adding #. it should be like this

var g = $('#<%=Label1.ClientID%>').text();

also I do not prefer using this method

that's because if you are calling a control in master or nested master page or if you are calling a control in page from master. Also controls in Repeater. regardless the MVC. this will cause problems.

you should ALWAYS call the ID of the control directly. like this

$('#ControlID')

this is simple and clear. but do not forget to set

ClientIDMode="Static"

in your controls to remain with same ID name after render. that's because ASP.net will modify the ID name in HTML rendered file in some contexts i.e. the page is for Master page the control name will be ConetentPlaceholderName_controlID

I hope it clears the question Good Luck

OnclientClick and OnClick is not working at the same time?

Vinay (above) gave an effective work-around. What's actually causing the button's OnClick event to not work following the OnClientClick event function is that MS has defined it where, once the button is disabled (in the function called by the OnClientClick event), the button "honors" this by not trying to complete the button's activity by calling the OnClick event's defined method.

I struggled several hours trying to figure this out. Once I removed the statement to disable the submit button (that was inside the OnClientClick function), the OnClick method was called with no further problem.

Microsoft, if you're listening, once the button is clicked it should complete it's assigned activity even if it is disabled part of the way through this activity. As long as it is not disabled when it is clicked, it should complete all assigned methods.

Default passwords of Oracle 11g?

Once installed in windows Followed the instructions starting from Run SQL Command Line (command prompt)

then... v. SQL> connect /as sysdba

Connected. [SQL prompt response]

vi. SQL> alter user SYS identified by "newpassword";

User altered. [SQL prompt response]

Thank you. This minimized a headache

In STL maps, is it better to use map::insert than []?

The two have different semantics when it comes to the key already existing in the map. So they aren't really directly comparable.

But the operator[] version requires default constructing the value, and then assigning, so if this is more expensive then copy construction, then it will be more expensive. Sometimes default construction doesn't make sense, and then it would be impossible to use the operator[] version.

Create an array with same element repeated multiple times

Use this function:

function repeatElement(element, count) {
    return Array(count).fill(element)
}
>>> repeatElement('#', 5).join('')
"#####"

Or for a more compact version:

const repeatElement = (element, count) =>
    Array(count).fill(element)
>>> repeatElement('#', 5).join('')
"#####"

Or for a curry-able version:

const repeatElement = element => count =>
    Array(count).fill(element)
>>> repeatElement('#')(5).join('')
"#####"

You can use this function with a list:

const repeatElement = (element, count) =>
    Array(count).fill(element)

>>> ['a', 'b', ...repeatElement('c', 5)]
['a', 'b', 'c', 'c', 'c', 'c', 'c']

How to run a single RSpec test?

You can pass a regex to the spec command which will only run it blocks matching the name you supply.

spec path/to/my_spec.rb -e "should be the correct answer"

2019 Update: Rspec2 switched from the 'spec' command to the 'rspec' command.

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

TL;DR. You can get around this by expressing your queries as MyModel::query()->find(10); instead of MyModel::find(10);.

To the best of my knowledge, starting PhpStorm 2017.2 code inspection fails for methods such as MyModel::where(), MyModel::find(), etc (check this thread). This could get quite annoying, when you try let's say to use PhpStorm's Git integration before committing your code, PhpStorm won't stop complaining about these static method call warnings.

One elegant way (IMOO) to get around this is to explicitly call ::query() wherever it makes sense to. This will let you benefit from a free auto-completion and a nice query formatting.

Examples

Snippet where inspection complains about static method calls

$myModel = MyModel::find(10); // static call complaint

// another poorly formatted query with code inspection complaints
$myFilteredModels = MyModel::where('is_beautiful', true)
    ->where('is_not_smart', false)
    ->get();

Well formatted code with no complaints

$myModel = MyModel::query()->find(10);

// a nicely formatted query with no complaints
$myFilteredModels = MyModel::query()
    ->where('is_beautiful', true)
    ->where('is_not_smart', false)
    ->get();

How can I find the dimensions of a matrix in Python?

The correct answer is the following:

import numpy 
numpy.shape(a)

Blurry text after using CSS transform: scale(); in Chrome

It will be difficult to solve with only css.

So I solved it with jquery.

This is my CSS.

.trY {
   top: 50%;
   transform: translateY(-50%);
}

.trX {
   left: 50%;
   transform: translateX(-50%);
}

.trXY {
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}

and this is my jquery.

function tr_init() {
$(".trY, .trX, .trXY").each(function () {
    if ($(this).outerWidth() % 2 != 0) {
        var fixed_width = Math.ceil($(this).outerWidth() / 2) * 2;
        $(this).css("width", fixed_width);
    }
    if ($(this).outerHeight() % 2 != 0) {
        var fixed_height = Math.ceil($(this).outerHeight() / 2) * 2;
        $(this).css("height", fixed_height);
    }
})}

Find all stored procedures that reference a specific column in some table

You can use the below query to identify the values. But please keep in mind that this will not give you the results from encrypted stored procedure.

SELECT DISTINCT OBJECT_NAME(comments.id) OBJECT_NAME
    ,objects.type_desc
FROM syscomments comments
    ,sys.objects objects
WHERE comments.id = objects.object_id
    AND TEXT LIKE '%CreatedDate%'
ORDER BY 1

Prolog "or" operator, query

you can 'invoke' alternative bindings on Y this way:

...registered(X, Y), (Y=ct101; Y=ct102; Y=ct103).

Note the parenthesis are required to keep the correct execution control flow. The ;/2 it's the general or operator. For your restricted use you could as well choice the more idiomatic

...registered(X, Y), member(Y, [ct101,ct102,ct103]).

that on backtracking binds Y to each member of the list.

edit I understood with a delay your last requirement. If you want that Y match all 3 values the or is inappropriate, use instead

...registered(X, ct101), registered(X, ct102), registered(X, ct103).

or the more compact

...findall(Y, registered(X, Y), L), sort(L, [ct101,ct102,ct103]).

findall/3 build the list in the very same order that registered/2 succeeds. Then I use sort to ensure the matching.

...setof(Y, registered(X, Y), [ct101,ct102,ct103]).

setof/3 also sorts the result list

Apache Cordova - uninstall globally

Try this for Windows:

    npm uninstall -g cordova

Try this for MAC:

    sudo npm uninstall -g cordova

You can also add Cordova like this:

  1. If You Want To install the previous version of Cordova through the Node Package Manager (npm):

    npm install -g [email protected]
    
  2. If You Want To install the latest version of Cordova:

    npm install -g cordova 
    

Enjoy!

How to filter a dictionary according to an arbitrary condition function?

dict((k, v) for (k, v) in points.iteritems() if v[0] < 5 and v[1] < 5)

How do I 'foreach' through a two-dimensional array?

UPDATE: I had some time on my hands, so ... I went ahead and fleshed out this idea. See below for the code.


Here's a bit of a crazy answer:

You could do what you're looking for -- essentially treat a two-dimensional array as a table with rows -- by writing a static method (perhaps an extension method) that takes a T[,] and returns an IEnumerable<T[]>. This would require copying each "row" of the underlying table into a new array, though.

A perhaps better (though more involved) approach would be to actually write a class that implements IList<T> as a wrapper around a single "row" of a two-dimensional array (you would probably set IsReadOnly to true and just implement the getter for the this[int] property and probably Count and GetEnumerator; everything else could throw a NotSupportedException). Then your static/extension method could return an IEnumerable<IList<T>> and provide deferred execution.

That way you could write code pretty much like what you have:

foreach (IList<string> row in table.GetRows()) // or something
{
    Console.WriteLine(row[0] + " " + row[1]);
}

Just a thought.


Implementation suggestion:

public static class ArrayTableHelper {
    public static IEnumerable<IList<T>> GetRows<T>(this T[,] table) {
        for (int i = 0; i < table.GetLength(0); ++i)
            yield return new ArrayTableRow<T>(table, i);
    }

    private class ArrayTableRow<T> : IList<T> {
        private readonly T[,] _table;
        private readonly int _count;
        private readonly int _rowIndex;

        public ArrayTableRow(T[,] table, int rowIndex) {
            if (table == null)
                throw new ArgumentNullException("table");

            if (rowIndex < 0 || rowIndex >= table.GetLength(0))
                throw new ArgumentOutOfRangeException("rowIndex");

            _table = table;
            _count = _table.GetLength(1);
            _rowIndex = rowIndex;
        }

        // I didn't implement the setter below,
        // but you easily COULD (and then set IsReadOnly to false?)
        public T this[int index] {
            get { return _table[_rowIndex, index]; }
            set { throw new NotImplementedException(); }
        }

        public int Count {
            get { return _count; }
        }

        bool ICollection<T>.IsReadOnly {
            get { return true; }
        }

        public IEnumerator<T> GetEnumerator() {
            for (int i = 0; i < _count; ++i)
                yield return this[i];
        }

        // omitted remaining IList<T> members for brevity;
        // you actually could implement IndexOf, Contains, etc.
        // quite easily, though
    }
}

...now I think I should give StackOverflow a break for the rest of the day ;)

The maximum value for an int type in Go

https://groups.google.com/group/golang-nuts/msg/71c307e4d73024ce?pli=1

The germane part:

Since integer types use two's complement arithmetic, you can infer the min/max constant values for int and uint. For example,

const MaxUint = ^uint(0) 
const MinUint = 0 
const MaxInt = int(MaxUint >> 1) 
const MinInt = -MaxInt - 1

As per @CarelZA's comment:

uint8  : 0 to 255 
uint16 : 0 to 65535 
uint32 : 0 to 4294967295 
uint64 : 0 to 18446744073709551615 
int8   : -128 to 127 
int16  : -32768 to 32767 
int32  : -2147483648 to 2147483647 
int64  : -9223372036854775808 to 9223372036854775807

How to remove unused imports from Eclipse

Not to reorganize imports (not to unfold .* and not to reorder lines) to have least VCS changeset
you can use custom eclipse clenup as this answer suggests

What is a stack trace, and how can I use it to debug my application errors?

To understand the name: A stack trace is a a list of Exceptions( or you can say a list of "Cause by"), from the most surface Exception(e.g. Service Layer Exception) to the deepest one (e.g. Database Exception). Just like the reason we call it 'stack' is because stack is First in Last out (FILO), the deepest exception was happened in the very beginning, then a chain of exception was generated a series of consequences, the surface Exception was the last one happened in time, but we see it in the first place.

Key 1:A tricky and important thing here need to be understand is : the deepest cause may not be the "root cause", because if you write some "bad code", it may cause some exception underneath which is deeper than its layer. For example, a bad sql query may cause SQLServerException connection reset in the bottem instead of syndax error, which may just in the middle of the stack.

-> Locate the root cause in the middle is your job. enter image description here

Key 2:Another tricky but important thing is inside each "Cause by" block, the first line was the deepest layer and happen first place for this block. For instance,

Exception in thread "main" java.lang.NullPointerException
        at com.example.myproject.Book.getTitle(Book.java:16)
           at com.example.myproject.Author.getBookTitles(Author.java:25)
               at com.example.myproject.Bootstrap.main(Bootstrap.java:14)

Book.java:16 was called by Auther.java:25 which was called by Bootstrap.java:14, Book.java:16 was the root cause. Here attach a diagram sort the trace stack in chronological order. enter image description here

What's an object file in C?

There are 3 kind of object files.

Relocatable object files

Contain machine code in a form that can be combined with other relocatable object files at link time, in order to form an executable object file.

If you have an a.c source file, to create its object file with GCC you should run: gcc a.c -c

The full process would be: preprocessor (cpp) would run over a.c. Its output (still source) will feed into the compiler (cc1). Its output (assembly) will feed into the assembler (as), which will produce the relocatable object file. That file contains object code and linking (and debugging if -g was used) metadata, and is not directly executable.

Shared object files

Special type of relocatable object file that can be loaded dynamically, either at load time, or at run time. Shared libraries are an example of these kinds of objects.

Executable object files

Contain machine code that can be directly loaded into memory (by the loader, e.g execve) and subsequently executed.

The result of running the linker over multiple relocatable object files is an executable object file. The linker merges all the input object files from the command line, from left-to-right, by merging all the same-type input sections (e.g. .data) to the same-type output section. It uses symbol resolution and relocation.

Bonus read:

When linking against a static library the functions that are referenced in the input objects are copied to the final executable. With dynamic libraries a symbol table is created instead that will enable a dynamic linking with the library's functions/globals. Thus, the result is a partially executable object file, as it depends on the library. If the library doesn't exist, the file can no longer execute).

The linking process can be done as follows: ld a.o -o myexecutable

The command: gcc a.c -o myexecutable will invoke all the commands mentioned at point 1 and at point 3 (cpp -> cc1 -> as -> ld1)

1: actually is collect2, which is a wrapper over ld.

Removing address bar from browser (to view on Android)

Finally I Try with this. Its worked for me..

  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ebook);

    //webview use to call own site
    webview =(WebView)findViewById(R.id.webView1);

    webview.setWebViewClient(new WebViewClient());       
    webview .getSettings().setJavaScriptEnabled(true);
    webview .getSettings().setDomStorageEnabled(true);     
    webview.loadUrl("http://www.google.com"); 
}

and your entire main.xml(res/layout) look should like this:

<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

don't go to add layouts.

How to add a Try/Catch to SQL Stored Procedure

Error-Handling with SQL Stored Procedures

TRY/CATCH error handling can take place either within or outside of a procedure (or both). The examples below demonstrate error handling in both cases.

If you want to experiment further, you can fork the query on Stack Exchange Data Explorer.

(This uses a temporary stored procedure... we can't create regular SP's on SEDE, but the functionality is the same.)

--our Stored Procedure
create procedure #myProc as --we can only create #temporary stored procedures on SEDE. 
  begin
    BEGIN TRY
      print 'This is our Stored Procedure.'
      print 1/0                          --<-- generate a "Divide By Zero" error.
      print 'We are not going to make it to this line.'
    END TRY

    BEGIN CATCH
      print 'This is the CATCH block within our Stored Procedure:'
          + ' Error Line #'+convert(varchar,ERROR_LINE())
          + ' of procedure '+isnull(ERROR_PROCEDURE(),'(Main)')
      --print 1/0                        --<-- generate another "Divide By Zero" error.
        -- uncomment the line above to cause error within the CATCH ¹ 
    END CATCH
  end
go

--our MAIN code block:
BEGIN TRY
  print 'This is our MAIN Procedure.'
  execute #myProc  --execute the Stored Procedure
      --print 1/0                        --<-- generate another "Divide By Zero" error.
        -- uncomment the line above to cause error within the MAIN Procedure ²
  print 'Now our MAIN sql code block continues.'
END TRY

BEGIN CATCH
  print 'This is the CATCH block for our MAIN sql code block:'
          + ' Error Line #'+convert(varchar,ERROR_LINE())
          + ' of procedure '+isnull(ERROR_PROCEDURE(),'(Main)')
END CATCH

Here's the result of running the above sql as-is:

This is our MAIN Procedure.
This is our Stored Procedure.
This is the CATCH block within our Stored Procedure: Error Line #5 of procedure #myProc
Now our MAIN sql code block continues.

¹ Uncommenting the "additional error line" from the Stored Procedure's CATCH block will produce:

This is our MAIN procedure.
This is our Stored Procedure.
This is the CATCH block within our Stored Procedure: Error Line #5 of procedure #myProc
This is the CATCH block for our MAIN sql code block: Error Line #13 of procedure #myProc

² Uncommenting the "additional error line" from the MAIN procedure will produce:

This is our MAIN Procedure.
This is our Stored Pprocedure.
This is the CATCH block within our Stored Procedure: Error Line #5 of procedure #myProc
This is the CATCH block for our MAIN sql code block: Error Line #4 of procedure (Main)

Use a single procedure for error handling

On topic of stored procedures and error handling, it can be helpful (and tidier) to use a single, dynamic, stored procedure to handle errors for multiple other procedures or code sections.

Here's an example:

--our error handling procedure
create procedure #myErrorHandling as
  begin
    print ' Error #'+convert(varchar,ERROR_NUMBER())+': '+ERROR_MESSAGE()  
    print ' occurred on line #'+convert(varchar,ERROR_LINE())
         +' of procedure '+isnull(ERROR_PROCEDURE(),'(Main)')
    if ERROR_PROCEDURE() is null       --check if error was in MAIN Procedure
      print '*Execution cannot continue after an error in the MAIN Procedure.'
  end
go

create procedure #myProc as     --our test Stored Procedure
  begin
    BEGIN TRY
      print 'This is our Stored Procedure.'
      print 1/0                       --generate a "Divide By Zero" error.
      print 'We will not make it to this line.'
    END TRY
    BEGIN CATCH
     execute #myErrorHandling
    END CATCH
  end
go

BEGIN TRY                       --our MAIN Procedure
  print 'This is our MAIN Procedure.'
  execute #myProc                     --execute the Stored Procedure
  print '*The error halted the procedure, but our MAIN code can continue.'
  print 1/0                           --generate another "Divide By Zero" error.
  print 'We will not make it to this line.'
END TRY
BEGIN CATCH
  execute #myErrorHandling
END CATCH

Example Output: (This query can be forked on SEDE here.)

This is our MAIN procedure.
This is our stored procedure.
 Error #8134: Divide by zero error encountered.
 occurred on line #5 of procedure #myProc
*The error halted the procedure, but our MAIN code can continue.
 Error #8134: Divide by zero error encountered.
 occurred on line #5 of procedure (Main)
*Execution cannot continue after an error in the MAIN procedure.

Documentation:

In the scope of a TRY/CATCH block, the following system functions can be used to obtain information about the error that caused the CATCH block to be executed:

  • ERROR_NUMBER() returns the number of the error.
  • ERROR_SEVERITY() returns the severity.
  • ERROR_STATE() returns the error state number.
  • ERROR_PROCEDURE() returns the name of the stored procedure or trigger where the error occurred.
  • ERROR_LINE() returns the line number inside the routine that caused the error.
  • ERROR_MESSAGE() returns the complete text of the error message. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times.

(Source)

Note that there are two types of SQL errors: Terminal and Catchable. TRY/CATCH will [obviously] only catch the "Catchable" errors. This is one of a number of ways of learning more about your SQL errors, but it probably the most useful.

It's "better to fail now" (during development) compared to later because, as Homer says . . .

Convert List<Object> to String[] in Java

Using Guava

List<Object> lst ...    
List<String> ls = Lists.transform(lst, Functions.toStringFunction());

Html table tr inside td

You can check this just use table inside table like this

_x000D_
_x000D_
<!DOCTYPE html>
<html>

<head>
  <style>
    table,
    th,
    td {
      border: 1px solid black;
      border-collapse: collapse;
    }
  </style>
</head>

<body>
  <table style="width:100%">
    <tr>
      <th>ABC</th>
      <th>ABC</th>
      <th>ABC</th>
      <th>ABC</th>
    </tr>
    <tr>
      <td>Item1</td>
      <td>Item1</td>
      <td>
        <table style="width:100%">
          <tr>
            <td>name1</td>
            <td>price1</td>
          </tr>
          <tr>
            <td>name2</td>
            <td>price2</td>
          </tr>
          <tr>
            <td>name3</td>
            <td>price3</td>
          </tr>
        </table>
      </td>
      <td>item1</td>
    </tr>
    <tr>
      <td>A</td>
      <td>B</td>
      <td>C</td>
      <td>D</td>
    </tr>
    <tr>
      <td>E</td>
      <td>F</td>
      <td>G</td>
      <td>H</td>
    </tr>
    <tr>
      <td>E</td>
      <td>R</td>
      <td>T</td>
      <td>T</td>
    </tr>
  </table>
</body>

</html>
_x000D_
_x000D_
_x000D_

List<object>.RemoveAll - How to create an appropriate Predicate

A predicate in T is a delegate that takes in a T and returns a bool. List<T>.RemoveAll will remove all elements in a list where calling the predicate returns true. The easiest way to supply a simple predicate is usually a lambda expression, but you can also use anonymous methods or actual methods.

{
    List<Vehicle> vehicles;
    // Using a lambda
    vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
    // Using an equivalent anonymous method
    vehicles.RemoveAll(delegate(Vehicle vehicle)
    {
        return vehicle.EnquiryID == 123;
    });
    // Using an equivalent actual method
    vehicles.RemoveAll(VehiclePredicate);
}

private static bool VehiclePredicate(Vehicle vehicle)
{
    return vehicle.EnquiryID == 123;
}

How to remove old Docker containers

I am suggesting you to stop the images first and then remove.

You could go like:

$ docker stop $(docker ps -a)
$ docker rm $(docker ps -a)

How to select last one week data from today's date

  1. The query is correct

2A. As far as last seven days have much less rows than whole table an index can help

2B. If you are interested only in Created_Date you can try using some group by and count, it should help with the result set size

In SQL, how can you "group by" in ranges?

create table scores (
   user_id int,
   score int
)

select t.range as [score range], count(*) as [number of occurences]
from (
      select user_id,
         case when score >= 0 and score < 10 then '0-9'
         case when score >= 10 and score < 20 then '10-19'
         ...
         else '90-99' as range
     from scores) t
group by t.range

Equivalent of Clean & build in Android Studio?

reed these links

http://tools.android.com/tech-docs/new-build-system/version-compatibility https://developer.android.com/studio/releases/gradle-plugin.html

in android studio version 2+, use this in gradle config

android{
..

compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
        incremental = false;
}
...

}

after 3 days of search and test :(, this solve "rebuild for any run"

How can I use Guzzle to send a POST request in JSON?

You can either using hardcoded json attribute as key, or you can conveniently using GuzzleHttp\RequestOptions::JSON constant.

Here is the example of using hardcoded json string.

use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('url', [
    'json' => ['foo' => 'bar']
]);

See Docs.

How do you iterate through every file/directory recursively in standard C++?

We are in 2019. We have filesystem standard library in C++. The Filesystem library provides facilities for performing operations on file systems and their components, such as paths, regular files, and directories.

There is an important note on this link if you are considering portability issues. It says:

The filesystem library facilities may be unavailable if a hierarchical file system is not accessible to the implementation, or if it does not provide the necessary capabilities. Some features may not be available if they are not supported by the underlying file system (e.g. the FAT filesystem lacks symbolic links and forbids multiple hardlinks). In those cases, errors must be reported.

The filesystem library was originally developed as boost.filesystem, was published as the technical specification ISO/IEC TS 18822:2015, and finally merged to ISO C++ as of C++17. The boost implementation is currently available on more compilers and platforms than the C++17 library.

@adi-shavit has answered this question when it was part of std::experimental and he has updated this answer in 2017. I want to give more details about the library and show more detailed example.

std::filesystem::recursive_directory_iterator is an LegacyInputIterator that iterates over the directory_entry elements of a directory, and, recursively, over the entries of all subdirectories. The iteration order is unspecified, except that each directory entry is visited only once.

If you don't want to recursively iterate over the entries of subdirectories, then directory_iterator should be used.

Both iterators returns an object of directory_entry. directory_entry has various useful member functions like is_regular_file, is_directory, is_socket, is_symlink etc. The path() member function returns an object of std::filesystem::path and it can be used to get file extension, filename, root name.

Consider the example below. I have been using Ubuntu and compiled it over the terminal using

g++ example.cpp --std=c++17 -lstdc++fs -Wall

#include <iostream>
#include <string>
#include <filesystem>

void listFiles(std::string path)
{
    for (auto& dirEntry: std::filesystem::recursive_directory_iterator(path)) {
        if (!dirEntry.is_regular_file()) {
            std::cout << "Directory: " << dirEntry.path() << std::endl;
            continue;
        }
        std::filesystem::path file = dirEntry.path();
        std::cout << "Filename: " << file.filename() << " extension: " << file.extension() << std::endl;

    }
}

int main()
{
    listFiles("./");
    return 0;
}

Count with IF condition in MySQL query

Better still (or shorter anyway):

SUM(ccc_news_comments.id = 'approved')

This works since the Boolean type in MySQL is represented as INT 0 and 1, just like in C. (May not be portable across DB systems though.)

As for COALESCE() as mentioned in other answers, many language APIs automatically convert NULL to '' when fetching the value. For example with PHP's mysqli interface it would be safe to run your query without COALESCE().

Changing java platform on which netbeans runs

For anyone on Mac OS X, you can find netbeans.conf here:

/Applications/NetBeans/NetBeans <version>.app/Contents/Resources/NetBeans/etc/netbeans.conf

In case anyone needs to know :)

How to resolve conflicts in EGit

An earlier process of resolving conflicts (through the staging view) in Eclipse seemed much more intuitive several years ago, so either the tooling no longer functions in the way that I was used to, or I am remembering the process of resolving merge conflicts within SVN repositories. Regardless, there was this nifty "Mark as Merged" menu option when right-clicking on a conflicting file.

Fast forward to 2019, I am using the "Git Staging" view in Eclipse (v4.11). Actually, I am using STS (Spring Tool Suite 3.9.8), but I think the Git Staging view is a standard Eclipse plugin for working with Java/Spring-based projects. I share the following approach in case it helps anyone else, and because I grow weary or resolving merge conflicts from the GIT command line. ;-)

Because the feature I recall is now gone (or perhaps done differently with the current version of GIT and Eclipse), here are the current steps that I now follow to resolve merge conflicts through Eclipse using a GIT repository. It seems the most intuitive to me. Obviously, it is clear from the number of responses here that there are many ways to resolve merge conflicts. Perhaps I just need to switch to JetBrains IntelliJ, with their three-way merge tool.

  1. Double-click on the offending file
  2. A "Text Compare" interface appears, with side-by-side views of the conflicting commits.
  3. Identify which view is the local state of the file, or the most recent commit.
  4. Make changes to the local window, either adding or redacting the changes from the offending commit.
  5. When the desired set of changes has been reviewed and updated, right-click on the unstaged file.
  6. Click the "Add to Index" option, and your file will be added to the staged changes.
  7. This also removes the conflicting file from the unstaged list, thus indicating that it has been "marked as merged"
  8. Continue this process with each additional file in conflict.
  9. When you have reivewed all conflicting files, confirm that all desired files (including additional changes) are staged.
  10. Add an appropriate commit message.
  11. Commit and push the "merged" files to the origin repository, and this officially marks your files as merged.

NOTE: Because the menu options are not intuitive, a number of things can be misleading. For example, if you have saved any updates locally, and try to reopen the conflicting file to confirmand that the changes you made have persisted, confusion may result since the original conflict state is opened... not your changes.

But once you add the file(s) to the index, you will see your changes there.

I also recommend that when you pull in changes that result in a merge conflict, that you "stash" your local changes first, and then pull the changes in again. At least with GIT, as a protection, you will not be allowed to pull in external changes until you either revert your changes or stash them. Discard and revert to the HEAD state if the changes are not important, but stash them otherwise.

Finally, if you have just one or two files changing, then consider pulling them into separate text files as a reference, then revert to the HEAD and then manually update the file(s) when you pull changes across.

syntax for creating a dictionary into another dictionary in python

You can declare a dictionary inside a dictionary by nesting the {} containers:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

And then you can access the elements using the [] syntax:

print d['dict1']           # {'foo': 1, 'bar': 2}
print d['dict1']['foo']    # 1
print d['dict2']['quux']   # 4

Given the above, if you want to add another dictionary to the dictionary, it can be done like so:

d['dict3'] = {'spam': 5, 'ham': 6}

or if you prefer to add items to the internal dictionary one by one:

d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8

How to find the socket buffer size of linux

If you want see your buffer size in terminal, you can take a look at:

  • /proc/sys/net/ipv4/tcp_rmem (for read)
  • /proc/sys/net/ipv4/tcp_wmem (for write)

They contain three numbers, which are minimum, default and maximum memory size values (in byte), respectively.

Streaming video from Android camera to server

Here is complete article about streaming android camera video to a webpage.

Android Streaming Live Camera Video to Web Page

  1. Used libstreaming on android app
  2. On server side Wowza Media Engine is used to decode the video stream
  3. Finally jWplayer is used to play the video on a webpage.

How can I import data into mysql database via mysql workbench?

  1. Open Connetion
  2. Select "Administration" tab
  3. Click on Data import

Upload sql file

enter image description here

Make sure to select your database in this award winning GUI:

enter image description here

pip install gives error: Unable to find vcvarsall.bat

If you are trying to install matplotlib in order to work with graphs on python. Try this link. https://github.com/jbmohler/matplotlib-winbuild. This is a set of scripts to build matplotlib from source on the MS Windows platform.

To build & install matplotlib in your Python, do:

git clone https://github.com/matplotlib/matplotlib
git clone https://github.com/jbmohler/matplotlib-winbuild
$ python matplotlib-winbuild\buildall.py

The build script will auto-detect Python version & 32/64 bit automatically.

PHP Fatal Error Failed opening required File

Just in case this helps anybody else out there, I stumbled on an obscure case for this error triggering last night. Specifically, I was using the require_once method and specifying only a filename and no path, since the file being required was present in the same directory.

I started to get the 'Failed opening required file' error at one point. After tearing my hair out for a while, I finally noticed a PHP Warning message immediately above the fatal error output, indicating 'failed to open stream: Permission denied', but more importantly, informing me of the path to the file it was trying to open. I then twigged to the fact I had created a copy of the file (with ownership not accessible to Apache) elsewhere that happened to also be in the PHP 'include' search path, and ahead of the folder where I wanted it to be picked up. D'oh!

"Unable to locate tools.jar" when running ant

The order of items in the PATH matters. If there are multiple entries for various java installations, the first one in your PATH will be used.

I have had similar issues after installing a product, like Oracle, that puts it's JRE at the beginning of the PATH.

Ensure that the JDK you want to be loaded is the first entry in your PATH (or at least that it appears before C:\Program Files\Java\jre6\bin appears).

ImportError: No module named PytQt5

this can be solved under MacOS X by installing pyqt with brew

brew install pyqt

How to solve munmap_chunk(): invalid pointer error in C++

The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

Copy file from source directory to binary directory using CMake

I would suggest TARGET_FILE_DIR if you want the file to be copied to the same folder as your .exe file.

$ Directory of main file (.exe, .so.1.2, .a).

add_custom_command(
  TARGET ${PROJECT_NAME} POST_BUILD
  COMMAND ${CMAKE_COMMAND} -E copy 
    ${CMAKE_CURRENT_SOURCE_DIR}/input.txt 
    $<TARGET_FILE_DIR:${PROJECT_NAME}>)

In VS, this cmake script will copy input.txt to the same file as your final exe, no matter it's debug or release.

Read a Csv file with powershell and capture corresponding data

Old topic, but never clearly answered. I've been working on similar as well, and found the solution:

The pipe (|) in this code sample from Austin isn't the delimiter, but to pipe the ForEach-Object, so if you want to use it as delimiter, you need to do this:

Import-Csv H:\Programs\scripts\SomeText.csv -delimiter "|" |`
ForEach-Object {
    $Name += $_.Name
    $Phone += $_."Phone Number"
}

Spent a good 15 minutes on this myself before I understood what was going on. Hope the answer helps the next person reading this avoid the wasted minutes! (Sorry for expanding on your comment Austin)

Submit form on pressing Enter with AngularJS

Just wanted to point out that in the case of having a hidden submit button, you can just use the ngShow directive and set it to false like so:

HTML

<form ng-submit="myFunc()">
    <input type="text" name="username">
    <input type="submit" value="submit" ng-show="false">
</form>

What does "use strict" do in JavaScript, and what is the reasoning behind it?

"use strict"; is the ECMA effort to make JavaScript a little bit more robust. It brings in JS an attempt to make it at least a little "strict" (other languages implement strict rules since the 90s). It actually "forces" JavaScript developers to follow some sort of coding best practices. Still, JavaScript is very fragile. There is no such thing as typed variables, typed methods, etc. I strongly recommend JavaScript developers to learn a more robust language such as Java or ActionScript3, and implement the same best practices in your JavaScript code, it will work better and be easier to debug.

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

Okay adding to @null's awesome post about using the Asset Catalog.

You may need to do the following to get the App's Icon linked and working for Ad-Hoc distributions / production to be seen in Organiser, Test flight and possibly unknown AppStore locations.


After creating the Asset Catalog, take note of the name of the Launch Images and App Icon names listed in the .xassets in Xcode.

By Default this should be

  • AppIcon
  • LaunchImage

[To see this click on your .xassets folder/icon in Xcode.] (this can be changed, so just take note of this variable for later)


What is created now each build is the following data structures in your .app:

For App Icons:

iPhone

  • AppIcon57x57.png (iPhone non retina) [Notice the Icon name prefix]
  • [email protected] (iPhone retina)

And the same format for each of the other icon resolutions.

iPad

  • AppIcon72x72~ipad.png (iPad non retina)
  • AppIcon72x72@2x~ipad.png (iPad retina)

(For iPad it is slightly different postfix)


Main Problem

Now I noticed that in my Info.plist in Xcode 5.0.1 it automatically attempted and failed to create a key for "Icon files (iOS 5)" after completing the creation of the Asset Catalog.

If it did create a reference successfully / this may have been patched by Apple or just worked, then all you have to do is review the image names to validate the format listed above.

Final Solution:

Add the following key to you main .plist

I suggest you open your main .plist with a external text editor such as TextWrangler rather than in Xcode to copy and paste the following key in.

<key>CFBundleIcons</key>
<dict>
    <key>CFBundlePrimaryIcon</key>
    <dict>
        <key>CFBundleIconFiles</key>
        <array>
            <string>AppIcon57x57.png</string>
            <string>[email protected]</string>
            <string>AppIcon72x72~ipad.png</string>
            <string>AppIcon72x72@2x~ipad.png</string>
        </array>
    </dict>
</dict>

Please Note I have only included my example resolutions, you will need to add them all.


If you want to add this Key in Xcode without an external editor, Use the following:

  • Icon files (iOS 5) - Dictionary
  • Primary Icon - Dictionary
  • Icon files - Array
  • Item 0 - String = AppIcon57x57.png And for each other item / app icon.

Now when you finally archive your project the final .xcarchive payload .plist will now include the above stated icon locations to build and use.

Do not add the following to any .plist: Just an example of what Xcode will now generate for your final payload

<key>IconPaths</key>
<array>
    <string>Applications/Example.app/AppIcon57x57.png</string>
    <string>Applications/Example.app/[email protected]</string>
    <string>Applications/Example.app/AppIcon72x72~ipad.png</string>
    <string>Applications/Example.app/AppIcon72x72@2x~ipad.png</string>
</array>

How to run vbs as administrator from vbs?

fun lil batch file

@set E=ECHO &set S=SET &set CS=CScript //T:3 //nologo %~n0.vbs /REALTIME^>nul^& timeout 1 /NOBREAK^>nul^& del /Q %~n0.vbs&CLS
@%E%off&color 4a&title %~n0&%S%CX=CLS^&EXIT&%S%BS=^>%~n0.vbs&%S%G=GOTO &%S%H=shell&AT>NUL
IF %ERRORLEVEL% EQU 0 (
    %G%2
) ELSE (
    if not "%minimized%"=="" %G%1
)
%S%minimized=true & start /min cmd /C "%~dpnx0"&%CX%
:1
%E%%S%%H%=CreateObject("%H%.Application"):%H%.%H%Execute "%~dpnx0",,"%CD%", "runas", 1:%S%%H%=nothing%BS%&%CS%&%CX%
:2
%E%%~dpnx0 fvcLing admin mode look up&wmic process where name="cmd.exe" CALL setpriority "realtime"& timeout 3 /NOBREAK>nul
:3
%E%x=msgbox("end of line" ,48, "%~n0")%BS%&%CS%&%CX%

Add ArrayList to another ArrayList in java

The problem you have is caused that you use the same ArrayList NodeList over all iterations in main for loop. Each iterations NodeList is enlarged by new elements.

  1. After first loop, NodeList has 5 elements (PropertyStart,a,b,c,PropertyEnd) and list has 1 element (NodeList: (PropertyStart,a,b,c,PropertyEnd))

  2. After second loop NodeList has 10 elements (PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd) and list has 2 elements (NodeList (with 10 elements), NodeList (with 10 elements))

To get you expectations you must replace

NodeList.addAll(nodes);
list.add(NodeList)

by

List childrenList = new ArrayList(nodes);
list.add(childrenList);

PS. Your code is not readable, keep Java code conventions to have readble code. For example is hard to recognize if NodeList is a class or object

Download multiple files with a single action

When using Ajax components it is possible to start multiple downloads. Therefore you have to use https://cwiki.apache.org/confluence/display/WICKET/AJAX+update+and+file+download+in+one+blow

Add an instance of AJAXDownload to your Page or whatever. Create an AjaxButton and override onSubmit. Create an AbstractAjaxTimerBehavior and start downloading.

        button = new AjaxButton("button2") {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form)
        {
            MultiSitePage.this.info(this);
            target.add(form);

            form.add(new AbstractAjaxTimerBehavior(Duration.milliseconds(1)) {

                @Override
                protected void onTimer(AjaxRequestTarget target) {
                    download.initiate(target);
                }

            });     
        }

Happy downloading!

Bootstrap 4 card-deck with number of columns based on viewport

I got this to work by adding a min-width to the cards:

<div class="card mb-3" style="min-width: 18rem;">
  <p>Card content</p>
</div>

The cards don't go below this width, but still properly fill each row and have equal heights.

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Your syntax is pretty screwy.

Change this:

input:not(disabled)not:[type="submit"]:focus{

to:

input:not(:disabled):not([type="submit"]):focus{

Seems that many people don't realize :enabled and :disabled are valid CSS selectors...

JQuery find first parent element with specific class prefix

Jquery later allowed you to to find the parents with the .parents() method.

Hence I recommend using:

var $div = $('#divid').parents('div[class^="div-a"]');

This gives all parent nodes matching the selector. To get the first parent matching the selector use:

var $div = $('#divid').parents('div[class^="div-a"]').eq(0);

For other such DOM traversal queries, check out the documentation on traversing the DOM.

Assert that a WebElement is not present using Selenium WebDriver with java

Not an answer to the very question but perhaps an idea for the underlying task:

When your site logic should not show a certain element, you could insert an invisible "flag" element that you check for.

if condition
    renderElement()
else
    renderElementNotShownFlag() // used by Selenium test

Turning off hibernate logging console output

Important notice: the property (part of hibernate configuration, NOT part of logging framework config!)

hibernate.show_sql

controls the logging directly to STDOUT bypassing any logging framework (which you can recognize by the missing output formatting of the messages). If you use a logging framework like log4j, you should always set that property to false because it gives you no benefit at all.

That circumstance irritated me quite a long time because I never really cared about it until I tried to write some benchmark regarding Hibernate.

jquery - is not a function error

This problem is "best" solved by using an anonymous function to pass-in the jQuery object thusly:

The Anonymous Function Looks Like:

<script type="text/javascript">
    (function($) {
        // You pass-in jQuery and then alias it with the $-sign
        // So your internal code doesn't change
    })(jQuery);
</script>

This is JavaScript's method of implementing (poor man's) 'Dependency Injection' when used alongside things like the 'Module Pattern'.

So Your Code Would Look Like:
Of course, you might want to make some changes to your internal code now, but you get the idea.

<script type="text/javascript">
    (function($) {
        $.fn.pluginbutton = function(options) {
            myoptions = $.extend({ left: true });
            return this.each(function() {
                var focus = false;
                if (focus === false) {
                    this.hover(function() {
                        this.animate({ backgroundPosition: "0 -30px" }, { duration: 0 });
                        this.removeClass('VBfocus').addClass('VBHover');
                    }, function() {
                        this.animate({ backgroundPosition: "0 0" }, { duration: 0 });
                        this.removeClass('VBfocus').removeClass('VBHover');
                    });
                }
                this.mousedown(function() {
                    focus = true
                    this.animate({ backgroundPosition: "0 30px" }, { duration: 0 });
                    this.addClass('VBfocus').removeClass('VBHover');
                }, function() {
                    focus = false;
                    this.animate({ backgroundPosition: "0 0" }, { duration: 0 });
                    this.removeClass('VBfocus').addClass('VBHover');
                });
            });
        }
    })(jQuery);
</script>

How do I select an element with its name attribute in jQuery?

jQuery("[name='test']") 

Although you should avoid it and if possible select by ID (e.g. #myId) as this has better performance because it invokes the native getElementById.

How can I filter a date of a DateTimeField in Django?

Here is an interesting technique-- I leveraged the startswith procedure as implemented with Django on MySQL to achieve the result of only looking up a datetime through only the date. Basically, when Django does the lookup in the database it has to do a string conversion for the DATETIME MySQL storage object, so you can filter on that, leaving out the timestamp portion of the date-- that way %LIKE% matches only the date object and you'll get every timestamp for the given date.

datetime_filter = datetime(2009, 8, 22) 
MyObject.objects.filter(datetime_attr__startswith=datetime_filter.date())

This will perform the following query:

SELECT (values) FROM myapp_my_object \ 
WHERE myapp_my_object.datetime_attr LIKE BINARY 2009-08-22%

The LIKE BINARY in this case will match everything for the date, no matter the timestamp. Including values like:

+---------------------+
| datetime_attr       |
+---------------------+
| 2009-08-22 11:05:08 |
+---------------------+

Hopefully this helps everyone until Django comes out with a solution!

How to replace negative numbers in Pandas Data Frame by zero

Perhaps you could use pandas.where(args) like so:

data_frame = data_frame.where(data_frame < 0, 0)

clear form values after submission ajax

use this:

$('form.contactForm input[type="text"],texatrea, select').val('');

or if you have a reference to the form with this:

$('input[type="text"],texatrea, select', this).val('');

:input === <input> + <select>s + <textarea>s

Exit codes in Python

For the record, you can use POSIX standard exit codes defined here.

Example:

import sys, os

try:
    config()
except:
    sys.exit(os.EX_CONFIG) 
try:
    do_stuff()
except:
    sys.exit(os.EX_SOFTWARE)
sys.exit(os.EX_OK) # code 0, all ok

How to view transaction logs in SQL Server 2008

You can't read the transaction log file easily because that's not properly documented. There are basically two ways to do this. Using undocumented or semi-documented database functions or using third-party tools.

Note: This only makes sense if your database is in full recovery mode.

SQL Functions:

DBCC LOG and fn_dblog - more details here and here.

Third-party tools:

Toad for SQL Server and ApexSQL Log.

You can also check out several other topics where this was discussed:

Can't find @Nullable inside javax.annotation.*

In case someone has this while trying to compile an Android project, there is an alternative Nullable implementation in android.support.annotation.Nullable. So take care which package you've referenced in your imports.

Chrome / Safari not filling 100% height of flex parent

Solution

Use nested flex containers.

Get rid of percentage heights. Get rid of table properties. Get rid of vertical-align. Avoid absolute positioning. Just stick with flexbox all the way through.

Apply display: flex to the flex item (.item), making it a flex container. This automatically sets align-items: stretch, which tells the child (.item-inner) to expand the full height of the parent.

Important: Remove specified heights from flex items for this method to work. If a child has a height specified (e.g. height: 100%), then it will ignore the align-items: stretch coming from the parent. For the stretch default to work, the child's height must compute to auto (full explanation).

Try this (no changes to HTML):

_x000D_
_x000D_
.container {_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    height: 20em;_x000D_
    border: 5px solid black_x000D_
}_x000D_
_x000D_
.item {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;_x000D_
    border-bottom: 1px solid white;_x000D_
}_x000D_
_x000D_
.item-inner {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;                            /* new */_x000D_
_x000D_
    /* height: 100%;                    <-- remove; unnecessary */_x000D_
    /* width: 100%;                     <-- remove; unnecessary */_x000D_
    /* display: table;                  <-- remove; unnecessary */  _x000D_
}_x000D_
_x000D_
a {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;                            /* new */_x000D_
    align-items: center;                /* new; vertically center text */_x000D_
    background: orange;_x000D_
_x000D_
    /* display: table-cell;             <-- remove; unnecessary */_x000D_
    /* vertical-align: middle;          <-- remove; unnecessary */_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle demo


Explanation

My problem is that .item-inner { height: 100% } is not working in webkit (Chrome).

It's not working because you're using percentage height in a way that doesn't conform with the traditional implementation of the spec.

10.5 Content height: the height property

percentage
Specifies a percentage height. The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly and this element is not absolutely positioned, the value computes to auto.

auto
The height depends on the values of other properties.

In other words, for percentage height to work on an in-flow child, the parent must have a set height.

In your code, the top-level container has a defined height: .container { height: 20em; }

The third-level container has a defined height: .item-inner { height: 100%; }

But between them, the second-level container – .itemdoes not have a defined height. Webkit sees that as a missing link.

.item-inner is telling Chrome: give me height: 100%. Chrome looks to the parent (.item) for reference and responds: 100% of what? I don't see anything (ignoring the flex: 1 rule that is there). As a result, it applies height: auto (content height), in accordance with the spec.

Firefox, on the other hand, now accepts a parent's flex height as a reference for the child's percentage height. IE11 and Edge accept flex heights, as well.

Also, Chrome will accept flex-grow as an adequate parent reference if used in conjunction with flex-basis (any numerical value works (auto won't), including flex-basis: 0). As of this writing, however, this solution fails in Safari.

_x000D_
_x000D_
#outer {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 300px;_x000D_
  background-color: white;_x000D_
  border: 1px solid red;_x000D_
}_x000D_
#middle {_x000D_
  flex-grow: 1;_x000D_
  flex-basis: 1px;_x000D_
  background-color: yellow;_x000D_
}_x000D_
#inner {_x000D_
  height: 100%;_x000D_
  background-color: lightgreen;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="middle">_x000D_
    <div id="inner">_x000D_
      INNER_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Four Solutions

1. Specify a height on all parent elements

A reliable cross-browser solution is to specify a height on all parent elements. This prevents missing links, which Webkit-based browsers consider a violation of the spec.

Note that min-height and max-height are not acceptable. It must be the height property.

More details here: Working with the CSS height property and percentage values

2. CSS Relative & Absolute Positioning

Apply position: relative to the parent and position: absolute to the child.

Size the child with height: 100% and width: 100%, or use the offset properties: top: 0, right: 0, bottom: 0, left: 0.

With absolute positioning, percentage height works without a specified height on the parent.

3. Remove unnecessary HTML containers (recommended)

Is there a need for two containers around button? Why not remove .item or .item-inner, or both? Although button elements sometimes fail as flex containers, they can be flex items. Consider making button a child of .container or .item, and removing gratuitous mark-up.

Here's an example:

_x000D_
_x000D_
.container {_x000D_
    height: 20em;_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    border: 5px solid black_x000D_
}_x000D_
_x000D_
a {_x000D_
    flex: 1;_x000D_
    background: orange;_x000D_
    border-bottom: 1px solid white;_x000D_
    display: flex;                   /* nested flex container (for aligning text) */_x000D_
    align-items: center;             /* center text vertically */_x000D_
    justify-content: center;         /* center text horizontally */_x000D_
}
_x000D_
<div class="container">_x000D_
    <a>Button</a>_x000D_
    <a>Button</a>_x000D_
    <a>Button</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

4. Nested Flex Containers (recommended)

Get rid of percentage heights. Get rid of table properties. Get rid of vertical-align. Avoid absolute positioning. Just stick with flexbox all the way through.

Apply display: flex to the flex item (.item), making it a flex container. This automatically sets align-items: stretch, which tells the child (.item-inner) to expand the full height of the parent.

Important: Remove specified heights from flex items for this method to work. If a child has a height specified (e.g. height: 100%), then it will ignore the align-items: stretch coming from the parent. For the stretch default to work, the child's height must compute to auto (full explanation).

Try this (no changes to HTML):

_x000D_
_x000D_
.container {_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    height: 20em;_x000D_
    border: 5px solid black_x000D_
}_x000D_
_x000D_
.item {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;_x000D_
    border-bottom: 1px solid white;_x000D_
}_x000D_
_x000D_
.item-inner {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;                            /* new */_x000D_
_x000D_
    /* height: 100%;                    <-- remove; unnecessary */_x000D_
    /* width: 100%;                     <-- remove; unnecessary */_x000D_
    /* display: table;                  <-- remove; unnecessary */  _x000D_
}_x000D_
_x000D_
a {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;                            /* new */_x000D_
    align-items: center;                /* new; vertically center text */_x000D_
    background: orange;_x000D_
_x000D_
    /* display: table-cell;             <-- remove; unnecessary */_x000D_
    /* vertical-align: middle;          <-- remove; unnecessary */_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle

ERROR 2006 (HY000): MySQL server has gone away

If you are on Mac and installed mysql through brew like me, the following worked.

  1. cp $(brew --prefix mysql)/support-files/my-default.cnf /usr/local/etc/my.cnf

Source: For homebrew mysql installs, where's my.cnf?

  1. add max_allowed_packet=1073741824 to /usr/local/etc/my.cnf

  2. mysql.server restart

InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately

If you are not able to upgrade your Python version to 2.7.9, and want to suppress warnings,

you can downgrade your 'requests' version to 2.5.3:

pip install requests==2.5.3

Bugfix disclosure / Warning introduced in 2.6.0

Move a view up only when the keyboard covers an input field

Swift: You can do this by checking which textField is being presented.

@objc func keyboardWillShow(notification: NSNotification) {
    if self.textField.isFirstResponder == true {
        self.view.frame.origin.y -= 150
     }
}

@objc func keyboardWillHide(notification: NSNotification){
    if self.textField.isFirstResponder == true {
       self.view.frame.origin.y += 150
    }
}

How do I send an HTML Form in an Email .. not just MAILTO

I actually use ASP C# to send my emails now, with something that looks like :

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Form.Count > 0)
    {
        string formEmail = "";
        string fromEmail = "[email protected]";
        string defaultEmail = "[email protected]";

        string sendTo1 = "";

        int x = 0;

        for (int i = 0; i < Request.Form.Keys.Count; i++)
        {
            formEmail += "<strong>" + Request.Form.Keys[i] + "</strong>";
            formEmail += ": " + Request.Form[i] + "<br/>";
            if (Request.Form.Keys[i] == "Email")
            {
                if (Request.Form[i].ToString() != string.Empty)
                {
                    fromEmail = Request.Form[i].ToString();
                }
                formEmail += "<br/>";
            }

        }
        System.Net.Mail.MailMessage myMsg = new System.Net.Mail.MailMessage();
        SmtpClient smtpClient = new SmtpClient();

        try
        {
            myMsg.To.Add(new System.Net.Mail.MailAddress(defaultEmail));
            myMsg.IsBodyHtml = true;
            myMsg.Body = formEmail;
            myMsg.From = new System.Net.Mail.MailAddress(fromEmail);
            myMsg.Subject = "Sent using Gmail Smtp";
            smtpClient.Host = "smtp.gmail.com";
            smtpClient.Port = 587;
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = true;
            smtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "pward");

            smtpClient.Send(defaultEmail, sendTo1, "Sent using gmail smpt", formEmail);

        }
        catch (Exception ee)
        {
            debug.Text += ee.Message;
        }
    }
}

This is an example using gmail as the smtp mail sender. Some of what is in here isn't needed, but it is how I use it, as I am sure there are more effective ways in the same fashion.

NuGet Package Restore Not Working

Just for others that might run into this problem, I was able to resolve the issue by closing Visual Studio and reopening the project. When the project was loaded the packages were restored during the initialization phase.

How do I download and save a file locally on iOS using objective C?

I'm not sure what wget is, but to get a file from the web and store it locally, you can use NSData:

NSString *stringURL = @"http://www.somewhere.com/thefile.png";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
  NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString  *documentsDirectory = [paths objectAtIndex:0];  

  NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
  [urlData writeToFile:filePath atomically:YES];
}

Git error: "Host Key Verification Failed" when connecting to remote repository

For me, I just had to type "yes" at the prompt which asks "Are you sure you want to continue connecting (yes/no)?" rather than just pressing Enter.

Can two Java methods have same name with different return types?

According the JLS, you cannot however due to a feature/bug in the Java 6/7 compiler (Oracle's JDK, OpenJDK, IBM's JDK) you can have different return types for the same method signature if you use generics.

public class Main {
    public static void main(String... args) {
        Main.<Integer>print();
        Main.<Short>print();
        Main.<Byte>print();
        Main.<Void>print();
    }

    public static <T extends Integer> int print() {
        System.out.println("here - Integer");
        return 0;
    }
    public static <T extends Short> short print() {
        System.out.println("here - Short");
        return 0;
    }
    public static <T extends Byte> byte print() {
        System.out.println("here - Byte");
        return 0;
    }
    public static <T extends Void> void print() {
        System.out.println("here - Void");
    }
}

Prints

here - Integer
here - Short
here - Byte
here - Void

For more details, read my article here

How can I capture the result of var_dump to a string?

You could also do this:

$dump = print_r($variable, true);

LEFT JOIN in LINQ to entities?

May be I come later to answer but right now I'm facing with this... if helps there are one more solution (the way i solved it).

    var query2 = (
    from users in Repo.T_Benutzer
    join mappings in Repo.T_Benutzer_Benutzergruppen on mappings.BEBG_BE equals users.BE_ID into tmpMapp
    join groups in Repo.T_Benutzergruppen on groups.ID equals mappings.BEBG_BG into tmpGroups
    from mappings in tmpMapp.DefaultIfEmpty()
    from groups in tmpGroups.DefaultIfEmpty()
    select new
    {
         UserId = users.BE_ID
        ,UserName = users.BE_User
        ,UserGroupId = mappings.BEBG_BG
        ,GroupName = groups.Name
    }

);

By the way, I tried using the Stefan Steiger code which also helps but it was slower as hell.

What's the "Content-Length" field in HTTP header?

The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

Content-Length = "Content-Length" ":" 1*DIGIT

An example is

Content-Length: 1024

Applications SHOULD use this field to indicate the transfer-length of the message-body.

In PHP you would use something like this.

header("Content-Length: ".filesize($filename));

In case of "Content-Type: application/x-www-form-urlencoded" the encoded data is sent to the processing agent designated so you can set the length or size of the data you are going to post.

How to check if a variable is null or empty string or all whitespace in JavaScript?

You can use if(addr && (addr = $.trim(addr)))

This has the advantage of actually removing any outer whitespace from addr instead of just ignoring it when performing the check.

Reference: http://api.jquery.com/jQuery.trim/

Causes of getting a java.lang.VerifyError

I was getting this problem due to pack200 mangling a class file. A bit of searching turned this java bug up. Basically, setting --effort=4 caused the problem to go away.

Using java 1.5.0_17 (though it cropped up in every single variant of java 1.5 I tried it in).

UIScrollView Scrollable Content Size Ambiguity

I made a video on youTube
Scroll StackViews using only Storyboard in Xcode

I think 2 kind of scenarios can appear here.

The view inside the scrollView -

  1. does not have any intrinsic content Size (e.g UIView)
  2. does have its own intrinsic content Size (e.g UIStackView)

For a vertically scrollable view in both cases you need to add these constraints:

  1. 4 constraints from top, left, bottom and right.

  2. Equal width to scrollview (to stop scrolling horizontally)

You don't need any other constraints for views which have his own intrinsic content height.

enter image description here


For views which do not have any intrinsic content height, you need to add a height constraint. The view will scroll only if the height constraint is more than the height of the scrollView.

enter image description here

Get decimal portion of a number with JavaScript

float a=3.2;
int b=(int)a; // you'll get output b=3 here;
int c=(int)a-b; // you'll get c=.2 value here

How do I use jQuery to redirect?

Via Jquery:

$(location).attr('href','http://example.com/Registration/Success/');

How can I get the number of records affected by a stored procedure?

Register an out parameter for the stored procedure, and set the value based on @@ROWCOUNT if using SQL Server. Use SQL%ROWCOUNT if you are using Oracle.

Mind that if you have multiple INSERT/UPDATE/DELETE, you'll need a variable to store the result from @@ROWCOUNT for each operation.

Remove ALL styling/formatting from hyperlinks

if you state a.redLink{color:red;} then to keep this on hover and such add a.redLink:hover{color:red;} This will make sure no other hover states will change the color of your links

Normalize data in pandas

In [92]: df
Out[92]:
           a         b          c         d
A  -0.488816  0.863769   4.325608 -4.721202
B -11.937097  2.993993 -12.916784 -1.086236
C  -5.569493  4.672679  -2.168464 -9.315900
D   8.892368  0.932785   4.535396  0.598124

In [93]: df_norm = (df - df.mean()) / (df.max() - df.min())

In [94]: df_norm
Out[94]:
          a         b         c         d
A  0.085789 -0.394348  0.337016 -0.109935
B -0.463830  0.164926 -0.650963  0.256714
C -0.158129  0.605652 -0.035090 -0.573389
D  0.536170 -0.376229  0.349037  0.426611

In [95]: df_norm.mean()
Out[95]:
a   -2.081668e-17
b    4.857226e-17
c    1.734723e-17
d   -1.040834e-17

In [96]: df_norm.max() - df_norm.min()
Out[96]:
a    1
b    1
c    1
d    1

Get month and year from a datetime in SQL Server 2005

The question is about SQL Server 2005, many of the answers here are for later version SQL Server.

select convert (varchar(7), getdate(),20)
--Typical output 2015-04

SQL Server 2005 does not have date function which was introduced in SQL Server 2008

Things possible in IntelliJ that aren't possible in Eclipse?

The IntelliJ debugger has a very handy feature called "Evaluate Expression", that is by far better than eclipses pendant. It has full code-completion and i concider it to be generally "more useful".

How do I get my page title to have an icon?

this is an interesting question so let check it if you have a image for use as a website-icon then

Add this to your script

   <link rel="icon" type="image/gif" href="animated_favicon1.gif" />

otherwise if you have a icon for your website icon then you chose

 <link rel="shortcut icon" href="favicon.ico" />

I always use http://www.iconspedia.com/ for more icons

if my answer solved your problem then give me vote ok

How to trigger the onclick event of a marker on a Google Maps V3?

I've found out the solution! Thanks to Firebug ;)

//"markers" is an array that I declared which contains all the marker of the map
//"i" is the index of the marker in the array that I want to trigger the OnClick event

//V2 version is:
GEvent.trigger(markers[i], 'click');

//V3 version is:
google.maps.event.trigger(markers[i], 'click');

How to do a PUT request with curl?

curl -X PUT -d 'new_value' URL_PATH/key

where,

X - option to be used for request command

d - option to be used in order to put data on remote url

URL_PATH - remote url

new_value - value which we want to put to the server's key

Creating an empty file in C#

File.WriteAllText("path", String.Empty);

or

File.CreateText("path").Close();

App.Config Transformation for projects which are not Web Projects in Visual Studio?

I have created another alternative to the one posted by Vishal Joshi where the requirement to change the build action to Content is removed and also implemented basic support for ClickOnce deployment. I say basic, because I didn't test it thoroughly but it should work in the typical ClickOnce deployment scenario.

The solution consists of a single MSBuild project that once imported to an existent windows application project (*.csproj) extends the build process to contemplate app.config transformation.

You can read a more detailed explanation at Visual Studio App.config XML Transformation and the MSBuild project file can be downloaded from GitHub.

How to change Named Range Scope

This still needs more refining however works with all simple references, without killing existing local names.

Type GlobalNamesToLocalNames_Type
   Name As String
   Sheet As String
   Ref As String
End Type

Sub GlobalNamesToLocalNames(Optional Void As Variant)
   Dim List() As GlobalNamesToLocalNames_Type
   Dim Count As Long
   Dim Name As Name
   Dim Dat() As String
   Dim X As Long

   ' count the size
   For Each Name In ActiveWorkbook.Names
      Count = Count + 1
   Next
   ReDim List(Count - 1)
   Count = 0

   ' Collecect all name data
   For Each Name In ActiveWorkbook.Names
      With List(Count)
         ' Pick up only the name
         If InStr(Name.Name, "!") > 0 Then
            Dat = Split(Name.Name, "!")
            .Name = Dat(1)
         Else
            .Name = Name.Name
         End If
         ' pick up the sheet and refer
         Dat = Split(Name.RefersTo, "!")
         .Sheet = Mid(Dat(0), 2)
         .Ref = Dat(1)
         ' make local sheet name
         .Name = .Sheet & "!" & .Name
      End With
      Count = Count + 1
   Next

   ' Delete all names
   For Each Name In ActiveWorkbook.Names
      Name.Delete
   Next

   'rebuild all the names
   For X = 0 To Count - 1
      With List(X)
         If Left(.Ref, 1) <> "#" Then
            ActiveWorkbook.Names.Add Name:=.Name, RefersToLocal:="=" & .Sheet & "!" & .Ref
         End If
      End With
   Next
End Sub

MessageBox Buttons?

  1. Your call to MessageBox.Show needs to pass MessageBoxButtons.YesNo to get the Yes/No buttons instead of the OK button.

  2. Compare the result of that call (which will block execution until the dialog returns) to DialogResult.Yes....

if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
    // user clicked yes
}
else
{
    // user clicked no
}

How should you diagnose the error SEHException - External component has thrown an exception

I got this error while running unit tests on inmemory caching I was setting up. It flooded the cache. After invalidating the cache and restarting the VM, it worked fine.

Select first and last row from grouped data

A different base R alternative would be to first order by id and stopSequence, split them based on id and for every id we select only the first and last index and subset the dataframe using those indices.

df[sapply(with(df, split(order(id, stopSequence), id)), function(x) 
                   c(x[1], x[length(x)])), ]


#  id stopId stopSequence
#1  1      a            1
#3  1      c            3
#5  2      b            1
#6  2      c            4
#8  3      b            1
#7  3      a            3

Or similar using by

df[unlist(with(df, by(order(id, stopSequence), id, function(x) 
                   c(x[1], x[length(x)])))), ]

Check that a input to UITextField is numeric only

   #import "NSString+Extension.h"

//@interface NSString (Extension)
//
//- (BOOL) isAnEmail;
//- (BOOL) isNumeric;
//
//@end

@implementation NSString (Extension)
 - (BOOL) isNumeric
    {
        NSString *emailRegex = @"[0-9]+";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

        return [emailTest evaluateWithObject:self];

    //    NSString *localDecimalSymbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];
    //    NSMutableCharacterSet *decimalCharacterSet = [NSMutableCharacterSet characterSetWithCharactersInString:localDecimalSymbol];
    //    [decimalCharacterSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
    //    
    //    NSCharacterSet* nonNumbers = [decimalCharacterSet invertedSet];
    //    NSRange r = [self rangeOfCharacterFromSet: nonNumbers];
    //    
    //    if (r.location == NSNotFound)
    //    {
    //        // check to see how many times the decimal symbol appears in the string. It should only appear once for the number to be numeric.
    //        int numberOfOccurances = [[self componentsSeparatedByString:localDecimalSymbol] count]-1;
    //        return (numberOfOccurances > 1) ? NO : YES;
    //    }
    //    else return NO;
    }

"Multiple definition", "first defined here" errors

Maybe you included the .c file in makefile multiple times.

Android adding simple animations while setvisibility(view.Gone)

Based on the answer of @Xaver Kapeller I figured out a way to create scroll animation when new views appear on the screen (and also animation to hide them).

It goes from this state:

  • Button
  • Last Button

to

  • Button
  • Button 1
  • Button 2
  • Button 3
  • Button 4
  • Last Button

and viceversa.

So, when the user clicks on the first button, the elements "Button 1", "Button 2", "Button 3" and "Button 4" will appear using fade animation and the element "Last Button" will move down till end. The height of the layout will change as well, allowing using scroll view properly.

This is the code to show elements with animation:

private void showElements() {
    // Precondition
    if (areElementsVisible()) {
        Log.w(TAG, "The view is already visible. Nothing to do here");
        return;
    }

    // Animate the hidden linear layout as visible and set
    // the alpha as 0.0. Otherwise the animation won't be shown
    mHiddenLinearLayout.setVisibility(View.VISIBLE);
    mHiddenLinearLayout.setAlpha(0.0f);
    mHiddenLinearLayout
            .animate()
            .setDuration(ANIMATION_TRANSITION_TIME)
            .alpha(1.0f)
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    updateShowElementsButton();
                    mHiddenLinearLayout.animate().setListener(null);
                }
            })
    ;

    mLastButton
            .animate()
            .setDuration(ANIMATION_TRANSITION_TIME)
            .translationY(mHiddenLinearLayoutHeight);

    // Update the high of all the elements relativeLayout
    LayoutParams layoutParams = mAllElementsRelativeLayout.getLayoutParams();

    // TODO: Add vertical margins
    layoutParams.height = mLastButton.getHeight() + mHiddenLinearLayoutHeight;
}

and this is the code to hide elements of the animation:

private void hideElements() {
    // Precondition
    if (!areElementsVisible()) {
        Log.w(TAG, "The view is already non-visible. Nothing to do here");
        return;
    }

    // Animate the hidden linear layout as visible and set
    mHiddenLinearLayout
            .animate()
            .setDuration(ANIMATION_TRANSITION_TIME)
            .alpha(0.0f)
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    Log.v(TAG, "Animation ended. Set the view as gone");
                    super.onAnimationEnd(animation);
                    mHiddenLinearLayout.setVisibility(View.GONE);
                    // Hack: Remove the listener. So it won't be executed when
                    // any other animation on this view is executed
                    mHiddenLinearLayout.animate().setListener(null);
                    updateShowElementsButton();
                }
            })
    ;

    mLastButton
            .animate()
            .setDuration(ANIMATION_TRANSITION_TIME)
            .translationY(0);

    // Update the high of all the elements relativeLayout
    LayoutParams layoutParams = mAllElementsRelativeLayout.getLayoutParams();

    // TODO: Add vertical margins
    layoutParams.height = mLastButton.getHeight();
}

Note there is a simple hack on the method to hide the animation. On the animation listener mHiddenLinearLayout, I had to remove the listener itself by using:

mHiddenLinearLayout.animate().setListener(null);

This is because once an animation listener is attached to an view, the next time when any animation is executed in this view, the listener will be executed as well. This might be a bug in the animation listener.

The source code of the project is on GitHub: https://github.com/jiahaoliuliu/ViewsAnimated

Happy coding!

Update: For any listener attached to the views, it should be removed after the animation ends. This is done by using

view.animate().setListener(null);

Dynamic array in C#

List<T> for strongly typed one, or ArrayList if you have .NET 1.1 or love to cast variables.

WPF: ItemsControl with scrollbar (ScrollViewer)

To get a scrollbar for an ItemsControl, you can host it in a ScrollViewer like this:

<ScrollViewer VerticalScrollBarVisibility="Auto">
  <ItemsControl>
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
  </ItemsControl>
</ScrollViewer>

Should try...catch go inside or outside a loop?

In your examples there is no functional difference. I find your first example more readable.

XAMPP permissions on Mac OS X?

Tried the above but the option to amend the permission was not available for the htdocs folder,

My solution was:

  1. Open applications folder
  2. Locate XAMPP folder
  3. Right click, get info (as described above)
  4. In pop-up window locate the 'sharing & permission' section
  5. Click the 'locked' padlock symbol
  6. Enter admin password
  7. Change 'Everyone' permissions to read & write
  8. In the get info window still, select the 'cog' icon' drop down option at the very bottom and select 'Apply to enclosed items' this will adjust the permission across all sub-folders as well.
  9. Re-lock the padlock symbol
  10. Close the 'Get Info' window.

Task complete, this will now allow you to populate sub-folders within the htdocs folder as needed to populate your website(s).

How to unpack pkl file?

Generally

Your pkl file is, in fact, a serialized pickle file, which means it has been dumped using Python's pickle module.

To un-pickle the data you can:

import pickle


with open('serialized.pkl', 'rb') as f:
    data = pickle.load(f)

For the MNIST data set

Note gzip is only needed if the file is compressed:

import gzip
import pickle


with gzip.open('mnist.pkl.gz', 'rb') as f:
    train_set, valid_set, test_set = pickle.load(f)

Where each set can be further divided (i.e. for the training set):

train_x, train_y = train_set

Those would be the inputs (digits) and outputs (labels) of your sets.

If you want to display the digits:

import matplotlib.cm as cm
import matplotlib.pyplot as plt


plt.imshow(train_x[0].reshape((28, 28)), cmap=cm.Greys_r)
plt.show()

mnist_digit

The other alternative would be to look at the original data:

http://yann.lecun.com/exdb/mnist/

But that will be harder, as you'll need to create a program to read the binary data in those files. So I recommend you to use Python, and load the data with pickle. As you've seen, it's very easy. ;-)

A potentially dangerous Request.Form value was detected from the client

In the web.config file, within the tags, insert the httpRuntime element with the attribute requestValidationMode="2.0". Also add the validateRequest="false" attribute in the pages element.

Example:

<configuration>
  <system.web>
   <httpRuntime requestValidationMode="2.0" />
  </system.web>
  <pages validateRequest="false">
  </pages>
</configuration>

Reading json files in C++

  1. Yes you can create a nested data structure people which can be indexed by Anna and Ben. However, you can't index it directly by age and profession (I will get to this part in the code).

  2. The data type of people is of type Json::Value (which is defined in jsoncpp). You are right, it is similar to the nested map, but Value is a data structure which is defined such that multiple types can be stored and accessed. It is similar to a map with a string as the key and Json::Value as the value. It could also be a map between an unsigned int as key and Json::Value as the value (In case of json arrays).

Here's the code:

#include <json/value.h>
#include <fstream>

std::ifstream people_file("people.json", std::ifstream::binary);
people_file >> people;

cout<<people; //This will print the entire json object.

//The following lines will let you access the indexed objects.
cout<<people["Anna"]; //Prints the value for "Anna"
cout<<people["ben"]; //Prints the value for "Ben"
cout<<people["Anna"]["profession"]; //Prints the value corresponding to "profession" in the json for "Anna"

cout<<people["profession"]; //NULL! There is no element with key "profession". Hence a new empty element will be created.

As you can see, you can index the json object only based on the hierarchy of the input data.

How can I check if a string represents an int, without using try/except?

I suggest the following:

import ast

def is_int(s):
    return isinstance(ast.literal_eval(s), int)

From the docs:

Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

I should note that this will raise a ValueError exception when called against anything that does not constitute a Python literal. Since the question asked for a solution without try/except, I have a Kobayashi-Maru type solution for that:

from ast import literal_eval
from contextlib import suppress

def is_int(s):
    with suppress(ValueError):
        return isinstance(literal_eval(s), int)
    return False

¯\_(?)_/¯

How to position background image in bottom right corner? (CSS)

This should do it:

<style>
body {
    background:url(bg.jpg) fixed no-repeat bottom right;
}
</style>

http://www.w3schools.com/cssref/pr_background-position.asp

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

Let me know if this works. Way to detect an Apple device (Mac computers, iPhones, etc.) with help from StackOverflow.com:
What is the list of possible values for navigator.platform as of today?

var deviceDetect = navigator.platform;
var appleDevicesArr = ['MacIntel', 'MacPPC', 'Mac68K', 'Macintosh', 'iPhone', 
'iPod', 'iPad', 'iPhone Simulator', 'iPod Simulator', 'iPad Simulator', 'Pike 
v7.6 release 92', 'Pike v7.8 release 517'];

// If on Apple device
if(appleDevicesArr.includes(deviceDetect)) {
    // Execute code
}
// If NOT on Apple device
else {
    // Execute code
}

How does the "final" keyword in Java work? (I can still modify an object.)

Suppose you have two moneyboxes, red and white. You assign these moneyboxes only two children and they are not allowed interchange their boxes. So You have red or white moneyboxes(final) you cannot modify the box but you can put money on your box.Nobody cares (Modification-2).

How to style SVG <g> element?

You actually cannot draw Container Elements

But you can use a "foreignObject" with a "SVG" inside it to simulate what you need.

http://jsfiddle.net/VBmbP/4/

<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">
      <foreignObject id="G" width="300" height="200">
        <svg>
          <rect fill="blue" stroke-width="2" height="112" width="84" y="55" x="55" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke="#000000"/>
          <ellipse fill="#FF0000" stroke="#000000" stroke-width="5" stroke-dasharray="null" stroke-linejoin="null" stroke-linecap="null" cx="155" cy="65" id="svg_7" rx="64" ry="56"/>     
        </svg>
          <style>
              #G {
                background: #cff; border: 1px dashed black;
              }
              #G:hover {
                background: #acc; border: 1px solid black;
              }
          </style>
      </foreignObject>
    </svg>

How to make Git "forget" about a file that was tracked but is now in .gitignore?

I liked JonBrave's answer but I have messy enough working directories that commit -a scares me a bit, so here's what I've done:

git config --global alias.exclude-ignored '!git ls-files -z --ignored --exclude-standard | xargs -0 git rm -r --cached && git ls-files -z --ignored --exclude-standard | xargs -0 git stage && git stage .gitignore && git commit -m "new gitignore and remove ignored files from index"'

breaking it down:

git ls-files -z --ignored --exclude-standard | xargs -0 git rm -r --cached 
git ls-files -z --ignored --exclude-standard | xargs -0 git stage 
git stage .gitignore 
git commit -m "new gitignore and remove ignored files from index"
  • remove ignored files from index
  • stage .gitignore and the files you just removed
  • commit

Full Screen DialogFragment in Android

The following way will work even if you are working on a relative layout. Follow the following steps:

  1. Go to theme editor ( Available under Tools-> Android -> Theme Editor)
  2. Select show all themes. Select the one with AppCompat.Dialog
  3. Choose the option android window background if you want it to be of any specific colored background or a transparent one.
  4. Select the color and hit OK.Select a name of the new theme.
  5. Go to styles.xml and then under the theme just added, add these two attributes:

    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">false</item>
    

My theme setting for the dialog is as under:

<style name="DialogTheme" parent="Theme.AppCompat.Dialog" >
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">match_parent</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">false</item>

Make sure that the theme has a parent as Theme.AppCompat.Dialog Another way would be just make a new style in styles.xml and change it as per the code above.

  1. Go to your Dialog Fragment class and in the onCreate() method, set the style of your Dialog as:

    @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NORMAL,R.style.DialogTheme); }

What is the cause for "angular is not defined"

You have to put your script tag after the one that references Angular. Move it out of the head:

<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>

The way you've set it up now, your script runs before Angular is loaded on the page.

How do I get values from a SQL database into textboxes using C#?

Make a connection and open it.

con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=<database_name>)));User Id =<userid>; Password =<password>");
con.Open();

Write the select query:

string sql = "select * from Pending_Tasks";

Create a command object:

OracleCommand cmd = new OracleCommand(sql, con);

Execute the command and put the result in a object to read it.

OracleDataReader r = cmd.ExecuteReader();

now start reading from it.

while (read.Read())
{
 CustID.Text = (read["Customer_ID"].ToString());
 CustName.Text = (read["Customer_Name"].ToString());
 Add1.Text = (read["Address_1"].ToString());
 Add2.Text = (read["Address_2"].ToString());
 PostBox.Text = (read["Postcode"].ToString());
 PassBox.Text = (read["Password"].ToString());
 DatBox.Text = (read["Data_Important"].ToString());
 LanNumb.Text = (read["Landline"].ToString());
 MobNumber.Text = (read["Mobile"].ToString());
 FaultRep.Text = (read["Fault_Report"].ToString());
}
read.Close();

Add this too using Oracle.ManagedDataAccess.Client;

How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

Make an exception handler like this,

private int ConvertIntoNumeric(String xVal)
{
 try
  { 
     return Integer.parseInt(xVal);
  }
 catch(Exception ex) 
  {
     return 0; 
  }
}

.
.
.
.

int xTest = ConvertIntoNumeric("N/A");  //Will return 0

What is phtml, and when should I use a .phtml extension rather than .php?

To give an example to what Alex said, if you're using Magento, for example, .phtml files are only to be found in the /design area as template files, and contain both HTML and PHP lines. Meanwhile the PHP files are pure code and don't have any lines of HTML in them.

Java SSL: how to disable hostname verification

In case you're using apache's http-client 4:

SSLConnectionSocketFactory sslConnectionSocketFactory = 
    new SSLConnectionSocketFactory(sslContext,
             new String[] { "TLSv1.2" }, null, new HostnameVerifier() {
                    public boolean verify(String arg0, SSLSession arg1) {
                            return true;
            }
      });

How to encrypt and decrypt file in Android?

I had a similar problem and for encrypt/decrypt i came up with this solution:

public static byte[] generateKey(String password) throws Exception
{
    byte[] keyStart = password.getBytes("UTF-8");

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
    sr.setSeed(keyStart);
    kgen.init(128, sr);
    SecretKey skey = kgen.generateKey();
    return skey.getEncoded();
}

public static byte[] encodeFile(byte[] key, byte[] fileData) throws Exception
{

    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(fileData);

    return encrypted;
}

public static byte[] decodeFile(byte[] key, byte[] fileData) throws Exception
{
    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);

    byte[] decrypted = cipher.doFinal(fileData);

    return decrypted;
}

To save a encrypted file to sd do:

File file = new File(Environment.getExternalStorageDirectory() + File.separator + "your_folder_on_sd", "file_name");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] yourKey = generateKey("password");
byte[] filesBytes = encodeFile(yourKey, yourByteArrayContainigDataToEncrypt);
bos.write(fileBytes);
bos.flush();
bos.close();

To decode a file use:

byte[] yourKey = generateKey("password");
byte[] decodedData = decodeFile(yourKey, bytesOfYourFile);

For reading in a file to a byte Array there a different way out there. A Example: http://examples.javacodegeeks.com/core-java/io/fileinputstream/read-file-in-byte-array-with-fileinputstream/

Using media breakpoints in Bootstrap 4-alpha

I answered a similar question here

As @Syden said, the mixins will work. Another option is using SASS map-get like this..

@media (min-width: map-get($grid-breakpoints, sm)){
  .something {
    padding: 10px;
   }
}

@media (min-width: map-get($grid-breakpoints, md)){
  .something {
    padding: 20px;
   }
}

http://www.codeply.com/go/0TU586QNlV


Bootstrap 4 Breakpoints demo

How to encode the filename parameter of Content-Disposition header in HTTP?

There is discussion of this, including links to browser testing and backwards compatibility, in the proposed RFC 5987, "Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters."

RFC 2183 indicates that such headers should be encoded according to RFC 2184, which was obsoleted by RFC 2231, covered by the draft RFC above.

Installing specific package versions with pip

TL;DR:

  • pip install -Iv (i.e. pip install -Iv MySQL_python==1.2.2)

First, I see two issues with what you're trying to do. Since you already have an installed version, you should either uninstall the current existing driver or use pip install -I MySQL_python==1.2.2

However, you'll soon find out that this doesn't work. If you look at pip's installation log, or if you do a pip install -Iv MySQL_python==1.2.2 you'll find that the PyPI URL link does not work for MySQL_python v1.2.2. You can verify this here: http://pypi.python.org/pypi/MySQL-python/1.2.2

The download link 404s and the fallback URL links are re-directing infinitely due to sourceforge.net's recent upgrade and PyPI's stale URL.

So to properly install the driver, you can follow these steps:

pip uninstall MySQL_python
pip install -Iv http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.2/MySQL-python-1.2.2.tar.gz/download

WPF Add a Border to a TextBlock

No, you need to wrap your TextBlock in a Border. Example:

<Border BorderThickness="1" BorderBrush="Black">
    <TextBlock ... />
</Border>

Of course, you can set these properties (BorderThickness, BorderBrush) through styles as well:

<Style x:Key="notCalledBorder" TargetType="{x:Type Border}">
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="BorderBrush" Value="Black" />
</Style>

<Border Style="{StaticResource notCalledBorder}">
    <TextBlock ... />
</Border>

Initializing a static std::map<int, int> in C++

If you are stuck with C++98 and don't want to use boost, here there is the solution I use when I need to initialize a static map:

typedef std::pair< int, char > elemPair_t;
elemPair_t elemPairs[] = 
{
    elemPair_t( 1, 'a'), 
    elemPair_t( 3, 'b' ), 
    elemPair_t( 5, 'c' ), 
    elemPair_t( 7, 'd' )
};

const std::map< int, char > myMap( &elemPairs[ 0 ], &elemPairs[ sizeof( elemPairs ) / sizeof( elemPairs[ 0 ] ) ] );

How do I copy a string to the clipboard?

Not all of the answers worked for my various python configurations so this solution only uses the subprocess module. However, copy_keyword has to be pbcopy for Mac or clip for Windows:

import subprocess
subprocess.run('copy_keyword', universal_newlines=True, input='New Clipboard Value ')

Here's some more extensive code that automatically checks what the current operating system is:

import platform
import subprocess

copy_string = 'New Clipboard Value '

# Check which operating system is running to get the correct copying keyword.
if platform.system() == 'Darwin':
    copy_keyword = 'pbcopy'
elif platform.system() == 'Windows':
    copy_keyword = 'clip'

subprocess.run(copy_keyword, universal_newlines=True, input=copy_string)

Update label from another thread

You cannot update UI from any other thread other than the UI thread. Use this to update thread on the UI thread.

 private void AggiornaContatore()
 {         
     if(this.lblCounter.InvokeRequired)
     {
         this.lblCounter.BeginInvoke((MethodInvoker) delegate() {this.lblCounter.Text = this.index.ToString(); ;});    
     }
     else
     {
         this.lblCounter.Text = this.index.ToString(); ;
     }
 }

Please go through this chapter and more from this book to get a clear picture about threading:

http://www.albahari.com/threading/part2.aspx#_Rich_Client_Applications

MySQL search and replace some text in a field

In my experience, the fastest method is

UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE field LIKE '%foo%';

The INSTR() way is the second-fastest and omitting the WHERE clause altogether is slowest, even if the column is not indexed.

The differences between initialize, define, declare a variable

Declaration

Declaration, generally, refers to the introduction of a new name in the program. For example, you can declare a new function by describing it's "signature":

void xyz();

or declare an incomplete type:

class klass;
struct ztruct;

and last but not least, to declare an object:

int x;

It is described, in the C++ standard, at §3.1/1 as:

A declaration (Clause 7) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations.

Definition

A definition is a definition of a previously declared name (or it can be both definition and declaration). For example:

int x;
void xyz() {...}
class klass {...};
struct ztruct {...};
enum { x, y, z };

Specifically the C++ standard defines it, at §3.1/1, as:

A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function- body, it declares a static data member in a class definition (9.2, 9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), it is a template-parameter (14.1), it is a parameter-declaration (8.3.5) in a function declarator that is not the declarator of a function-definition, or it is a typedef declaration (7.1.3), an alias-declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attribute- declaration (Clause 7), an empty-declaration (Clause 7), or a using-directive (7.3.4).

Initialization

Initialization refers to the "assignment" of a value, at construction time. For a generic object of type T, it's often in the form:

T x = i;

but in C++ it can be:

T x(i);

or even:

T x {i};

with C++11.

Conclusion

So does it mean definition equals declaration plus initialization?

It depends. On what you are talking about. If you are talking about an object, for example:

int x;

This is a definition without initialization. The following, instead, is a definition with initialization:

int x = 0;

In certain context, it doesn't make sense to talk about "initialization", "definition" and "declaration". If you are talking about a function, for example, initialization does not mean much.

So, the answer is no: definition does not automatically mean declaration plus initialization.

Create an array of integers property in Objective-C

Like lucius said, it's not possible to have a C array property. Using an NSArray is the way to go. An array only stores objects, so you'd have to use NSNumbers to store your ints. With the new literal syntax, initialising it is very easy and straight-forward:

NSArray *doubleDigits = @[ @1, @2, @3, @4, @5, @6, @7, @8, @9, @10 ];

Or:

NSMutableArray *doubleDigits = [NSMutableArray array];

for (int n = 1; n <= 10; n++)
    [doubleDigits addObject:@(n)];

For more information: NSArray Class Reference, NSNumber Class Reference, Literal Syntax

Find size and free space of the filesystem containing a given file

This should make everything you asked:

import os
from collections import namedtuple

disk_ntuple = namedtuple('partition',  'device mountpoint fstype')
usage_ntuple = namedtuple('usage',  'total used free percent')

def disk_partitions(all=False):
    """Return all mountd partitions as a nameduple.
    If all == False return phyisical partitions only.
    """
    phydevs = []
    f = open("/proc/filesystems", "r")
    for line in f:
        if not line.startswith("nodev"):
            phydevs.append(line.strip())

    retlist = []
    f = open('/etc/mtab', "r")
    for line in f:
        if not all and line.startswith('none'):
            continue
        fields = line.split()
        device = fields[0]
        mountpoint = fields[1]
        fstype = fields[2]
        if not all and fstype not in phydevs:
            continue
        if device == 'none':
            device = ''
        ntuple = disk_ntuple(device, mountpoint, fstype)
        retlist.append(ntuple)
    return retlist

def disk_usage(path):
    """Return disk usage associated with path."""
    st = os.statvfs(path)
    free = (st.f_bavail * st.f_frsize)
    total = (st.f_blocks * st.f_frsize)
    used = (st.f_blocks - st.f_bfree) * st.f_frsize
    try:
        percent = ret = (float(used) / total) * 100
    except ZeroDivisionError:
        percent = 0
    # NB: the percentage is -5% than what shown by df due to
    # reserved blocks that we are currently not considering:
    # http://goo.gl/sWGbH
    return usage_ntuple(total, used, free, round(percent, 1))


if __name__ == '__main__':
    for part in disk_partitions():
        print part
        print "    %s\n" % str(disk_usage(part.mountpoint))

On my box the code above prints:

giampaolo@ubuntu:~/dev$ python foo.py 
partition(device='/dev/sda3', mountpoint='/', fstype='ext4')
    usage(total=21378641920, used=4886749184, free=15405903872, percent=22.9)

partition(device='/dev/sda7', mountpoint='/home', fstype='ext4')
    usage(total=30227386368, used=12137168896, free=16554737664, percent=40.2)

partition(device='/dev/sdb1', mountpoint='/media/1CA0-065B', fstype='vfat')
    usage(total=7952400384, used=32768, free=7952367616, percent=0.0)

partition(device='/dev/sr0', mountpoint='/media/WB2PFRE_IT', fstype='iso9660')
    usage(total=695730176, used=695730176, free=0, percent=100.0)

partition(device='/dev/sda6', mountpoint='/media/Dati', fstype='fuseblk')
    usage(total=914217758720, used=614345637888, free=299872120832, percent=67.2)

Using the HTML5 "required" attribute for a group of checkboxes?

Inspired by the answers from @thegauraw and @Brian Woodward, here's a bit I pulled together for JQuery users, including a custom validation error message:

$cbx_group = $("input:checkbox[name^='group']");
$cbx_group.on("click", function() {
    if ($cbx_group.is(":checked")) {
        // checkboxes become unrequired as long as one is checked
        $cbx_group.prop("required", false).each(function() {
            this.setCustomValidity("");
        });
    } else {
        // require checkboxes and set custom validation error message
        $cbx_group.prop("required", true).each(function() {
            this.setCustomValidity("Please select at least one checkbox.");
        });
    }
});

Note that my form has some checkboxes checked by default.

Maybe some of you JavaScript/JQuery wizards could tighten that up even more?

Drawing a line/path on Google Maps

This can be done by using intents too:

  final Intent intent = new Intent(Intent.ACTION_VIEW,
    Uri.parse(
            "http://maps.google.com/maps?" +
            "saddr="+YOUR_START_LONGITUDE+","+YOUR_START_LATITUDE+"&daddr="YOUR_END_LONGITUDE+","+YOUR_END_LATITUDE));
         intent.setClassName(
          "com.google.android.apps.maps",
          "com.google.android.maps.MapsActivity");
   startActivity(intent);

How to map an array of objects in React

What you need is to map your array of objects and remember that every item will be an object, so that you will use for instance dot notation to take the values of the object.

In your component

 [
    {
        name: 'Sam',
        email: '[email protected]'
    },

    {
        name: 'Ash',
        email: '[email protected]'
    }
].map((anObjectMapped, index) => {
    return (
        <p key={`${anObjectMapped.name}_{anObjectMapped.email}`}>
            {anObjectMapped.name} - {anObjectMapped.email}
        </p>
    );
})

And remember when you put an array of jsx it has a different meaning and you can not just put object in your render method as you can put an array.

Take a look at my answer at mapping an array to jsx

Proper indentation for Python multiline strings

For strings you can just after process the string. For docstrings you need to after process the function instead. Here is a solution for both that is still readable.

class Lstrip(object):
    def __rsub__(self, other):
        import re
        return re.sub('^\n', '', re.sub('\n$', '', re.sub('\n\s+', '\n', other)))

msg = '''
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
      veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum.
      ''' - Lstrip()

print msg

def lstrip_docstring(func):
    func.__doc__ = func.__doc__ - Lstrip()
    return func

@lstrip_docstring
def foo():
    '''
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
    veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
    commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
    velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
    cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
    est laborum.
    '''
    pass


print foo.__doc__

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Another option would be using flexbox.

While it's not supported by IE8 and IE9, you could consider:

  • Not minding about those old IE versions
  • Providing a fallback
  • Using a polyfill

Despite some additional browser-specific style prefixing would be necessary for full cross-browser support, you can see the basic usage either on this fiddle and on the following snippet:

_x000D_
_x000D_
html {_x000D_
  height: 100%;_x000D_
}_x000D_
html body {_x000D_
  height: 100%;_x000D_
  overflow: hidden;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
  width: 100%;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
    background-color: #4C4;_x000D_
    min-height: 50px;_x000D_
    width: 100%;_x000D_
}_x000D_
footer {_x000D_
    background-color: #4C4;_x000D_
    min-height: 30px;_x000D_
    width: 100%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
_x000D_
_x000D_

How to get folder directory from HTML input type "file" or any other way?

Eventhough it is an old question, this may help someone.

We can choose multiple files while browsing for a file using "multiple"

<input type="file" name="datafile" size="40"  multiple> 

XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header

I got the same error in Chrome console.

My problem was, I was trying to go to the site using http:// instead of https://. So there was nothing to fix, just had to go to the same site using https.

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

I faced the same issue. I had missed the forms module import tag in the app.module.ts

import { FormsModule } from '@angular/forms';

@NgModule({
    imports: [BrowserModule,
        FormsModule
    ],

Tensorflow: Using Adam optimizer

You need to call tf.global_variables_initializer() on you session, like

init = tf.global_variables_initializer()
sess.run(init)

Full example is available in this great tutorial https://www.tensorflow.org/get_started/mnist/mechanics

Difference between private, public, and protected inheritance

Public inheritance models an IS-A relationship. With

class B {};
class D : public B {};

every D is a B.

Private inheritance models an IS-IMPLEMENTED-USING relationship (or whatever that's called). With

class B {};
class D : private B {};

a D is not a B, but every D uses its B in its implementation. Private inheritance can always be eliminated by using containment instead:

class B {};
class D {
  private: 
    B b_;
};

This D, too, can be implemented using B, in this case using its b_. Containment is a less tight coupling between types than inheritance, so in general it should be preferred. Sometimes using containment instead of private inheritance is not as convenient as private inheritance. Often that's a lame excuse for being lazy.

I don't think anyone knows what protected inheritance models. At least I haven't seen any convincing explanation yet.

PHP mailer multiple address

You need to call the AddAddress method once for every recipient. Like so:

$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..

Better yet, add them as Carbon Copy recipients.

$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddCC($email, $name);
}

What's the difference between echo, print, and print_r in PHP?

Just to add to John's answer, echo should be the only one you use to print content to the page.

print is slightly slower. var_dump() and print_r() should only be used to debug.

Also worth mentioning is that print_r() and var_dump() will echo by default, add a second argument to print_r() at least that evaluates to true to get it to return instead, e.g. print_r($array, TRUE).

The difference between echoing and returning are:

  • echo: Will immediately print the value to the output.
  • returning: Will return the function's output as a string. Useful for logging, etc.

C: What is the difference between ++i and i++?

The effective result of using either in a loop is identical. In other words, the loop will do the same exact thing in both instances.

In terms of efficiency, there could be a penalty involved with choosing i++ over ++i. In terms of the language spec, using the post-increment operator should create an extra copy of the value on which the operator is acting. This could be a source of extra operations.

However, you should consider two main problems with the preceding logic.

  1. Modern compilers are great. All good compilers are smart enough to realize that it is seeing an integer increment in a for-loop, and it will optimize both methods to the same efficient code. If using post-increment over pre-increment actually causes your program to have a slower running time, then you are using a terrible compiler.

  2. In terms of operational time-complexity, the two methods (even if a copy is actually being performed) are equivalent. The number of instructions being performed inside of the loop should dominate the number of operations in the increment operation significantly. Therefore, in any loop of significant size, the penalty of the increment method will be massively overshadowed by the execution of the loop body. In other words, you are much better off worrying about optimizing the code in the loop rather than the increment.

In my opinion, the whole issue simply boils down to a style preference. If you think pre-increment is more readable, then use it. Personally, I prefer the post-incrment, but that is probably because it was what I was taught before I knew anything about optimization.

This is a quintessential example of premature optimization, and issues like this have the potential to distract us from serious issues in design. It is still a good question to ask, however, because there is no uniformity in usage or consensus in "best practice."

How to check if an integer is within a range of numbers in PHP?

The expression:

 ($min <= $value) && ($value <= $max)

will be true if $value is between $min and $max, inclusively

See the PHP docs for more on comparison operators

How do I force my .NET application to run as administrator?

I implemented some code to do it manually:

using System.Security.Principal;
public bool IsUserAdministrator()
{
    bool isAdmin;
    try
    {
        WindowsIdentity user = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(user);
        isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch (UnauthorizedAccessException ex)
    {
        isAdmin = false;
    }
    catch (Exception ex)
    {
        isAdmin = false;
    }
    return isAdmin;
}

Can a CSV file have a comment?

In engineering data, it is common to see the # symbol in the first column used to signal a comment.

I use the ostermiller CSV parsing library for Java to read and process such files. That library allows you to set the comment character. After the parse operation you get an array just containing the real data, no comments.

CSS3 Transition not working

If you have a <script> tag anywhere on your page (even in the HTML, even if it is an empty tag with a src), then a transition must be activated by some event (it won't fire automatically when the page loads).

Checking whether the pip is installed?

In CMD, type:

pip freeze

And it will show you a list of all the modules installed including the version number.

Output:

aiohttp==1.1.4
async-timeout==1.1.0
cx-Freeze==4.3.4
Django==1.9.2
django-allauth==0.24.1
django-cors-headers==1.2.2
django-crispy-forms==1.6.0
django-robots==2.0
djangorestframework==3.3.2
easygui==0.98.0
future==0.16.0
httpie==0.9.6
matplotlib==1.5.3
multidict==2.1.2
numpy==1.11.2
oauthlib==1.0.3
pandas==0.19.1
pefile==2016.3.28
pygame==1.9.2b1
Pygments==2.1.3
PyInstaller==3.2
pyparsing==2.1.10
pypiwin32==219
PyQt5==5.7
pytz==2016.7
requests==2.9.1
requests-oauthlib==0.6
six==1.10.0
sympy==1.0
virtualenv==15.0.3
xlrd==1.0.0
yarl==0.7.0

Set form backcolor to custom color

With Winforms you can use Form.BackColor to do this.
From within the Form's code:

BackColor = Color.LightPink;

If you mean a WPF Window you can use the Background property.
From within the Window's code:

Background = Brushes.LightPink;

seek() function?

The seek function expect's an offset in bytes.

Ascii File Example:

So if you have a text file with the following content:

simple.txt

abc

You can jump 1 byte to skip over the first character as following:

fp = open('simple.txt', 'r')
fp.seek(1)
print fp.readline()
>>> bc

Binary file example gathering width :

fp = open('afile.png', 'rb')
fp.seek(16)
print 'width: {0}'.format(struct.unpack('>i', fp.read(4))[0])
print 'height: ', struct.unpack('>i', fp.read(4))[0]

Note: Once you call read you are changing the position of the read-head, which act's like seek.

Why Doesn't C# Allow Static Methods to Implement an Interface?

To the extent that interfaces represent "contracts", it seems quiet reasonable for static classes to implement interfaces.

The above arguments all seem to miss this point about contracts.

Changing button color programmatically

I believe you want bgcolor. Something like this:

document.getElementById("button").bgcolor="#ffffff";

Here are a couple of demos that might help:

Background Color

Background Color Changer

How to embed a .mov file in HTML?

<object CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="320" height="256" CODEBASE="http://www.apple.com/qtactivex/qtplugin.cab">
    <param name="src" value="sample.mov">
    <param name="qtsrc" value="rtsp://realmedia.uic.edu/itl/ecampb5/demo_broad.mov">
    <param name="autoplay" value="true">
    <param name="loop" value="false">
    <param name="controller" value="true">
    <embed src="sample.mov" qtsrc="rtsp://realmedia.uic.edu/itl/ecampb5/demo_broad.mov" width="320" height="256" autoplay="true" loop="false" controller="true" pluginspage="http://www.apple.com/quicktime/"></embed>
</object>

source is the first search result of the Google

Check if string ends with one of the strings from a list

I just came across this, while looking for something else.

I would recommend to go with the methods in the os package. This is because you can make it more general, compensating for any weird case.

You can do something like:

import os

the_file = 'aaaa/bbbb/ccc.ddd'

extensions_list = ['ddd', 'eee', 'fff']

if os.path.splitext(the_file)[-1] in extensions_list:
    # Do your thing.

"Debug only" code that should run only when "turned on"

If you want to know whether if debugging, everywhere in program. Use this.

Declare global variable.

bool isDebug=false;

Create function for checking debug mode

[ConditionalAttribute("DEBUG")]
    public static void isDebugging()
    {
        isDebug = true;
    }

In the initialize method call the function

isDebugging();

Now in the entire program. You can check for debugging and do the operations. Hope this Helps!

Why can't I duplicate a slice with `copy()`?

The builtin copy(dst, src) copies min(len(dst), len(src)) elements.

So if your dst is empty (len(dst) == 0), nothing will be copied.

Try tmp := make([]int, len(arr)) (Go Playground):

arr := []int{1, 2, 3}
tmp := make([]int, len(arr))
copy(tmp, arr)
fmt.Println(tmp)
fmt.Println(arr)

Output (as expected):

[1 2 3]
[1 2 3]

Unfortunately this is not documented in the builtin package, but it is documented in the Go Language Specification: Appending to and copying slices:

The number of elements copied is the minimum of len(src) and len(dst).

Edit:

Finally the documentation of copy() has been updated and it now contains the fact that the minimum length of source and destination will be copied:

Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).

NameError: global name is not defined

try

from sqlitedbx import SqliteDBzz

How to access random item in list?

I usually use this little collection of extension methods:

public static class EnumerableExtension
{
    public static T PickRandom<T>(this IEnumerable<T> source)
    {
        return source.PickRandom(1).Single();
    }

    public static IEnumerable<T> PickRandom<T>(this IEnumerable<T> source, int count)
    {
        return source.Shuffle().Take(count);
    }

    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
    {
        return source.OrderBy(x => Guid.NewGuid());
    }
}

For a strongly typed list, this would allow you to write:

var strings = new List<string>();
var randomString = strings.PickRandom();

If all you have is an ArrayList, you can cast it:

var strings = myArrayList.Cast<string>();

What's the proper way to compare a String to an enum value?

You can compare a string to an enum item as follow,

public class Main {

    enum IaaSProvider{
        aws,
        microsoft,
        google
    }

    public static void main(String[] args){

        IaaSProvider iaaSProvider = IaaSProvider.google;

        if("google".equals(iaaSProvider.toString())){
            System.out.println("The provider is google");
        }

    }
}

React - Display loading screen while DOM is rendering?

The starting of react app is based on the main bundle download. React app only starts after the main bundle being downloaded in the browser. This is even true in case of lazy loading architecture. But the fact is we cannot exactly state the name of any bundles. Because webpack will add a hash value at the end of each bundle at the time when you run 'npm run build' command. Of course we can avoid that by changing hash settings, but it will seriously affect the cache data problem in the Browser. Browsers might not take the new version because of the same bundle name. . we need a webpack + js + CSS approach to handle this situation.

change the public/index.html as below

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en" xml:lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=3.0, shrink-to-fit=no">_x000D_
  <meta name="theme-color" content="#000000">_x000D_
  <!--_x000D_
      manifest.json provides metadata used when your web app is added to the_x000D_
      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/_x000D_
    -->_x000D_
  <link rel="manifest" href="%PUBLIC_URL%/manifest.json">_x000D_
  <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">_x000D_
  <style>_x000D_
 .percentage {_x000D_
      position: absolute;_x000D_
      top: 50%;_x000D_
      left: 50%;_x000D_
      width: 150px;_x000D_
      height: 150px;_x000D_
      border: 1px solid #ccc;_x000D_
      background-color: #f3f3f3;_x000D_
      -webkit-transform: translate(-50%, -50%);_x000D_
          -ms-transform: translate(-50%, -50%);_x000D_
              transform: translate(-50%, -50%);_x000D_
      border: 1.1em solid rgba(0, 0, 0, 0.2);_x000D_
      border-radius: 50%;_x000D_
      overflow: hidden;_x000D_
      display: -webkit-box;_x000D_
      display: -ms-flexbox;_x000D_
      display: flex;_x000D_
      -webkit-box-pack: center;_x000D_
          -ms-flex-pack: center;_x000D_
              justify-content: center;_x000D_
      -webkit-box-align: center;_x000D_
          -ms-flex-align: center;_x000D_
              align-items: center;_x000D_
    }_x000D_
_x000D_
    .innerpercentage {_x000D_
      font-size: 20px;_x000D_
    }_x000D_
  </style>_x000D_
  <script>_x000D_
    function showPercentage(value) {_x000D_
      document.getElementById('percentage').innerHTML = (value * 100).toFixed() + "%";_x000D_
    }_x000D_
    var req = new XMLHttpRequest();_x000D_
    req.addEventListener("progress", function (event) {_x000D_
      if (event.lengthComputable) {_x000D_
        var percentComplete = event.loaded / event.total;_x000D_
        showPercentage(percentComplete)_x000D_
        // ..._x000D_
      } else {_x000D_
        document.getElementById('percentage').innerHTML = "Loading..";_x000D_
      }_x000D_
    }, false);_x000D_
_x000D_
    // load responseText into a new script element_x000D_
    req.addEventListener("load", function (event) {_x000D_
      var e = event.target;_x000D_
      var s = document.createElement("script");_x000D_
      s.innerHTML = e.responseText;_x000D_
      document.documentElement.appendChild(s);_x000D_
      document.getElementById('parentDiv').style.display = 'none';_x000D_
_x000D_
    }, false);_x000D_
_x000D_
    var bundleName = "<%= htmlWebpackPlugin.files.chunks.main.entry %>";_x000D_
    req.open("GET", bundleName);_x000D_
    req.send();_x000D_
_x000D_
  </script>_x000D_
  <!--_x000D_
      Notice the use of %PUBLIC_URL% in the tags above._x000D_
      It will be replaced with the URL of the `public` folder during the build._x000D_
      Only files inside the `public` folder can be referenced from the HTML._x000D_
_x000D_
      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will_x000D_
      work correctly both with client-side routing and a non-root public URL._x000D_
      Learn how to configure a non-root public URL by running `npm run build`._x000D_
    -->_x000D_
_x000D_
  <title>App Name</title>_x000D_
  <link href="<%= htmlWebpackPlugin.files.chunks.main.css[0] %>" rel="stylesheet">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <noscript>_x000D_
    You need to enable JavaScript to run this app._x000D_
  </noscript>_x000D_
  <div id="parentDiv" class="percentage">_x000D_
    <div id="percentage" class="innerpercentage">loading</div>_x000D_
  </div>_x000D_
  <div id="root"></div>_x000D_
  <!--_x000D_
      This HTML file is a template._x000D_
      If you open it directly in the browser, you will see an empty page._x000D_
_x000D_
      You can add webfonts, meta tags, or analytics to this file._x000D_
      The build step will place the bundled scripts into the <body> tag._x000D_
_x000D_
      To begin the development, run `npm start` or `yarn start`._x000D_
      To create a production bundle, use `npm run build` or `yarn build`._x000D_
    -->_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

In your production webpack configuration change the HtmlWebpackPlugin option to below

 new HtmlWebpackPlugin({
          inject: false,
...

You may need to use 'eject' command to get the configuration file. latest webpack might have the option to configure the HtmlWebpackPlugin without ejecting project. enter image description here

Java 'file.delete()' Is not Deleting Specified File

Try closing all the FileOutputStream/FileInputStream you've opened earlier in other methods ,then try deleting ,worked like a charm.

Make text wrap in a cell with FPDF?

Text Wrap:

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

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

Line Height:

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

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

You can read the full documentation here.

Exception: Serialization of 'Closure' is not allowed

Direct Closure serialisation is not allowed by PHP. But you can use powefull class like PHP Super Closure : https://github.com/jeremeamia/super_closure

This class is really simple to use and is bundled into the laravel framework for the queue manager.

From the github documentation :

$helloWorld = new SerializableClosure(function ($name = 'World') use ($greeting) {
    echo "{$greeting}, {$name}!\n";
});

$serialized = serialize($helloWorld);

installation app blocked by play protect

I am adding this answer for others who are still seeking a solution to this problem if you don't want to upload your app on playstore then temporarily there is a workaround for this problem.

Google is providing safety device verification api which you need to call only once in your application and after that your application will not be blocked by play protect:

Here are there the links:

https://developer.android.com/training/safetynet/attestation#verify-attestation-response

Link for sample code project:

https://github.com/googlesamples/android-play-safetynet

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

This happens when Elasticsearch thinks the disk is running low on space so it puts itself into read-only mode.

By default Elasticsearch's decision is based on the percentage of disk space that's free, so on big disks this can happen even if you have many gigabytes of free space.

The flood stage watermark is 95% by default, so on a 1TB drive you need at least 50GB of free space or Elasticsearch will put itself into read-only mode.

For docs about the flood stage watermark see https://www.elastic.co/guide/en/elasticsearch/reference/6.2/disk-allocator.html.

The right solution depends on the context - for example a production environment vs a development environment.

Solution 1: free up disk space

Freeing up enough disk space so that more than 5% of the disk is free will solve this problem. Elasticsearch won't automatically take itself out of read-only mode once enough disk is free though, you'll have to do something like this to unlock the indices:

$ curl -XPUT -H "Content-Type: application/json" https://[YOUR_ELASTICSEARCH_ENDPOINT]:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

Solution 2: change the flood stage watermark setting

Change the "cluster.routing.allocation.disk.watermark.flood_stage" setting to something else. It can either be set to a lower percentage or to an absolute value. Here's an example of how to change the setting from the docs:

PUT _cluster/settings
{
  "transient": {
    "cluster.routing.allocation.disk.watermark.low": "100gb",
    "cluster.routing.allocation.disk.watermark.high": "50gb",
    "cluster.routing.allocation.disk.watermark.flood_stage": "10gb",
    "cluster.info.update.interval": "1m"
  }
}

Again, after doing this you'll have to use the curl command above to unlock the indices, but after that they should not go into read-only mode again.

How to access global variables

I create a file dif.go that contains your code:

package dif

import (
    "time"
)

var StartTime = time.Now()

Outside the folder I create my main.go, it is ok!

package main

import (
    dif "./dif"
    "fmt"
)

func main() {
    fmt.Println(dif.StartTime)
}

Outputs:

2016-01-27 21:56:47.729019925 +0800 CST

Files directory structure:

folder
  main.go
  dif
    dif.go

It works!

How do I use JDK 7 on Mac OSX?

I updated to Yosemite and Android Studio wouldn't clean my projects or Run them on virtual or real device because of the following error:

Failed to complete Gradle execution.Cause:Supplied javaHome is not a valid folder. You supplied: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home

After some research and trouble shooting, I found that the JDK file that was being pointed to at "/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home" wasn't there; all of "JavaVirtualMachines/1.6.0.jdk/Contents/Home" was missing from "/System/Library/Java". So, I copied "JavaVirtualMachines/1.6.0.jdk/Contents/Home" over from "/Library/Java/" to "/System/Library/Java/" and cha ching! I was back in business.

how to run python files in windows command prompt?

First set path of python https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows

and run python file

python filename.py

command line argument with python

python filename.py command-line argument

How to extract a value from a string using regex and a shell?

You can certainly extract that part of a string and that's a great way to parse out data. Regular expression syntax varies a lot so you need to reference the help file for the regex you're using. You might try a regular expression like:

[0-9]+ *[a-zA-Z]+,([0-9]+) *[a-zA-Z]+,[0-9]+ *[a-zA-Z]+

If your regex program can do string replacement then replace the entire string with the result you want and you can easily use that result.

You didn't mention if you're using bash or some other shell. That would help get better answers when asking for help.

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

Usage of margin-left:auto and margin-right:auto may not work in certain situations. Here is a solution what will always work. You specify a required width and than set a left-margin to a half of the remaining width.

    <div style="width:80%; margin-left:calc(10%);">
        your_html
    </div>

How to rename a file using Python

As of Python 3.4 one can use the pathlib module to solve this.

If you happen to be on an older version, you can use the backported version found here

Let's assume you are not in the root path (just to add a bit of difficulty to it) you want to rename, and have to provide a full path, we can look at this:

some_path = 'a/b/c/the_file.extension'

So, you can take your path and create a Path object out of it:

from pathlib import Path
p = Path(some_path)

Just to provide some information around this object we have now, we can extract things out of it. For example, if for whatever reason we want to rename the file by modifying the filename from the_file to the_file_1, then we can get the filename part:

name_without_extension = p.stem

And still hold the extension in hand as well:

ext = p.suffix

We can perform our modification with a simple string manipulation:

Python 3.6 and greater make use of f-strings!

new_file_name = f"{name_without_extension}_1"

Otherwise:

new_file_name = "{}_{}".format(name_without_extension, 1)

And now we can perform our rename by calling the rename method on the path object we created and appending the ext to complete the proper rename structure we want:

p.rename(Path(p.parent, new_file_name + ext))

More shortly to showcase its simplicity:

Python 3.6+:

from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, f"{p.stem}_1_{p.suffix}"))

Versions less than Python 3.6 use the string format method instead:

from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, "{}_{}_{}".format(p.stem, 1, p.suffix))

__init__() missing 1 required positional argument

You should possibly make data a keyword parameter with a default value of empty dictionary:

class DHT:
    def __init__(self, data=dict()):
        self.data['one'] = '1'
        self.data['two'] = '2'
        self.data['three'] = '3'
    def showData(self):
        print(self.data)

if __name__ == '__main__': 
    DHT().showData()

Ruby on Rails: Where to define global constants?

For application-wide settings and for global constants I recommend to use Settingslogic. This settings are stored in YML file and can be accessed from models, views and controllers. Furthermore, you can create different settings for all your environments:

  # app/config/application.yml
  defaults: &defaults
    cool:
      sweet: nested settings
    neat_setting: 24
    awesome_setting: <%= "Did you know 5 + 5 = #{5 + 5}?" %>

    colors: "white blue black red green"

  development:
    <<: *defaults
    neat_setting: 800

  test:
    <<: *defaults

  production:
    <<: *defaults

Somewhere in the view (I prefer helper methods for such kind of stuff) or in a model you can get, for ex., array of colors Settings.colors.split(/\s/). It's very flexible. And you don't need to invent a bike.

How to increase request timeout in IIS?

I know the question was about ASP but maybe somebody will find this answer helpful.

If you have a server behind the IIS 7.5 (e.g. Tomcat). In my case I have a server farm with Tomcat server configured. In such case you can change the timeout using the IIS Manager:

  • go to Server Farms -> {Server Name} -> Proxy
  • change the value in the Time-out entry box
  • click Apply (top-right corner)

or you can change it in the cofig file:

  • open %WinDir%\System32\Inetsrv\Config\applicationHost.config
  • adjust the server webFarm configuration to be similar to the following

Example:

<webFarm name="${SERVER_NAME}" enabled="true"> 
  <server address="${SERVER_ADDRESS}" enabled="true">
    <applicationRequestRouting httpPort="${SERVER_PORT}" />
  </server>
  <applicationRequestRouting>
    <protocol timeout="${TIME}" />
  </applicationRequestRouting>
</webFarm>

The ${TIME} is in HH:mm:ss format (so if you want to set it to 90 seconds then put there 00:01:30)

In case of Tomcat (and probably other servlet containers) you have to remember to change the timeout in the %TOMCAT_DIR%\conf\server.xml (just search for connectionTimeout attribute in Connector tag, and remember that it is specified in milliseconds)

How do I import material design library to Android Studio?

Goto

  1. File (Top Left Corner)
  2. Project Structure
  3. Under Module. Find the Dependence tab
  4. press plus button (+) at top right.
  5. You will find all the dependencies

add elements to object array

You can use class System.Array for add new element:

Array.Resize(ref objArray, objArray.Length + 1);
objArray[objArray.Length - 1] = new Someobject();

Restoring MySQL database from physical files

Yes it is! Just add them to your database-folder ( depending on the OS ) and run a command such as "MySQL Fix Permissions". This re-stored the database. See too it that the correct permissions are set on the files aswell.

How to rotate portrait/landscape Android emulator?

Yes. Thanks

Ctrl + F11 for Portrait

and

Ctrl + F12 for Landscape

how to move elasticsearch data from one server to another

Use ElasticDump

1) yum install epel-release

2) yum install nodejs

3) yum install npm

4) npm install elasticdump

5) cd node_modules/elasticdump/bin

6)

./elasticdump \

  --input=http://192.168.1.1:9200/original \

  --output=http://192.168.1.2:9200/newCopy \

  --type=data

Regex to extract URLs from href attribute in HTML with Python

The best answer is...

Don't use a regex

The expression in the accepted answer misses many cases. Among other things, URLs can have unicode characters in them. The regex you want is here, and after looking at it, you may conclude that you don't really want it after all. The most correct version is ten-thousand characters long.

Admittedly, if you were starting with plain, unstructured text with a bunch of URLs in it, then you might need that ten-thousand-character-long regex. But if your input is structured, use the structure. Your stated aim is to "extract the url, inside the anchor tag's href." Why use a ten-thousand-character-long regex when you can do something much simpler?

Parse the HTML instead

For many tasks, using Beautiful Soup will be far faster and easier to use:

>>> from bs4 import BeautifulSoup as Soup
>>> html = Soup(s, 'html.parser')           # Soup(s, 'lxml') if lxml is installed
>>> [a['href'] for a in html.find_all('a')]
['http://example.com', 'http://example2.com']

If you prefer not to use external tools, you can also directly use Python's own built-in HTML parsing library. Here's a really simple subclass of HTMLParser that does exactly what you want:

from html.parser import HTMLParser

class MyParser(HTMLParser):
    def __init__(self, output_list=None):
        HTMLParser.__init__(self)
        if output_list is None:
            self.output_list = []
        else:
            self.output_list = output_list
    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            self.output_list.append(dict(attrs).get('href'))

Test:

>>> p = MyParser()
>>> p.feed(s)
>>> p.output_list
['http://example.com', 'http://example2.com']

You could even create a new method that accepts a string, calls feed, and returns output_list. This is a vastly more powerful and extensible way than regular expressions to extract information from html.

C++ correct way to return pointer to array from function

Your code (which looks ok) doesn't return a pointer to an array. It returns a pointer to the first element of an array.

In fact that's usually what you want to do. Most manipulation of arrays are done via pointers to individual elements, not via pointers to the array as a whole.

You can define a pointer to an array, for example this:

double (*p)[42];

defines p as a pointer to a 42-element array of doubles. A big problem with that is that you have to specify the number of elements in the array as part of the type -- and that number has to be a compile-time constant. Most programs that deal with arrays need to deal with arrays of varying sizes; a given array's size won't vary after it's been created, but its initial size isn't necessarily known at compile time, and different array objects can have different sizes.

A pointer to the first element of an array lets you use either pointer arithmetic or the indexing operator [] to traverse the elements of the array. But the pointer doesn't tell you how many elements the array has; you generally have to keep track of that yourself.

If a function needs to create an array and return a pointer to its first element, you have to manage the storage for that array yourself, in one of several ways. You can have the caller pass in a pointer to (the first element of) an array object, probably along with another argument specifying its size -- which means the caller has to know how big the array needs to be. Or the function can return a pointer to (the first element of) a static array defined inside the function -- which means the size of the array is fixed, and the same array will be clobbered by a second call to the function. Or the function can allocate the array on the heap -- which makes the caller responsible for deallocating it later.

Everything I've written so far is common to C and C++, and in fact it's much more in the style of C than C++. Section 6 of the comp.lang.c FAQ discusses the behavior of arrays and pointers in C.

But if you're writing in C++, you're probably better off using C++ idioms. For example, the C++ standard library provides a number of headers defining container classes such as <vector> and <array>, which will take care of most of this stuff for you. Unless you have a particular reason to use raw arrays and pointers, you're probably better off just using C++ containers instead.

EDIT : I think you edited your question as I was typing this answer. The new code at the end of your question is, as you observer, no good; it returns a pointer to an object that ceases to exist as soon as the function returns. I think I've covered the alternatives.

How to get the latest record in each group using GROUP BY?

You need to order them.

SELECT * FROM messages GROUP BY from_id ORDER BY timestamp DESC LIMIT 1

Nested iframes, AKA Iframe Inception

Hey I got something that seems to be doing what you want a do. It involves some dirty copying but works. You can find the working code here

So here is the main html file :

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function(){
            Iframe = $('#frame1');

            Iframe.on('load', function(){
                IframeInner = Iframe.contents().find('iframe');

                IframeInnerClone = IframeInner.clone();

                IframeInnerClone.insertAfter($('#insertIframeAfter')).css({display:'none'});

                IframeInnerClone.on('load', function(){
                    IframeContents = IframeInner.contents();

                    YourNestedEl = IframeContents.find('div');

                    $('<div>Yeepi! I can even insert stuff!</div>').insertAfter(YourNestedEl)
                });
            });
        });
    </script>
</head>
<body>
    <div id="insertIframeAfter">Hello!!!!</div>
    <iframe id="frame1" src="Test_Iframe.html">

    </iframe>
</body>
</html>

As you can see, once the first Iframe is loaded, I get the second one and clone it. I then reinsert it in the dom, so I can get access to the onload event. Once this one is loaded, I retrieve the content from non-cloned one (must have loaded as well, since they use the same src). You can then do wathever you want with the content.

Here is the Test_Iframe.html file :

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div>Test_Iframe</div>
    <iframe src="Test_Iframe2.html">
    </iframe>
</body>
</html>

and the Test_Iframe2.html file :

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div>I am the second nested iframe</div>
</body>
</html>

Jenkins Host key verification failed

issue is with the /var/lib/jenkins/.ssh/known_hosts. It exists in the first case, but not in the second one. This means you are running either on different system or the second case is somehow jailed in chroot or by other means separated from the rest of the filesystem (this is a good idea for running random code from jenkins).

Next steps are finding out how are the chroots for this user created and modify the known hosts inside this chroot. Or just go other ways of ignoring known hosts, such as ssh-keyscan, StrictHostKeyChecking=no or so.

Find an element in DOM based on an attribute value

Here is an example , How to search images in a document by src attribute :

document.querySelectorAll("img[src='https://pbs.twimg.com/profile_images/........jpg']");

Include files from parent or other directory

In laymans terms, and practicality, I see this as an old DOS trick/thing. Whoa! What was that? DOS? Never heard of it!

".." backs you out of the current sub-directory one time to a higher folder/directory, and .. enter typed twice backs you out too 2 higher parent folders. Keep adding the ".. enter" back to back and you will soon find yourself at the top level of the directory.

As for Newbies to understand this better, consider this (in terms of the home PC or "C:\ drive" if you know what that means, rather than the web-servers/host "root directory" ). While your at it, Consider your website existing somewhere on your home PC's hard drive, buried in some folder under the C:\ drive. Lastly, you can think of it as ".." is back one directory and "/" is forward one directory/folder.

Now! If you are using the command prompt and are within the "myDocuments" folder of your PC you must back out of that folder to get closer to the higher directory "C:\" by typing the "../". If you wanted to access a file that is located in the widows directory while you are still in the myDocuments folder you would theoretically type ../windows; in reality of DOS command prompt you would simply type .., but I am setting you up for the web. The / redirects forward to another directory naturally.

Using "myDocuments" lets pretend that you created 2 folders within it called "PHP1" and "PHP2", in such we now have the folders:

  • C:\myDocuments\PHP1
  • C:\myDocuments\PHP2

In PHP1 you place a file called index.php. and in PHP2 folder you placed a file called Found.php. it now becomes:

  • C:\myDocuments\PHP1\index.php
  • C:\myDocuments\PHP2\found.php

Inside the C:\myDocuments\PHP1\index.php file you would need to edit and type something like:

<?php include ('../php2/found.php')?>

The ../ is positional thus it considers your current file location "C:\myDocuments\PHP1\index.php" and is a directive telling it to back out of PHP1 directory and enter or move forward into PHP2 directory to look for the Found.php file. But does it read it? See my thoughts on trouble shooting below.

Now! suppose you have 1 folder PHP1 and a sub-folder PHP2:

  • C:\myDocuments\PHP1\PHP2

you would simply reference/code

<?php include('/PHP2/found.php') ?>

as PHP2 exist as a sub-directory, below or within PHP1 directory.

If the above does not work it may have something to do with access/htaccess or permission to the directory or a typo. To enhance this...getting into trouble shooting...If the "found.php" file has errors/typo's within it, it will crash upon rendering at the error, such could be the reason (require/require_once) that you are experiencing the illusion that it is not changing directories or accessing the file. At last thought on the matter, you may need to instantiate your functions or references in order to use the included/require "whatever" by creating a new variable or object such as

$newObject = new nameobject("origianlThingy");

Remember, just because you are including/requiring something, sometimes means just that, it is included/required to run, but it might need to be recreated to make it active or access it. New will surely re-create an instance of it "if it is readable" and make it available within the current document while preserving the original. However you should reference the newly created variable $newObject in all instances....if its global.

To put this in perspective of some web host account; the web host is some whopping over sized hard-drive (like that on your PC) and your domain is nothing more than a folder they have assigned to you. Your folder is called the root. Inside that folder you can do anything you are allowed to do. your "one of many ways" to move between directories/folders is to use the ../ however many times to back out of your current in reference to folder position you want to find.

In my drunken state I realize that I know too much to be sane, and not enough to be insane!"

SQL Server - stop or break execution of a SQL script

I use RETURN here all the time, works in script or Stored Procedure

Make sure you ROLLBACK the transaction if you are in one, otherwise RETURN immediately will result in an open uncommitted transaction

Pandas index column title or name

The solution for multi-indexes is inside jezrael's cyclopedic answer, but it took me a while to find it so I am posting a new answer:

df.index.names gives the names of a multi-index (as a Frozenlist).

How may I align text to the left and text to the right in the same line?

?HTML:

<span class="right">Right aligned</span><span class="left">Left aligned</span>?

css:

.right{
    float:right;
}

.left{
    float:left;
}

Demo:
http://jsfiddle.net/W3Pxv/1

Concatenating strings in Razor

You can give like this....

<a href="@(IsProduction.IsProductionUrl)Index/LogOut">

In C/C++ what's the simplest way to reverse the order of bits in a byte?

Can this be fast solution?

int byte_to_be_reversed = 
    ((byte_to_be_reversed>>7)&0x01)|((byte_to_be_reversed>>5)&0x02)|      
    ((byte_to_be_reversed>>3)&0x04)|((byte_to_be_reversed>>1)&0x08)| 
    ((byte_to_be_reversed<<7)&0x80)|((byte_to_be_reversed<<5)&0x40)|
    ((byte_to_be_reversed<<3)&0x20)|((byte_to_be_reversed<<1)&0x10);

Gets rid of the hustle of using a for loop! but experts please tell me if this is efficient and faster?

sed whole word search and replace

Use \b for word boundaries:

sed -i 's/\boldtext\b/newtext/g' <file>

vertical alignment of text element in SVG

The alignment-baseline property is what you're looking for it can take the following values

auto | baseline | before-edge | text-before-edge | 
middle | central | after-edge | text-after-edge | 
ideographic | alphabetic | hanging | mathematical | 
inherit

Description from w3c

This property specifies how an object is aligned with respect to its parent. This property specifies which baseline of this element is to be aligned with the corresponding baseline of the parent. For example, this allows alphabetic baselines in Roman text to stay aligned across font size changes. It defaults to the baseline with the same name as the computed value of the alignment-baseline property. That is, the position of "ideographic" alignment-point in the block-progression-direction is the position of the "ideographic" baseline in the baseline-table of the object being aligned.

W3C Source

Unfortunately, although this is the "correct" way of achieving what you're after it would appear Firefox have not implemented a lot of the presentation attributes for the SVG Text Module ('SVG in Firefox' MDN Documentation)

Can't specify the 'async' modifier on the 'Main' method of a console app

class Program
{
     public static EventHandler AsyncHandler;
     static void Main(string[] args)
     {
        AsyncHandler+= async (sender, eventArgs) => { await AsyncMain(); };
        AsyncHandler?.Invoke(null, null);
     }

     private async Task AsyncMain()
     {
        //Your Async Code
     }
}

Regex to replace everything except numbers and a decimal point

Check the link Regular Expression Demo

use the below reg exp

[a-z] + [^0-9\s.]+|.(?!\d)

How does the compilation/linking process work?

The compilation of a C++ program involves three steps:

  1. Preprocessing: the preprocessor takes a C++ source code file and deals with the #includes, #defines and other preprocessor directives. The output of this step is a "pure" C++ file without pre-processor directives.

  2. Compilation: the compiler takes the pre-processor's output and produces an object file from it.

  3. Linking: the linker takes the object files produced by the compiler and produces either a library or an executable file.

Preprocessing

The preprocessor handles the preprocessor directives, like #include and #define. It is agnostic of the syntax of C++, which is why it must be used with care.

It works on one C++ source file at a time by replacing #include directives with the content of the respective files (which is usually just declarations), doing replacement of macros (#define), and selecting different portions of text depending of #if, #ifdef and #ifndef directives.

The preprocessor works on a stream of preprocessing tokens. Macro substitution is defined as replacing tokens with other tokens (the operator ## enables merging two tokens when it makes sense).

After all this, the preprocessor produces a single output that is a stream of tokens resulting from the transformations described above. It also adds some special markers that tell the compiler where each line came from so that it can use those to produce sensible error messages.

Some errors can be produced at this stage with clever use of the #if and #error directives.

Compilation

The compilation step is performed on each output of the preprocessor. The compiler parses the pure C++ source code (now without any preprocessor directives) and converts it into assembly code. Then invokes underlying back-end(assembler in toolchain) that assembles that code into machine code producing actual binary file in some format(ELF, COFF, a.out, ...). This object file contains the compiled code (in binary form) of the symbols defined in the input. Symbols in object files are referred to by name.

Object files can refer to symbols that are not defined. This is the case when you use a declaration, and don't provide a definition for it. The compiler doesn't mind this, and will happily produce the object file as long as the source code is well-formed.

Compilers usually let you stop compilation at this point. This is very useful because with it you can compile each source code file separately. The advantage this provides is that you don't need to recompile everything if you only change a single file.

The produced object files can be put in special archives called static libraries, for easier reusing later on.

It's at this stage that "regular" compiler errors, like syntax errors or failed overload resolution errors, are reported.

Linking

The linker is what produces the final compilation output from the object files the compiler produced. This output can be either a shared (or dynamic) library (and while the name is similar, they haven't got much in common with static libraries mentioned earlier) or an executable.

It links all the object files by replacing the references to undefined symbols with the correct addresses. Each of these symbols can be defined in other object files or in libraries. If they are defined in libraries other than the standard library, you need to tell the linker about them.

At this stage the most common errors are missing definitions or duplicate definitions. The former means that either the definitions don't exist (i.e. they are not written), or that the object files or libraries where they reside were not given to the linker. The latter is obvious: the same symbol was defined in two different object files or libraries.

Can I catch multiple Java exceptions in the same catch clause?

If there is a hierarchy of exceptions you can use the base class to catch all subclasses of exceptions. In the degenerate case you can catch all Java exceptions with:

try {
   ...
} catch (Exception e) {
   someCode();
}

In a more common case if RepositoryException is the the base class and PathNotFoundException is a derived class then:

try {
   ...
} catch (RepositoryException re) {
   someCode();
} catch (Exception e) {
   someCode();
}

The above code will catch RepositoryException and PathNotFoundException for one kind of exception handling and all other exceptions are lumped together. Since Java 7, as per @OscarRyz's answer above:

try { 
  ...
} catch( IOException | SQLException ex ) { 
  ...
}

How can javascript upload a blob?

Try this

var fd = new FormData();
fd.append('fname', 'test.wav');
fd.append('data', soundBlob);
$.ajax({
    type: 'POST',
    url: '/upload.php',
    data: fd,
    processData: false,
    contentType: false
}).done(function(data) {
       console.log(data);
});

You need to use the FormData API and set the jQuery.ajax's processData and contentType to false.

Add a column to a table, if it does not already exist

When checking for a column in another database, you can simply include the database name:

IF NOT EXISTS (
  SELECT * 
  FROM   DatabaseName.sys.columns 
  WHERE  object_id = OBJECT_ID(N'[DatabaseName].[dbo].[TableName]') 
         AND name = 'ColumnName'
)

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

difference between css height : 100% vs height : auto

height: 100% gives the element 100% height of its parent container.

height: auto means the element height will depend upon the height of its children.

Consider these examples:

height: 100%

<div style="height: 50px">
    <div id="innerDiv" style="height: 100%">
    </div>
</div>

#innerDiv is going to have height: 50px

height: auto

<div style="height: 50px">
    <div id="innerDiv" style="height: auto">
          <div id="evenInner" style="height: 10px">
          </div>
    </div>
</div>

#innerDiv is going to have height: 10px

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

We have fixed the issue by adding the following environment variable.

PYTHONPATH=${PYTHONPATH}:${PWD}/src:${PWD}/test

Upload file to FTP using C#

publish date: 06/26/2018

https://docs.microsoft.com/en-us/dotnet/framework/network-programming/how-to-upload-files-with-ftp

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
    public static void Main ()
    {
        // Get the object used to communicate with the server.
        FtpWebRequest request = 
(FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
        request.Method = WebRequestMethods.Ftp.UploadFile;

        // This example assumes the FTP site uses anonymous logon.
        request.Credentials = new NetworkCredential("anonymous", 
"[email protected]");

        // Copy the contents of the file to the request stream.
        byte[] fileContents;
        using (StreamReader sourceStream = new StreamReader("testfile.txt"))
        {
            fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        }

        request.ContentLength = fileContents.Length;

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(fileContents, 0, fileContents.Length);
        }

        using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
        {
            Console.WriteLine($"Upload File Complete, status 
{response.StatusDescription}");
        }
    }
}
}