Programs & Examples On #Safe bool idiom

Validate objects in a boolean context without harmful side effects caused by implicit conversions.

Where are the Properties.Settings.Default stored?

thanks for pointing me in the right direction. I found user.config located at this monstrosity: c:\users\USER\AppData\Local\COMPANY\APPLICATION.exe_Url_LOOKSLIKESOMEKINDOFHASH\VERSION\user.config.

I had to uprev the version on my application and all the settings seemed to have vanished. application created a new folder with the new version and used the default settings. took forever to find where the file was stored, but then it was a simple copy and paste to get the settings to the new version.

PyCharm shows unresolved references error for valid code

I have a project where one file in src/ imports another file in the same directory. To get PyCharm to recognize I had to to go to File > Settings > Project > Project Structure > select src folder and click "Mark as: Sources"

From https://www.jetbrains.com/help/pycharm/configuring-folders-within-a-content-root.html

Source roots contain the actual source files and resources. PyCharm uses the source roots as the starting point for resolving imports

How to change Windows 10 interface language on Single Language version

Actually, it looks like you may be able to download language packs directly through Windows Update. Open the old Control Panel by pressing WinKey+X and clicking Control Panel. Then go to Clock, Language, and Region > Add a language. Add the desired language. Then under the language it should say "Windows display language: Available". Click "Options" and then "Download and install language pack."

I'm not sure why this functionality appears to be less accessible than it was in Windows 8.

JavaScript variable assignments from tuples

Tuples aren't supported in JavaScript

If you're looking for an immutable list, Object.freeze() can be used to make an array immutable.

The Object.freeze() method freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object is made effectively immutable. The method returns the object being frozen.

Source: Mozilla Developer Network - Object.freeze()

Assign an array as usual but lock it using 'Object.freeze()

> tuple = Object.freeze(['Bob', 24]);
[ 'Bob', 24 ]

Use the values as you would a regular array (python multi-assignment is not supported)

> name = tuple[0]
'Bob'
> age = tuple[1]
24

Attempt to assign a new value

> tuple[0] = 'Steve'
'Steve'

But the value is not changed

> console.log(tuple)
[ 'Bob', 24 ]

SQL: how to use UNION and order by a specific select?

Using @Adrian tips, I found a solution:

I'm using GROUP BY and COUNT. I tried to use DISTINCT with ORDER BY but I'm getting error message: "not a SELECTed expression"

select id from 
(
    SELECT id FROM a -- returns 1,4,2,3
    UNION ALL -- changed to ALL
    SELECT id FROM b -- returns 2,1
)
GROUP BY id ORDER BY count(id);

Thanks Adrian and this blog.

How to save a git commit message from windows cmd?

I believe the REAL answer to this question is an explanation as to how you configure what editor to use by default, if you are not comfortable with Vim.

This is how to configure Notepad for example, useful in Windows:

git config --global core.editor "notepad"

Gedit, more Linux friendly:

git config --global core.editor "gedit"

You can read the current configuration like this:

git config core.editor

Cannot delete or update a parent row: a foreign key constraint fails

I think that your foreign key is backwards. Try:

ALTER TABLE 'jobs'
ADD CONSTRAINT `advertisers_ibfk_1` FOREIGN KEY (`advertiser_id`) REFERENCES `advertisers` (`advertiser_id`)

'str' object has no attribute 'decode'. Python 3 error?

It s already decoded in Python3, Try directly it should work.

How to group subarrays by a column value?

In a more functional programming style, you could use array_reduce

$groupedById = array_reduce($data, function (array $accumulator, array $element) {
  $accumulator[$element['id']][] = $element;

  return $accumulator;
}, []);

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

We have been solving the same problem just today, and all you need to do is to increase the runtime version of .NET

4.5.2 didn't work for us with the above problem, while 4.6.1 was OK

If you need to keep the .NET version, then set

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

How do I delete unpushed git commits?

If you want to move that commit to another branch, get the SHA of the commit in question

git rev-parse HEAD

Then switch the current branch

git checkout other-branch

And cherry-pick the commit to other-branch

git cherry-pick <sha-of-the-commit>

Google MAP API v3: Center & Zoom on displayed markers

I've also find this fix that zooms to fit all markers

LatLngList: an array of instances of latLng, for example:

// "map" is an instance of GMap3

var LatLngList = [
                     new google.maps.LatLng (52.537,-2.061), 
                     new google.maps.LatLng (52.564,-2.017)
                 ],
    latlngbounds = new google.maps.LatLngBounds();

LatLngList.forEach(function(latLng){
   latlngbounds.extend(latLng);
});

// or with ES6:
// for( var latLng of LatLngList)
//    latlngbounds.extend(latLng);

map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds); 

Angularjs $http post file and form data

I had similar problem when had to upload file and send user token info at the same time. transformRequest along with forming FormData helped:

        $http({
            method: 'POST',
            url: '/upload-file',
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            data: {
                email: Utils.getUserInfo().email,
                token: Utils.getUserInfo().token,
                upload: $scope.file
            },
            transformRequest: function (data, headersGetter) {
                var formData = new FormData();
                angular.forEach(data, function (value, key) {
                    formData.append(key, value);
                });

                var headers = headersGetter();
                delete headers['Content-Type'];

                return formData;
            }
        })
        .success(function (data) {

        })
        .error(function (data, status) {

        });

For getting file $scope.file I used custom directive:

app.directive('file', function () {
    return {
        scope: {
            file: '='
        },
        link: function (scope, el, attrs) {
            el.bind('change', function (event) {
                var file = event.target.files[0];
                scope.file = file ? file : undefined;
                scope.$apply();
            });
        }
    };
});

Html:

<input type="file" file="file" required />

Group a list of objects by an attribute

Function<Student, List<Object>> compositKey = std ->
                Arrays.asList(std.stud_location());
        studentList.stream().collect(Collectors.groupingBy(compositKey, Collectors.toList()));

If you want to add multiple objects for group by you can simply add the object in compositKey method separating by a comma:

Function<Student, List<Object>> compositKey = std ->
                Arrays.asList(std.stud_location(),std.stud_name());
        studentList.stream().collect(Collectors.groupingBy(compositKey, Collectors.toList()));

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

I experienced this soon after compiling and installing a shiny new GCC — version 8.1 — on RHEL 7. In the end, it ended up being a permissions problem; my root umask was the culprit. I eventually found cc1 hiding in /usr/local/libexec:

[root@nacelle gdb-8.1]# ls -l /usr/local/libexec/gcc/x86_64-pc-linux-gnu/8.1.0/ | grep cc1
-rwxr-xr-x 1 root root 196481344 Jul  2 13:53 cc1

However, the permissions on the directories leading there didn't allow my standard user account:

[root@nacelle gdb-8.1]# ls -l /usr/local/libexec/
total 4
drwxr-x--- 3 root root 4096 Jul  2 13:53 gcc
[root@nacelle gdb-8.1]# ls -l /usr/local/libexec/gcc/
total 4
drwxr-x--- 3 root root 4096 Jul  2 13:53 x86_64-pc-linux-gnu
[root@nacelle gdb-8.1]# ls -l /usr/local/libexec/gcc/x86_64-pc-linux-gnu/
total 4
drwxr-x--- 4 root root 4096 Jul  2 13:53 8.1.0

A quick recursive chmod to add world read/execute permissions fixed it right up:

[root@nacelle 8.1.0]# cd /usr/local/libexec
[root@nacelle lib]# ls -l | grep gcc
drwxr-x---  3 root root     4096 Jul  2 13:53 gcc
[root@nacelle lib]# chmod -R o+rx gcc
[root@nacelle lib]# ls -l | grep gcc
drwxr-xr-x  3 root root     4096 Jul  2 13:53 gcc

And now gcc can find cc1 when I ask it to compile something!

Check if a PHP cookie exists and if not set its value

Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.

Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

Source

How can one display images side by side in a GitHub README.md?

This solution allows you to add space in-between the images as well. It combines the best parts of all the existing solutions and doesn't add any ugly table borders.

<p align="center">
  <img alt="Light" src="https://...light.png" width="45%">
&nbsp; &nbsp; &nbsp; &nbsp;
  <img alt="Dark" src="https://...dark.png" width="45%">
</p>

The key is adding the &nbsp; non-breaking space HTML entities, which you can add and remove in order to customize the spacing.

You can see this example live on GitHub here.

Implement a simple factory pattern with Spring 3 annotations

You are right, by creating object manually you are not letting Spring to perform autowiring. Consider managing your services by Spring as well:

@Component
public class MyServiceFactory {

    @Autowired
    private MyServiceOne myServiceOne;

    @Autowired
    private MyServiceTwo myServiceTwo;

    @Autowired
    private MyServiceThree myServiceThree;

    @Autowired
    private MyServiceDefault myServiceDefault;

    public static MyService getMyService(String service) {
        service = service.toLowerCase();

        if (service.equals("one")) {
            return myServiceOne;
        } else if (service.equals("two")) {
            return myServiceTwo;
        } else if (service.equals("three")) {
            return myServiceThree;
        } else {
            return myServiceDefault;
        }
    }
}

But I would consider the overall design to be rather poor. Wouldn't it better to have one general MyService implementation and pass one/two/three string as extra parameter to checkStatus()? What do you want to achieve?

@Component
public class MyServiceAdapter implements MyService {

    @Autowired
    private MyServiceOne myServiceOne;

    @Autowired
    private MyServiceTwo myServiceTwo;

    @Autowired
    private MyServiceThree myServiceThree;

    @Autowired
    private MyServiceDefault myServiceDefault;

    public boolean checkStatus(String service) {
        service = service.toLowerCase();

        if (service.equals("one")) {
            return myServiceOne.checkStatus();
        } else if (service.equals("two")) {
            return myServiceTwo.checkStatus();
        } else if (service.equals("three")) {
            return myServiceThree.checkStatus();
        } else {
            return myServiceDefault.checkStatus();
        }
    }
}

This is still poorly designed because adding new MyService implementation requires MyServiceAdapter modification as well (SRP violation). But this is actually a good starting point (hint: map and Strategy pattern).

Creating dummy variables in pandas for python

So I was actually needing an answer to this question today (7/25/2013), so I wrote this earlier. I've tested it with some toy examples, hopefully you get some mileage out of it

def categorize_dict(x, y=0):
    # x Requires string or numerical input
    # y is a boolean that specifices whether to return category names along with the dict.
    # default is no
    cats = list(set(x))
    n = len(cats)
    m = len(x)
    outs = {}
    for i in cats:
        outs[i] = [0]*m
    for i in range(len(x)):
        outs[x[i]][i] = 1
    if y:
        return outs,cats
    return outs

How to use PHP with Visual Studio

Try Visual Studio Code. Very good support for PHP and other languages directly or via extensions. It can not replace power of Visual Studio but it is powerful addition to Visual Studio. And you can run it on all OS (Windows, Linux, Mac...).

https://code.visualstudio.com/

Why do we need the "finally" clause in Python?

The code blocks are not equivalent. The finally clause will also be run if run_code1() throws an exception other than TypeError, or if run_code2() throws an exception, while other_code() in the first version wouldn't be run in these cases.

How to SELECT a dropdown list item by value programmatically

Ian Boyd (above) had a great answer -- Add this to Ian Boyd's class "WebExtensions" to select an item in a dropdownlist based on text:

/// <summary>
/// Selects the item in the list control that contains the specified text, if it exists.
/// </summary>
/// <param name="dropDownList"></param>
/// <param name="selectedText">The text of the item in the list control to select</param>
/// <returns>Returns true if the value exists in the list control, false otherwise</returns>
public static Boolean SetSelectedText(this DropDownList dropDownList, String selectedText)
{
    ListItem selectedListItem = dropDownList.Items.FindByText(selectedText);
    if (selectedListItem != null)
    {
        selectedListItem.Selected = true;
        return true;
    }
    else
        return false;
}

To call it:

WebExtensions.SetSelectedText(MyDropDownList, "MyValue");

Create Word Document using PHP in Linux

OpenOffice templates + OOo command line interface.

  1. Create manually an ODT template with placeholders, like [%value-to-replace%]
  2. When instantiating the template with real data in PHP, unzip the template ODT (it's a zipped XML), and run against the XML the textual replace of the placeholders with the actual values.
  3. Zip the ODT back
  4. Run the conversion ODT -> DOC via OpenOffice command line interface.

There are tools and libraries available to ease each of those steps.

May be that helps.

Pass a PHP variable value through an HTML form

Try that

First place

global $var;
$var = 'value';

Second place

global $var;
if (isset($_POST['save_exit']))
{
    echo $var; 
}

Or if you want to be more explicit you can use the globals array:

$GLOBALS['var'] = 'test';

// after that
echo $GLOBALS['var'];

And here is third options which has nothing to do with PHP global that is due to the lack of clarity and information in the question. So if you have form in HTML and you want to pass "variable"/value to another PHP script you have to do the following:

HTML form

<form action="script.php" method="post">
    <input type="text" value="<?php echo $var?>" name="var" />
    <input type="submit" value="Send" />
</form>

PHP script ("script.php")

<?php

$var = $_POST['var'];
echo $var;

?>

plot with custom text for x axis points

You can manually set xticks (and yticks) using pyplot.xticks:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([0,1,2,3])
y = np.array([20,21,22,23])
my_xticks = ['John','Arnold','Mavis','Matt']
plt.xticks(x, my_xticks)
plt.plot(x, y)
plt.show()

"Correct" way to specifiy optional arguments in R functions

These are my rules of thumb:

If default values can be calculated from other parameters, use default expressions as in:

fun <- function(x,levels=levels(x)){
    blah blah blah
}

if otherwise using missing

fun <- function(x,levels){
    if(missing(levels)){
        [calculate levels here]
    }
    blah blah blah
}

In the rare case that you thing a user may want to specify a default value that lasts an entire R session, use getOption

fun <- function(x,y=getOption('fun.y','initialDefault')){# or getOption('pkg.fun.y',defaultValue)
    blah blah blah
}

If some parameters apply depending on the class of the first argument, use an S3 generic:

fun <- function(...)
    UseMethod(...)


fun.character <- function(x,y,z){# y and z only apply when x is character
   blah blah blah 
}

fun.numeric <- function(x,a,b){# a and b only apply when x is numeric
   blah blah blah 
}

fun.default <- function(x,m,n){# otherwise arguments m and n apply
   blah blah blah 
}

Use ... only when you are passing additional parameters on to another function

cat0 <- function(...)
    cat(...,sep = '')

Finally, if you do choose the use ... without passing the dots onto another function, warn the user that your function is ignoring any unused parameters since it can be very confusing otherwise:

fun <- (x,...){
    params <- list(...)
    optionalParamNames <- letters
    unusedParams <- setdiff(names(params),optionalParamNames)
    if(length(unusedParams))
        stop('unused parameters',paste(unusedParams,collapse = ', '))
   blah blah blah 
}

How to change background color of cell in table using java script

<table border="1" cellspacing="0" cellpadding= "20">
    <tr>
    <td id="id1" ></td>
    </tr>
</table>
<script>
    document.getElementById('id1').style.backgroundColor='#003F87';
</script>

Put id for cell and then change background of the cell.

how to destroy bootstrap modal window completely?

only this worked for me

$('body').on('hidden.bs.modal', '.modal', function() {
    $('selector').val('');
});

It is safe forcing selectors to make them blank since bootstrap and jquery version may be the reason of this problem

Difference between @click and v-on:click Vuejs

v-bind and v-on are two frequently used directives in vuejs html template. So they provided a shorthand notation for the both of them as follows:

You can replace v-on: with @

v-on:click='someFunction'

as:

@click='someFunction'

Another example:

v-on:keyup='someKeyUpFunction'

as:

@keyup='someKeyUpFunction'

Similarly, v-bind with :

v-bind:href='var1'

Can be written as:

:href='var1'

Hope it helps!

What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?

The key difference(noticed when reading the Spring Docs) between @Autowired and @Inject is that, @Autowired has the 'required' attribute while the @Inject has no 'required' attribute.

In C++ check if std::vector<string> contains a certain value

You can use std::find as follows:

if (std::find(v.begin(), v.end(), "abc") != v.end())
{
  // Element in vector.
}

To be able to use std::find: include <algorithm>.

How can I turn a DataTable to a CSV?

A new extension function based on Paul Grimshaw's answer. I cleaned it up and added the ability to handle unexpected data. (Empty Data, Embedded Quotes, and comma's in the headings...)

It also returns a string which is more flexible. It returns Null if the table object does not contain any structure.

    public static string ToCsv(this DataTable dataTable) {
        StringBuilder sbData = new StringBuilder();

        // Only return Null if there is no structure.
        if (dataTable.Columns.Count == 0)
            return null;

        foreach (var col in dataTable.Columns) {
            if (col == null)
                sbData.Append(",");
            else
                sbData.Append("\"" + col.ToString().Replace("\"", "\"\"") + "\",");
        }

        sbData.Replace(",", System.Environment.NewLine, sbData.Length - 1, 1);

        foreach (DataRow dr in dataTable.Rows) {
            foreach (var column in dr.ItemArray) {
                if (column == null)
                    sbData.Append(",");
                else
                    sbData.Append("\"" + column.ToString().Replace("\"", "\"\"") + "\",");
            }
            sbData.Replace(",", System.Environment.NewLine, sbData.Length - 1, 1);
        }

        return sbData.ToString();
    }

You call it as follows:

var csvData = dataTableOject.ToCsv();

How to get the CUDA version?

On Ubuntu Cuda V8:

$ cat /usr/local/cuda/version.txt

Git: list only "untracked" files (also, custom commands)

The accepted answer crashes on filenames with space. I'm at this point not sure how to update the alias command, so I'll put the improved version here:

git ls-files -z -o --exclude-standard | xargs -0 git add

How to calculate a time difference in C++

See std::clock() function.

const clock_t begin_time = clock();
// do something
std::cout << float( clock () - begin_time ) /  CLOCKS_PER_SEC;

If you want calculate execution time for self ( not for user ), it is better to do this in clock ticks ( not seconds ).

EDIT:
responsible header files - <ctime> or <time.h>

How to force a list to be vertical using html css

Hope this is your structure:

   <ul> 
     <li>
        <div ><img.. /><p>text</p></div>
    </li>
     <li>
        <div ><img.. /><p>text</p></div>
    </li>
     <li>
        <div ><img.. /><p>text</p></div>
    </li>
   </ul> 

By default, it will be add one after another row:

-----
-----
-----

if you want to make it vertical, just add float left to li, give width and height, make sure that content will not break the width:

|  |  |
|  |  |

li
{
   display:block;
   float:left;
   width:300px; /* adjust */
   height:150px; /* adjust */
   padding: 5px; /*adjust*/
}

Jquery resizing image

You can do this with the aeimageresize jquery plugin.

https://plugins.jquery.com/ae.image.resize

https://github.com/adeelejaz/jquery-image-resize

$(function() {
    $( ".resizeme" ).aeImageResize({ height: 250, width: 250 });
});

How to detect a textbox's content has changed

Use closures to remember what was the text in the checkbox before the key stroke and check whether this has changed.

Yep. You don't have to use closures necessarily, but you will need to remember the old value and compare it to the new.

However! This still won't catch every change, because there a ways of editing textbox content that do not involve any keypress. For example selecting a range of text then right-click-cut. Or dragging it. Or dropping text from another app into the textbox. Or changing a word via the browser's spell-check. Or...

So if you must detect every change, you have to poll for it. You could window.setInterval to check the field against its previous value every (say) second. You could also wire onkeyup to the same function so that changes that are caused by keypresses are reflected quicker.

Cumbersome? Yes. But it's that or just do it the normal HTML onchange way and don't try to instant-update.

java create date object using a value string

Here is the optimized solution to do it with SimpleDateFormat parse() method.

SimpleDateFormat formatter = new SimpleDateFormat(
        "EEEE, dd/MM/yyyy/hh:mm:ss");
String strDate = formatter.format(new Date());

try {
    Date pDate = formatter.parse(strDate);
} catch (ParseException e) { // note: parse method can throw ParseException
    e.printStackTrace();
}

Few things to notice

  • We don't need to create a Calendar instance to get the current date & time instead use new Date()
  • Also it doesn't require 2 instances of SimpleDateFormat as found in the most voted answer for this question. It's just a waste of memory
  • Furthermore, catching a generic exception like Exception is a bad practice when we know that the parse method only stands a chance to throw a ParseException. We need to be as specific as possible when dealing with Exceptions. You can refer, throws Exception bad practice?

Can I call methods in constructor in Java?

Better design would be

public static YourObject getMyObject(File configFile){
    //process and create an object configure it and return it
}

Can I use DIV class and ID together in CSS?

If you want to target a specific class and ID in CSS, then use a format like div.x#y {}.

Difference between $(this) and event.target?

this is a reference for the DOM element for which the event is being handled (the current target). event.target refers to the element which initiated the event. They were the same in this case, and can often be, but they aren't necessarily always so.

You can get a good sense of this by reviewing the jQuery event docs, but in summary:

event.currentTarget

The current DOM element within the event bubbling phase.

event.delegateTarget

The element where the currently-called jQuery event handler was attached.

event.relatedTarget

The other DOM element involved in the event, if any.

event.target

The DOM element that initiated the event.

To get the desired functionality using jQuery, you must wrap it in a jQuery object using either: $(this) or $(evt.target).

The .attr() method only works on a jQuery object, not on a DOM element. $(evt.target).attr('href') or simply evt.target.href will give you what you want.

Laravel 5 Application Key

From the line

'key' => env('APP_KEY', 'SomeRandomString'),

APP_KEY is a global environment variable that is present inside the .env file.

You can replace the application key if you trigger

php artisan key:generate

command. This will always generate the new key.

The output may be like this:


Application key [Idgz1PE3zO9iNc0E3oeH3CHDPX9MzZe3] set successfully.

Application key [base64:uynE8re8ybt2wabaBjqMwQvLczKlDSQJHCepqxmGffE=] set successfully.

Base64 encoding should be the default in Laravel 5.4

Note that when you first create your Laravel application, key:generate is automatically called.

If you change the key be aware that passwords saved with Hash::make() will no longer be valid.

get keys of json-object in JavaScript

The working code

_x000D_
_x000D_
var jsonData = [{person:"me", age :"30"},{person:"you",age:"25"}];_x000D_
_x000D_
for(var obj in jsonData){_x000D_
    if(jsonData.hasOwnProperty(obj)){_x000D_
    for(var prop in jsonData[obj]){_x000D_
        if(jsonData[obj].hasOwnProperty(prop)){_x000D_
           alert(prop + ':' + jsonData[obj][prop]);_x000D_
        }_x000D_
    }_x000D_
}_x000D_
}
_x000D_
_x000D_
_x000D_

Python truncate a long string

limit = 75
info = data[:limit] + '..' * (len(data) > limit)

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
Out[80]:
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
Out[81]:
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
Out[82]:
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

How to empty/destroy a session in rails?

add this code to your ApplicationController

def reset_session
  @_request.reset_session
end

( Dont know why no one above just mention this code as it fixed my problem ) http://apidock.com/rails/ActionController/RackDelegation/reset_session

Firebase onMessageReceived not called when app in background

you can try this in your main Activity , when in the background

   if (getIntent().getExtras() != null) {
            for (String key : getIntent().getExtras().keySet()) {
                Object value = getIntent().getExtras().get(key);
                Log.d(TAG, "Key: " + key + " Value: " + value);
            }
        }

Check the following project as reference

Maintaining the final state at end of a CSS3 animation

Try adding animation-fill-mode: forwards;. For example like this:

-webkit-animation: bubble 1.0s forwards; /* for less modern browsers */
        animation: bubble 1.0s forwards;

Html encode in PHP

By encode, do you mean: Convert all applicable characters to HTML entities?

htmlspecialchars or htmlentities

You can also use strip_tags if you want to remove all HTML tags :

strip_tags

Note: this will NOT stop all XSS attacks

Get the size of a 2D array

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

How to detect my browser version and operating system using JavaScript?

Code to detect the operating system of an user

let os = navigator.userAgent.slice(13).split(';')
os = os[0]
console.log(os)
Windows NT 10.0

Unsupported operation :not writeable python

file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))

This is solve your encode error also.

Bootstrap control with multiple "data-toggle"

One more solution:

    <a data-toggle="modal" data-target="#exampleModalCenter">
      <span
        class="tags"
        data-toggle="tooltip"
        data-placement="right"
        title="Tooltip text"
      >
        Text
     </span>
   </a>

RestTemplate: How to send URL and query parameters together

One simple way to do that is:

String url = "http://test.com/Services/rest/{id}/Identifier"

UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
uriComponents = uriComponents.expand(Collections.singletonMap("id", "1234"));

and then adds the query params.

How to pass a list from Python, by Jinja2 to JavaScript

I can suggest you a javascript oriented approach which makes it easy to work with javascript files in your project.

Create a javascript section in your jinja template file and place all variables you want to use in your javascript files in a window object:

Start.html

...
{% block scripts %}
<script type="text/javascript">
window.appConfig = {
    debug: {% if env == 'development' %}true{% else %}false{% endif %},
    facebook_app_id: {{ facebook_app_id }},
    accountkit_api_version: '{{ accountkit_api_version }}',
    csrf_token: '{{ csrf_token }}'
}
</script>
<script type="text/javascript" src="{{ url_for('static', filename='app.js') }}"></script>
{% endblock %}

Jinja will replace values and our appConfig object will be reachable from our other script files:

App.js

var AccountKit_OnInteractive = function(){
    AccountKit.init({
        appId: appConfig.facebook_app_id,
        debug: appConfig.debug,
        state: appConfig.csrf_token,
        version: appConfig.accountkit_api_version
    })
}

I have seperated javascript code from html documents with this way which is easier to manage and seo friendly.

Disable sorting for a particular column in jQuery DataTables

Here is what you can use to disable certain column to be disabled:

 $('#tableId').dataTable({           
            "columns": [
                { "data": "id"},
                { "data": "sampleSortableColumn" },
                { "data": "otherSortableColumn" },
                { "data": "unsortableColumn", "orderable": false}
           ]
});

So all you have to do is add the "orderable": false to the column you don't want to be sortable.

syntax for creating a dictionary into another dictionary in python

Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?

Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.

To re-reference the values of one dictionary into another, you can use dict.update:

>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}

A change to a value that's present in both dictionaries will be visible in both:

>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}

This is the same as copying the value over or making a new dictionary with it, i.e.

>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

With lodash, in addition to the answer provided above, you can also have the key in the output array.

Without the object keys in the output array

for:

const array = _.values(obj);

If obj is the following:

{ “art”: { id: 1,  title: “aaaa” }, “fiction”: { id: 22,  title: “7777”} }

Then array will be:

[ { id: 1, title: “aaaa” }, { id: 22, title: “7777” } ]

With the object keys in the output array

If you write instead ('genre' is a string that you choose):

const array= _.map(obj, (val, id) => {
    return { ...val, genre: key };
  });

You will get:

[ 
  { id: 1, title: “aaaa” , genre: “art”}, 
  { id: 22, title: “7777”, genre: “fiction” }
]

How to uninstall/upgrade Angular CLI?

I always use the following commands before upgrading to latest . If it is for Ubuntu prefix : 'sudo'

npm uninstall -g angular-cli
npm cache clean
npm install -g angular-cli@latest

How to set a default entity property value with Hibernate

Working with Oracle, I was trying to insert a default value for an Enum

I found the following to work the best.

@Column(nullable = false)
@Enumerated(EnumType.STRING)
private EnumType myProperty = EnumType.DEFAULT_VALUE;

Get DataKey values in GridView RowCommand

you can just do this:

string id = GridName.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();

Git log to get commits only for a specific branch

I needed to export log in one line for a specific branch.

So I probably came out with a simpler solution.
When doing git log --pretty=oneline --graph we can see that all commit not done in the current branch are lines starting with |

So a simple grep -v do the job:
git log --pretty=oneline --graph | grep -v "^|"

Of course you can change the pretty parameter if you need other info, as soon as you keep it in one line.

You probably want to remove merge commit too.
As the message start with "Merge branch", pipe another grep -v and you're done.

In my specific ase, the final command was:
git log --pretty="%ad : %an, %s" --graph | grep -v "^|" | grep -v "Merge branch"

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

but as for this method, I don't understand the purpose of Integer.MAX_VALUE and Integer.MIN_VALUE.

By starting out with smallest set to Integer.MAX_VALUE and largest set to Integer.MIN_VALUE, they don't have to worry later about the special case where smallest and largest don't have a value yet. If the data I'm looking through has a 10 as the first value, then numbers[i]<smallest will be true (because 10 is < Integer.MAX_VALUE) and we'll update smallest to be 10. Similarly, numbers[i]>largest will be true because 10 is > Integer.MIN_VALUE and we'll update largest. And so on.

Of course, when doing this, you must ensure that you have at least one value in the data you're looking at. Otherwise, you end up with apocryphal numbers in smallest and largest.


Note the point Onome Sotu makes in the comments:

...if the first item in the array is larger than the rest, then the largest item will always be Integer.MIN_VALUE because of the else-if statement.

Which is true; here's a simpler example demonstrating the problem (live copy):

public class Example
{
    public static void main(String[] args) throws Exception {
        int[] values = {5, 1, 2};
        int smallest = Integer.MAX_VALUE;
        int largest  = Integer.MIN_VALUE;
        for (int value : values) {
            if (value < smallest) {
                smallest = value;
            } else if (value > largest) {
                largest = value;
            }
        }
        System.out.println(smallest + ", " + largest); // 1, 2 -- WRONG
    }
}

To fix it, either:

  1. Don't use else, or

  2. Start with smallest and largest equal to the first element, and then loop the remaining elements, keeping the else if.

Here's an example of that second one (live copy):

public class Example
{
    public static void main(String[] args) throws Exception {
        int[] values = {5, 1, 2};
        int smallest = values[0];
        int largest  = values[0];
        for (int n = 1; n < values.length; ++n) {
            int value = values[n];
            if (value < smallest) {
                smallest = value;
            } else if (value > largest) {
                largest = value;
            }
        }
        System.out.println(smallest + ", " + largest); // 1, 5
    }
}

Convert textbox text to integer

If your SQL database allows Null values for that field try using int? value like that :

if (this.txtboxname.Text == "" || this.txtboxname.text == null)
     value = null;
else
     value = Convert.ToInt32(this.txtboxname.Text);

Take care that Convert.ToInt32 of a null value returns 0 !

Convert.ToInt32(null) returns 0

How to know if an object has an attribute in Python

Try hasattr():

if hasattr(a, 'property'):
    a.property

EDIT: See zweiterlinde's answer below, who offers good advice about asking forgiveness! A very pythonic approach!

The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except block. This will likely be faster than hasattr. If the property is likely to not be there most of the time, or you're not sure, using hasattr will probably be faster than repeatedly falling into an exception block.

How to create a link to another PHP page

Use like this

<a href="index.php">Index Page</a>
<a href="page2.php">Page 2</a>

Formatting PowerShell Get-Date inside string

"This is my string with date in specified format $($theDate.ToString('u'))"

or

"This is my string with date in specified format $(Get-Date -format 'u')"

The sub-expression ($(...)) can include arbitrary expressions calls.

MSDN Documents both standard and custom DateTime format strings.

Delete multiple rows by selecting checkboxes using PHP

<?php $sql = "SELECT * FROM guest_book";
                            $res = mysql_query($sql);
                            if (mysql_num_rows($res)) {
                            $query = mysql_query("SELECT * FROM guest_book ORDER BY id");
                            $i=1;
                            while($row = mysql_fetch_assoc($query)){
                            ?>


<input type="checkbox" name="checkboxstatus[<?php echo $i; ?>]" value="<?php echo $row['id']; ?>"  />

<?php $i++; }} ?>


<input type="submit" value="Delete" name="Delete" />

if($_REQUEST['Delete'] != '')
{
    if(!empty($_REQUEST['checkboxstatus'])) {
        $checked_values = $_REQUEST['checkboxstatus'];
        foreach($checked_values as $val) {
            $sqldel = "DELETE from guest_book WHERE id = '$val'";
           mysql_query($sqldel);

        }
    }
} 

Transparent ARGB hex value

Transparency is controlled by the alpha channel (AA in #AARRGGBB). Maximal value (255 dec, FF hex) means fully opaque. Minimum value (0 dec, 00 hex) means fully transparent. Values in between are semi-transparent, i.e. the color is mixed with the background color.

To get a fully transparent color set the alpha to zero. RR, GG and BB are irrelevant in this case because no color will be visible. This means #00FFFFFF ("transparent White") is the same color as #00F0F8FF ("transparent AliceBlue"). To keep it simple one chooses black (#00000000) or white (#00FFFFFF) if the color does not matter.

In the table you linked to you'll find Transparent defined as #00FFFFFF.

month name to month number and vice versa in python

Building on ideas expressed above, This is effective for changing a month name to its appropriate month number:

from time import strptime
monthWord = 'september'

newWord = monthWord [0].upper() + monthWord [1:3].lower() 
# converted to "Sep"

print(strptime(newWord,'%b').tm_mon) 
# "Sep" converted to "9" by strptime

What is the newline character in the C language: \r or \n?

It's \n. When you're reading or writing text mode files, or to stdin/stdout etc, you must use \n, and C will handle the translation for you. When you're dealing with binary files, by definition you are on your own.

Sending E-mail using C#

You could use the System.Net.Mail.MailMessage class of the .NET framework.

You can find the MSDN documentation here.

Here is a simple example (code snippet):

using System.Net;
using System.Net.Mail;
using System.Net.Mime;

...
try
{

   SmtpClient mySmtpClient = new SmtpClient("my.smtp.exampleserver.net");

    // set smtp-client with basicAuthentication
    mySmtpClient.UseDefaultCredentials = false;
   System.Net.NetworkCredential basicAuthenticationInfo = new
      System.Net.NetworkCredential("username", "password");
   mySmtpClient.Credentials = basicAuthenticationInfo;

   // add from,to mailaddresses
   MailAddress from = new MailAddress("[email protected]", "TestFromName");
   MailAddress to = new MailAddress("[email protected]", "TestToName");
   MailMessage myMail = new System.Net.Mail.MailMessage(from, to);

   // add ReplyTo
   MailAddress replyTo = new MailAddress("[email protected]");
   myMail.ReplyToList.Add(replyTo);

   // set subject and encoding
   myMail.Subject = "Test message";
   myMail.SubjectEncoding = System.Text.Encoding.UTF8;

   // set body-message and encoding
   myMail.Body = "<b>Test Mail</b><br>using <b>HTML</b>.";
   myMail.BodyEncoding = System.Text.Encoding.UTF8;
   // text or html
   myMail.IsBodyHtml = true;

   mySmtpClient.Send(myMail);
}

catch (SmtpException ex)
{
  throw new ApplicationException
    ("SmtpException has occured: " + ex.Message);
}
catch (Exception ex)
{
   throw ex;
}

Typescript: How to extend two classes?

I found an up-to-date & unparalleled solution: https://www.npmjs.com/package/ts-mixer

You are welcome :)

How to insert special characters into a database?

Are you escaping? Try the mysql_real_escape_string() function and it will handle the special characters.

Accessing Imap in C#

MailSystem.NET contains all your need for IMAP4. It's free & open source.

(I'm involved in the project)

How to initialize a vector with fixed length in R

The initialization method easiest to remember is

vec = vector(,10); #the same as "vec = vector(length = 10);"

The values of vec are: "[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE" (logical mode) by default.

But after setting a character value, like

vec[2] = 'abc'

vec becomes: "FALSE" "abc" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE"", which is of the character mode.

Instantiating a generic type

No, and the fact that you want to seems like a bad idea. Do you really need a default constructor like this?

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

I resolve this is by changing the version no of recyleview to recyclerview-v7:24.2.1. Please check your dependencies and use the proper version number.

TSQL PIVOT MULTIPLE COLUMNS

Since you want to pivot multiple columns of data, I would first suggest unpivoting the result, score and grade columns so you don't have multiple columns but you will have multiple rows.

Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:

select ratio, col, value
from GRAND_TOTALS
cross apply
(
  select 'result', cast(result as varchar(10)) union all
  select 'score', cast(score as varchar(10)) union all
  select 'grade', grade
) c(col, value)

See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:

select ratio = col,
  [current ratio], [gearing ratio], [performance ratio], total
from
(
  select ratio, col, value
  from GRAND_TOTALS
  cross apply
  (
    select 'result', cast(result as varchar(10)) union all
    select 'score', cast(score as varchar(10)) union all
    select 'grade', grade
  ) c(col, value)
) d
pivot
(
  max(value)
  for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;

See SQL Fiddle with Demo. This will give you the result:

|  RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO |     TOTAL |
|--------|---------------|---------------|-------------------|-----------|
|  grade |          Good |          Good |      Satisfactory |      Good |
| result |       1.29400 |       0.33840 |           0.04270 |    (null) |
|  score |      60.00000 |      70.00000 |          50.00000 | 180.00000 |

How do I configure the proxy settings so that Eclipse can download new plugins?

For me, I go to \eclipse\configuration.settings\org.eclipse.core.net.prefs set the property systemProxiesEnabled to true manually and restart eclipse.

Using sed, how do you print the first 'N' characters of a line?

How about head ?

echo alonglineoftext | head -c 9

CASE statement in SQLite query

Also, you do not have to use nested CASEs. You can use several WHEN-THEN lines and the ELSE line is also optional eventhough I recomend it

CASE 
   WHEN [condition.1] THEN [expression.1]
   WHEN [condition.2] THEN [expression.2]
   ...
   WHEN [condition.n] THEN [expression.n]
   ELSE [expression] 
END

Use jQuery to change value of a label

val() is more like a shortcut for attr('value'). For your usage use text() or html() instead

Is there a way to override class variables in Java?

Yes. But as the variable is concerned it is overwrite (Giving new value to variable. Giving new definition to the function is Override). Just don't declare the variable but initialize (change) in the constructor or static block.

The value will get reflected when using in the blocks of parent class

if the variable is static then change the value during initialization itself with static block,

class Son extends Dad {
    static { 
       me = "son"; 
    }
}

or else change in constructor.

You can also change the value later in any blocks. It will get reflected in super class

What are the differences between virtual memory and physical memory?

Virtual memory is, among other things, an abstraction to give the programmer the illusion of having infinite memory available on their system.

Virtual memory mappings are made to correspond to actual physical addresses. The operating system creates and deals with these mappings - utilizing the page table, among other data structures to maintain the mappings. Virtual memory mappings are always found in the page table or some similar data structure (in case of other implementations of virtual memory, we maybe shouldn't call it the "page table"). The page table is in physical memory as well - often in kernel-reserved spaces that user programs cannot write over.

Virtual memory is typically larger than physical memory - there wouldn't be much reason for virtual memory mappings if virtual memory and physical memory were the same size.

Only the needed part of a program is resident in memory, typically - this is a topic called "paging". Virtual memory and paging are tightly related, but not the same topic. There are other implementations of virtual memory, such as segmentation.

I could be assuming wrong here, but I'd bet the things you are finding hard to wrap your head around have to do with specific implementations of virtual memory, most likely paging. There is no one way to do paging - there are many implementations and the one your textbook describes is likely not the same as the one that appears in real OSes like Linux/Windows - there are probably subtle differences.

I could blab a thousand paragraphs about paging... but I think that is better left to a different question targeting specifically that topic.

How to underline a UILabel in swift?

I have algorithm that used in my app. In this algorithm you can underline substring even that have space between words

extension NSMutableAttributedString{

    static func  findSubStringAndUnderlineIt(subStringToBeFound : String,totalString : String)->  NSMutableAttributedString?{
        
        let attributedString = NSMutableAttributedString(string: totalString)

        var spaceCount = 0
        
        if subStringToBeFound.contains(" "){
            spaceCount = subStringToBeFound.components(separatedBy:" ").count-1
        }

        
        if  let range = attributedString.string.range(of: subStringToBeFound, options: .caseInsensitive){
        
            attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange((range.lowerBound.utf16Offset(in: subStringToBeFound)) ,(range.upperBound.utf16Offset(in: subStringToBeFound)) +
            spaceCount))
                return attributedString
        }
        return attributedString
        
    }
    
}

in used section

 lblWarning.attributedText = NSMutableAttributedString.findSubStringAndUnderlineIt(subStringToBeFound:"Not: Sadece uygulamanin reklamlari kaldirilacaktir.", totalString: lblWarning.text!)

ReactJS: setTimeout() not working?

Do

setTimeout(
    function() {
        this.setState({ position: 1 });
    }
    .bind(this),
    3000
);

Otherwise, you are passing the result of setState to setTimeout.

You can also use ES6 arrow functions to avoid the use of this keyword:

setTimeout(
  () => this.setState({ position: 1 }), 
  3000
);

Java resource as file

Try this:

ClassLoader.getResourceAsStream ("some/pkg/resource.properties");

There are more methods available, e.g. see here: http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html

Android - Launcher Icon Size

I would create separate images for each one:

LDPI should be 36 x 36.

MDPI should be 48 x 48.

TVDPI should be 64 x 64.

HDPI should be 72 x 72.

XHDPI should be 96 x 96.

XXHDPI should be 144 x 144.

XXXHDPI should be 192 x 192.

Then just put each of them in the separate stalks of the drawable folder.

You are also required to give a large version of your icon when uploading your app onto the Google Play Store and this should be WEB 512 x 512. This is so large so that Google can rescale it to any size in order to advertise your app throughout the Google Play Store and not add pixelation to your logo.

Basically, all of the other icons should be in proportion to the 'baseline' icon, MDPI at 48 x 48.

LDPI is MDPI x 0.75.

TVDPI is MDPI x 1.33.

HDPI is MDPI x 1.5.

XHDPI is MDPI x 2.

XXHDPI is MDPI x 3.

XXXHDPI is MDPI x 4.

This is all explained on the Iconography page of the Android Developers website: http://developer.android.com/design/style/iconography.html

Sending Arguments To Background Worker?

Even though this is an already answered question, I'd leave another option that IMO is a lot easier to read:

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, e) => WorkerDoWork(value, text);
worker.RunWorkerAsync();

And on the handler method:

private void WorkerDoWork(int value, string text) {
    ...
}

Using a scanner to accept String input and storing in a String Array

Please correct me if I'm wrong.`

public static void main(String[] args) {

    Scanner na = new Scanner(System.in);
    System.out.println("Please enter the number of contacts: ");
    int num = na.nextInt();

    String[] contactName = new String[num];
    String[] contactPhone = new String[num];
    String[] contactAdd1 = new String[num];
    String[] contactAdd2 = new String[num];

    Scanner input = new Scanner(System.in);

    for (int i = 0; i < num; i++) {

        System.out.println("Enter contacts name: " + (i+1));
        contactName[i] = input.nextLine();

        System.out.println("Enter contacts addressline1: " + (i+1));
        contactAdd1[i] = input.nextLine();

        System.out.println("Enter contacts addressline2: " + (i+1));
        contactAdd2[i] = input.nextLine();

        System.out.println("Enter contact phone number: " + (i+1));
        contactPhone[i] = input.nextLine();

    }

    for (int i = 0; i < num; i++) {
        System.out.println("Contact Name No." + (i+1) + " is "+contactName[i]);
        System.out.println("First Contacts Address No." + (i+1) + " is "+contactAdd1[i]);
        System.out.println("Second Contacts Address No." + (i+1) + " is "+contactAdd2[i]);
        System.out.println("Contact Phone Number No." + (i+1) + " is "+contactPhone[i]);
    }
}

`

convert a JavaScript string variable to decimal/money

It is fairly risky to rely on javascript functions to compare and play with numbers. In javascript (0.1+0.2 == 0.3) will return false due to rounding errors. Use the math.js library.

How to use Chrome's network debugger with redirects

I don't know of a way to force Chrome to not clear the Network debugger, but this might accomplish what you're looking for:

  1. Open the js console
  2. window.addEventListener("beforeunload", function() { debugger; }, false)

This will pause chrome before loading the new page by hitting a breakpoint.

Rails: How to list database tables/objects using the Rails console?

To get a list of all model classes, you can use ActiveRecord::Base.subclasses e.g.

ActiveRecord::Base.subclasses.map { |cl| cl.name }
ActiveRecord::Base.subclasses.find { |cl| cl.name == "Foo" }

How to count the number of lines of a string in javascript

There are three options:

Using jQuery (download from jQuery website) - jquery.com

var lines = $("#ptest").val().split("\n");
return lines.length;

Using Regex

var lines = str.split(/\r\n|\r|\n/);
return lines.length;

Or, a recreation of a for each loop

var length = 0;
for(var i = 0; i < str.length; ++i){
    if(str[i] == '\n') {
        length++;
    }
}
return length;

Disable button in WPF?

In MVVM (wich makes a lot of things a lot easier - you should try it) you would have two properties in your ViewModel Text that is bound to your TextBox and you would have an ICommand property Apply (or similar) that is bound to the button:

<Button Command="Apply">Apply</Button>

The ICommand interface has a Method CanExecute that is where you return true if (!string.IsNullOrWhiteSpace(this.Text). The rest is done by WPF for you (enabling/disabling, executing the actual command on click).

The linked article explains it in detail.

How to filter WooCommerce products by custom attribute

You can use the WooCommerce Layered Nav widget, which allows you to use different sets of attributes as filters for products. Here's the "official" description:

Shows a custom attribute in a widget which lets you narrow down the list of products when viewing product categories.

If you look into plugins/woocommerce/widgets/widget-layered_nav.php, you can see the way it operates with the attributes in order to set filters. The URL then looks like this:

http://yoursite.com/shop/?filtering=1&filter_min-kvadratura=181&filter_max-kvadratura=108&filter_obem-ohlajdane=111

... and the digits are actually the id-s of the different attribute values, that you want to set.

Find out whether radio button is checked with JQuery?

... Thanks guys... all I needed was the 'value' of the checked radio button where each radio button in the set had a different id...

 var user_cat = $("input[name='user_cat']:checked").val();

works for me...

Scanner method to get a char

You can use the Console API (which made its appearance in Java 6) as follows:

Console cons = System.console();
if(cons != null) {
  char c = (char) cons.reader().read();  // Checking for EOF omitted
  ...
}

If you just need a single line you don't even need to go through the reader object:

String s = cons.readLine();

Error: Execution failed for task ':app:clean'. Unable to delete file

In my case node.js was using some resources in build folder (my app in reactnative). So I killed node.js and it solved.

Go test string contains substring

Use the function Contains from the strings package.

import (
    "strings"
)
strings.Contains("something", "some") // true

Most efficient way to prepend a value to an array

Calling unshift only returns the length of the new array. So, to add an element in the beginning and to return a new array, I did this:

let newVal = 'someValue';
let array = ['hello', 'world'];
[ newVal ].concat(array);

or simply with spread operator:

[ newVal, ...array ]

This way, the original array remains untouched.

Should I use PATCH or PUT in my REST API?

The PATCH method is the correct choice here as you're updating an existing resource - the group ID. PUT should only be used if you're replacing a resource in its entirety.

Further information on partial resource modification is available in RFC 5789. Specifically, the PUT method is described as follows:

Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

Pipenv: Command Not Found

Installing pipenv globally can have an adverse effect by overwriting the global/system-managed pip installation, thus resulting in import errors when trying to run pip.

You can install pipenv at the user level:

pip install --user pipenv

This should install pipenv at a user-level in /home/username/.local so that it does not conflict with the global version of pip. In my case, that still did not work after running the '--user' switch, so I ran the longer 'fix what I screwed up' command once to restore the system managed environment:

sudo python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall

^ found here: Error after upgrading pip: cannot import name 'main'

and then did the following:

mkdir /home/username/.local ... if it doesn't already exist

export PYTHONUSERBASE=/home/username/.local

Make sure the export took effect (bit me once during this process):

echo $PYTHONUSERBASE

Then, I ran the pip install --user pipenv and all was well. I could then run pipenv from the CLI and it did not overwrite the global/system-managed pip module. Of course, this is specific to the user so you want to make sure you install pipenv this way while working as the user you wish to use pipenv.

References:

https://pipenv.readthedocs.io/en/latest/diagnose/#no-module-named-module-name https://pipenv.readthedocs.io/en/latest/install/#pragmatic-installation-of-pipenv https://pip.pypa.io/en/stable/user_guide/#user-installs

php execute a background process

I'd just like to add a very simple example for testing this functionality on Windows:

Create the following two files and save them to a web directory:

foreground.php:

<?php

ini_set("display_errors",1);
error_reporting(E_ALL);

echo "<pre>loading page</pre>";

function run_background_process()
{
    file_put_contents("testprocesses.php","foreground start time = " . time() . "\n");
    echo "<pre>  foreground start time = " . time() . "</pre>";

    // output from the command must be redirected to a file or another output stream 
    // http://ca.php.net/manual/en/function.exec.php

    exec("php background.php > testoutput.php 2>&1 & echo $!", $output);

    echo "<pre>  foreground end time = " . time() . "</pre>";
    file_put_contents("testprocesses.php","foreground end time = " . time() . "\n", FILE_APPEND);
    return $output;
}

echo "<pre>calling run_background_process</pre>";

$output = run_background_process();

echo "<pre>output = "; print_r($output); echo "</pre>";
echo "<pre>end of page</pre>";
?>

background.php:

<?
file_put_contents("testprocesses.php","background start time = " . time() . "\n", FILE_APPEND);
sleep(10);
file_put_contents("testprocesses.php","background end time = " . time() . "\n", FILE_APPEND);
?>

Give IUSR permission to write to the directory in which you created the above files

Give IUSR permission to READ and EXECUTE C:\Windows\System32\cmd.exe

Hit foreground.php from a web browser

The following should be rendered to the browser w/the current timestamps and local resource # in the output array:

loading page
calling run_background_process
  foreground start time = 1266003600
  foreground end time = 1266003600
output = Array
(
    [0] => 15010
)
end of page

You should see testoutput.php in the same directory as the above files were saved, and it should be empty

You should see testprocesses.php in the same directory as the above files were saved, and it should contain the following text w/the current timestamps:

foreground start time = 1266003600
foreground end time = 1266003600
background start time = 1266003600
background end time = 1266003610

File Upload using AngularJS

<form id="csv_file_form" ng-submit="submit_import_csv()" method="POST" enctype="multipart/form-data">
    <input ng-model='file' type="file"/>
    <input type="submit" value='Submit'/>
</form>

In angularJS controller

$scope.submit_import_csv = function(){

        var formData = new FormData(document.getElementById("csv_file_form"));
        console.log(formData);

        $.ajax({
            url: "import",
            type: 'POST',
            data:  formData,
            mimeType:"multipart/form-data",
            contentType: false,
            cache: false,
            processData:false,
            success: function(result, textStatus, jqXHR)
            {
            console.log(result);
            }
        });

        return false;
    }

Heroku deployment error H10 (App crashed)

See if you get

bash: bin/rails: No such file or directory

in logs while running (heroku logs -t) command if yes then please Run

bundle exec rake rails:update

Don't overwrite your files, in the end this command will create

  create  bin
  create  bin/bundle
  create  bin/rails
  create  bin/rake

push these files to heroku and you are done.

a href link for entire div in HTML/CSS

put display:block on the anchor element. and/or zoom:1;

but you should just really do this.

a#parentdivimage{position:relative; width:184px; height:235px; 
                 border:2px solid #000; text-align:center; 
                 background-image:url("myimage.jpg"); 
                 background-position: 50% 50%; 
                 background-repeat:no-repeat; display:block; 
                 text-indent:-9999px}

<a id="parentdivimage">whatever your alt attribute was</a>

Insert data using Entity Framework model

var context = new DatabaseEntities();

var t = new test //Make sure you have a table called test in DB
{
    ID = Guid.NewGuid(),
    name = "blah",
};

context.test.Add(t);
context.SaveChanges();

Should do it

Tesseract OCR simple example

This worked for me, I had 3-4 more PDF to Text extractor and if one doesnot work the other one will ... tesseract in particular this code can be used on Windows 7, 8, Server 2008 . Hope this is helpful to you

    do
    {
    // Sleep or Pause the Thread for 1 sec, if service is running too fast...
    Thread.Sleep(millisecondsTimeout: 1000);
    Guid tempGuid = ToSeqGuid();
    string newFileName = tempGuid.ToString().Split('-')[0];
    string outputFileName = appPath + "\\pdf2png\\" + fileNameithoutExtension + "-" + newFileName +
                            ".png";
    extractor.SaveCurrentImageToFile(outputFileName, ImageFormat.Png);
    // Create text file here using Tesseract
    foreach (var file in Directory.GetFiles(appPath + "\\pdf2png"))
    {
        try
        {
            var pngFileName = Path.GetFileNameWithoutExtension(file);
            string[] myArguments =
            {
                "/C tesseract ", file,
                " " + appPath + "\\png2text\\" + pngFileName
            }; // /C for closing process automatically whent completes
            string strParam = String.Join(" ", myArguments);

            var myCmdProcess = new Process();
            var theProcess = new ProcessStartInfo("cmd.exe", strParam)
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                WindowStyle = ProcessWindowStyle.Minimized
            }; // Keep the cmd.exe window minimized
            myCmdProcess.StartInfo = theProcess;
            myCmdProcess.Exited += myCmdProcess_Exited;
            myCmdProcess.Start();

            //if (process)
            {
                /*
                MessageBox.Show("cmd.exe process started: " + Environment.NewLine +
                                "Process Name: " + myCmdProcess.ProcessName +
                                Environment.NewLine + " Process Id: " + myCmdProcess.Id
                                + Environment.NewLine + "process.Handle: " +
                                myCmdProcess.Handle);
                */
                Process.EnterDebugMode();
                //ShowWindow(hWnd: process.Handle, nCmdShow: 2);
                /*
                MessageBox.Show("After EnterDebugMode() cmd.exe process Exited: " +
                                Environment.NewLine +
                                "Process Name: " + myCmdProcess.ProcessName +
                                Environment.NewLine + " Process Id: " + myCmdProcess.Id
                                + Environment.NewLine + "process.Handle: " +
                                myCmdProcess.Handle);
                */
                myCmdProcess.WaitForExit(60000);
                /*
                MessageBox.Show("After WaitForExit() cmd.exe process Exited: " +
                                Environment.NewLine +
                                "Process Name: " + myCmdProcess.ProcessName +
                                Environment.NewLine + " Process Id: " + myCmdProcess.Id
                                + Environment.NewLine + "process.Handle: " +
                                myCmdProcess.Handle);
                */
                myCmdProcess.Refresh();
                Process.LeaveDebugMode();
                //myCmdProcess.Dispose();
                /*
                MessageBox.Show("After LeaveDebugMode() cmd.exe process Exited: " +
                                Environment.NewLine);
                */
            }


            //process.Kill();
            // Waits for the process to complete task and exites automatically
            Thread.Sleep(millisecondsTimeout: 1000);

            // This works fine in Windows 7 Environment, and not in Windows 8
            // Try following code block
            // Check, if process is not comletey exited

            if (!myCmdProcess.HasExited)
            {
                //process.WaitForExit(2000); // Try to wait for exit 2 more seconds
                /*
                MessageBox.Show(" Process of cmd.exe was exited by WaitForExit(); Method " +
                                Environment.NewLine);
                */
                try
                {
                    // If not, then Kill the process
                    myCmdProcess.Kill();
                    //myCmdProcess.Dispose();
                    //if (!myCmdProcess.HasExited)
                    //{
                    //    myCmdProcess.Kill();
                    //}

                    MessageBox.Show(" Process of cmd.exe exited ( Killed ) successfully " +
                                    Environment.NewLine);
                }
                catch (System.ComponentModel.Win32Exception ex)
                {
                    MessageBox.Show(
                        " Exception: System.ComponentModel.Win32Exception " +
                        ex.ErrorCode + Environment.NewLine);
                }
                catch (NotSupportedException notSupporEx)
                {
                    MessageBox.Show(" Exception: NotSupportedException " +
                                    notSupporEx.Message +
                                    Environment.NewLine);
                }
                catch (InvalidOperationException invalidOperation)
                {
                    MessageBox.Show(
                        " Exception: InvalidOperationException " +
                        invalidOperation.Message + Environment.NewLine);
                    foreach (
                        var textFile in Directory.GetFiles(appPath + "\\png2text", "*.txt",
                            SearchOption.AllDirectories))
                    {
                        loggingInfo += textFile +
                                       " In Reading Text from generated text file by Tesseract " +
                                       Environment.NewLine;
                        strBldr.Append(File.ReadAllText(textFile));
                    }
                    // Delete text file after reading text here
                    Directory.GetFiles(appPath + "\\pdf2png").ToList().ForEach(File.Delete);
                    Directory.GetFiles(appPath + "\\png2text").ToList().ForEach(File.Delete);
                }
            }
        }
        catch (Exception exception)
        {
            MessageBox.Show(
                " Cought Exception in Generating image do{...}while{...} function " +
                Environment.NewLine + exception.Message + Environment.NewLine);
        }
    }
    // Delete png image here
    Directory.GetFiles(appPath + "\\pdf2png").ToList().ForEach(File.Delete);
    Thread.Sleep(millisecondsTimeout: 1000);
    // Read text from text file here
    foreach (var textFile in Directory.GetFiles(appPath + "\\png2text", "*.txt",
        SearchOption.AllDirectories))
    {
        loggingInfo += textFile +
                       " In Reading Text from generated text file by Tesseract " +
                       Environment.NewLine;
        strBldr.Append(File.ReadAllText(textFile));
    }
    // Delete text file after reading text here
    Directory.GetFiles(appPath + "\\png2text").ToList().ForEach(File.Delete);
} while (extractor.GetNextImage()); // Advance image enumeration... 

Reverse HashMap keys and values in Java

private <A, B> Map<B, A> invertMap(Map<A, B> map) {
    Map<B, A> reverseMap = new HashMap<>();
    for (Map.Entry<A, B> entry : map.entrySet()) {
        reverseMap.put(entry.getValue(), entry.getKey());
    }
    return reverseMap;
}

It's important to remember that put replaces the value when called with the same key. So if you map has two keys with the same value only one of them will exist in the inverted map.

$("#form1").validate is not a function

I had the same issue, and yes I had my jquery included first followed by the jquery validate script. I had no idea what was wrong. Turns out I was using a validate url that had moved. I figured this out by doing the following:

  1. Open firefox
  2. Open firebug
  3. Click the NET tab in firebug. This will show you all the resources that get loaded.
  4. Load your page.
  5. Check the loaded resources and see if both your jquery & jquery.validate.js loaded.

In my situation I had a 403 Forbidden error when trying to obtain (http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js which is used in the example on http://rocketsquared.com/wiki/Plugins/Validation ).

Turns out the that link (http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js) had moved to http://view.jquery.com/trunk/plugins/validate/jquery.validate.js (Firebug told me this when I loaded the file locally as opposed to on my web server).

NOTE: I tried using microsoft's CDN link also but it failed when I tried to load the javascript file in the browser with the correct url, there was some odd issue going on with the CDN site.

Dynamically access object property using variable

const something = { bar: "Foobar!" };
const foo = 'bar';

something[\`${foo}\`];

How can you represent inheritance in a database?

Alternatively, consider using a document databases (such as MongoDB) which natively support rich data structures and nesting.

MySQL: Can't create/write to file '/tmp/#sql_3c6_0.MYI' (Errcode: 2) - What does it even mean?

Check permission issues, mysql config.

Also check if you haven't reached disk space, quota limits.

Note: Some systems are limiting number of files (not just space), deleting some old session files helped fixed the issue in my case.

Regex match digits, comma and semicolon?

Try word.matches("^[0-9,;]+$");

Android studio logcat nothing to show

You may put some text in the search and filter out the Logcat result.
That was the reason for my problem :)

Correct way to write line to file?

To write text in a file in the flask can be used:

filehandle = open("text.txt", "w")
filebuffer = ["hi","welcome","yes yes welcome"]
filehandle.writelines(filebuffer)
filehandle.close()

How to enable Ad Hoc Distributed Queries

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO

What does this thread join code mean?

For me, Join() behavior was always confusing because I was trying to remember who will wait for whom. Don't try to remember it that way.

Underneath, it is pure wait() and notify() mechanism.

We all know that, when we call wait() on any object(t1), calling object(main) is sent to waiting room(Blocked state).

Here, main thread is calling join() which is wait() under the covers. So main thread will wait until it is notified. Notification is given by t1 when it finishes it's run(thread completion).

After receiving the notification, main comes out of waiting room and proceeds it's execution.

Node.js - EJS - including a partial

As of Express 4.x

app.js

// above is all your node requires

// view engine setup
app.set('views', path.join(__dirname, 'views')); <-- ./views has all your .ejs files
app.set('view engine', 'ejs');

error.ejs

<!-- because ejs knows your root directory for views, you can navigate to the ./base directory and select the header.ejs file and include it -->

<% include ./base/header %> 
<h1> Other mark up here </h1>
<% include ./base/footer %>

how to set ul/li bullet point color?

A couple ways this can be done:

This will make it a square

ul
{
  list-style-type: square;
}

This will make it green

li
{
  color: #0F0;
}

This will prevent the text from being green

li p
{
  color: #000;
}

However that will require that all text within lists be in paragraphs so that the color is not overridden.

A better way is to make an image of a green square and use:

ul
{
  list-style: url(green-square.png);
}

How do I fix twitter-bootstrap on IE?

I had similar problems as well. I put the following line of code in the head of my layout file and all seems to be fine.

<meta http-equiv="X-UA-Compatible" content="IE=9">

Excel Reference To Current Cell

I found the best way to handle this (for me) is to use the following:

Dim MyString as String
MyString = Application.ThisCell.Address
Range(MyString).Select

Hope this helps.

Maven: how to override the dependency added by a library

What you put inside the </dependencies> tag of the root pom will be included by all child modules of the root pom. If all your modules use that dependency, this is the way to go.

However, if only 3 out of 10 of your child modules use some dependency, you do not want this dependency to be included in all your child modules. In that case, you can just put the dependency inside the </dependencyManagement>. This will make sure that any child module that needs the dependency must declare it in their own pom file, but they will use the same version of that dependency as specified in your </dependencyManagement> tag.

You can also use the </dependencyManagement> to modify the version used in transitive dependencies, because the version declared in the upper most pom file is the one that will be used. This can be useful if your project A includes an external project B v1.0 that includes another external project C v1.0. Sometimes it happens that a security breach is found in project C v1.0 which is corrected in v1.1, but the developers of B are slow to update their project to use v1.1 of C. In that case, you can simply declare a dependency on C v1.1 in your project's root pom inside `, and everything will be good (assuming that B v1.0 will still be able to compile with C v1.1).

Is it possible to decompile an Android .apk file?

I may also add, that nowadays it is possible to decompile Android application online, no software needed!

Here are 2 options for you:

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

Something I've noticed - in the INFORMATION_SCHEMA.COLUMNS view, CHARACTER_MAXIMUM_LENGTH gives a size of 2147483647 (2^31-1) for field types such as image and text. ntext is 2^30-1 (being double-byte unicode and all).

This size is included in the output from this query, but it is invalid for these data types in a CREATE statement (they should not have a maximum size value at all). So unless the results from this are manually corrected, the CREATE script won't work given these data types.

I imagine it's possible to fix the script to account for this, but that's beyond my SQL capabilities.

What is the most efficient/quickest way to loop through rows in VBA (excel)?

EDIT Summary and reccomendations

Using a for each cell in range construct is not in itself slow. What is slow is repeated access to Excel in the loop (be it reading or writing cell values, format etc, inserting/deleting rows etc).

What is too slow depends entierly on your needs. A Sub that takes minutes to run might be OK if only used rarely, but another that takes 10s might be too slow if run frequently.

So, some general advice:

  1. keep it simple at first. If the result is too slow for your needs, then optimise
  2. focus on optimisation of the content of the loop
  3. don't just assume a loop is needed. There are sometime alternatives
  4. if you need to use cell values (a lot) inside the loop, load them into a variant array outside the loop.
  5. a good way to avoid complexity with inserts is to loop the range from the bottom up
    (for index = max to min step -1)
  6. if you can't do that and your 'insert a row here and there' is not too many, consider reloading the array after each insert
  7. If you need to access cell properties other than value, you are stuck with cell references
  8. To delete a number of rows consider building a range reference to a multi area range in the loop, then delete that range in one go after the loop

eg (not tested!)

Dim rngToDelete as range
for each rw in rng.rows
    if need to delete rw then

        if rngToDelete is nothing then
            set rngToDelete = rw
        else
            set rngToDelete = Union(rngToDelete, rw)
        end if

    endif
next
rngToDelete.EntireRow.Delete

Original post

Conventional wisdom says that looping through cells is bad and looping through a variant array is good. I too have been an advocate of this for some time. Your question got me thinking, so I did some short tests with suprising (to me anyway) results:

test data set: a simple list in cells A1 .. A1000000 (thats 1,000,000 rows)

Test case 1: loop an array

Dim v As Variant
Dim n As Long

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
v = r
For n = LBound(v, 1) To UBound(v, 1)
    'i = i + 1
    'i = r.Cells(n, 1).Value 'i + 1
Next
Debug.Print "Array Time = " & (GetTickCount - T1) / 1000#
Debug.Print "Array Count = " & Format(n, "#,###")

Result:

Array Time = 0.249 sec
Array Count = 1,000,001

Test Case 2: loop the range

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
For Each c In r
Next c
Debug.Print "Range Time = " & (GetTickCount - T1) / 1000#
Debug.Print "Range Count = " & Format(r.Cells.Count, "#,###")

Result:

Range Time = 0.296 sec
Range Count = 1,000,000

So,looping an array is faster but only by 19% - much less than I expected.

Test 3: loop an array with a cell reference

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
v = r
For n = LBound(v, 1) To UBound(v, 1)
    i = r.Cells(n, 1).Value
Next
Debug.Print "Array Time = " & (GetTickCount - T1) / 1000# & " sec"
Debug.Print "Array Count = " & Format(i, "#,###")

Result:

Array Time = 5.897 sec
Array Count = 1,000,000

Test case 4: loop range with a cell reference

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
For Each c In r
    i = c.Value
Next c
Debug.Print "Range Time = " & (GetTickCount - T1) / 1000# & " sec"
Debug.Print "Range Count = " & Format(r.Cells.Count, "#,###")

Result:

Range Time = 2.356 sec
Range Count = 1,000,000

So event with a single simple cell reference, the loop is an order of magnitude slower, and whats more, the range loop is twice as fast!

So, conclusion is what matters most is what you do inside the loop, and if speed really matters, test all the options

FWIW, tested on Excel 2010 32 bit, Win7 64 bit All tests with

  • ScreenUpdating off,
  • Calulation manual,
  • Events disabled.

Get each line from textarea

You could use PHP constant:

$array = explode(PHP_EOL, $text);

additional notes:
1. For me this is the easiest and the safest way because it is cross platform compatible (Windows/Linux etc.)
2. It is better to use PHP CONSTANT whenever you can for faster execution

String is immutable. What exactly is the meaning?

see here

class ImmutableStrings {

    public static void main(String[] args) {
        testmethod();
    }

    private static void testmethod() {
    String a="a";
    System.out.println("a 1-->"+a);
    System.out.println("a 1 address-->"+a.hashCode());

    a = "ty";
    System.out.println("a 2-->"+a);

       System.out.println("a 2 address-->"+a.hashCode());
    }
}

output:

a 1-->a
a 1 address-->97
a 2-->ty
a 2 address-->3717

This indicates that whenever you are modifying the content of immutable string object a a new object will be created. i.e you are not allowed to change the content of immutable object. that's why the address are different for both the object.

Can I target all <H> tags with a single selector?

You could .class all the headings in Your document if You would like to target them with a single selector, as follows,

<h1 class="heading">...heading text...</h1>
<h2 class="heading">...heading text...</h2>

and in the css

.heading{
    color: #Dad;
    background-color: #DadDad;
}

I am not saying this is always best practice, but it can be useful, and for targeting syntax, easier in many ways,

so if You give all h1 through h6 the same .heading class in the html, then You can modify them for any html docs that utilize that css sheet.

upside, more global control versus "section div article h1, etc{}",

downside, instead of calling all the selectors in on place in the css, You will have much more typing in the html, yet I find that having a class in the html to target all headings can be beneficial, just be careful of precedence in the css, because conflicts could arise from

Fetch the row which has the Max value for a column

I think this should work?

Select
T1.UserId,
(Select Top 1 T2.Value From Table T2 Where T2.UserId = T1.UserId Order By Date Desc) As 'Value'
From
Table T1
Group By
T1.UserId
Order By
T1.UserId

Python how to exit main function

use sys module

import sys
sys.exit()

Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

After checking php version and a lot of research , the problem was on Composer side so just run the following command

composer install --ignore-platform-reqs

How do I get the list of keys in a Dictionary?

For a hybrid dictionary, I use this:

List<string> keys = new List<string>(dictionary.Count);
keys.AddRange(dictionary.Keys.Cast<string>());

How can I list all tags for a Docker image on a remote registry?

I got the answer from here . Thanks a lot! :)

Just one-line-script:(find all the tags of debian)

wget -q https://registry.hub.docker.com/v1/repositories/debian/tags -O -  | sed -e 's/[][]//g' -e 's/"//g' -e 's/ //g' | tr '}' '\n'  | awk -F: '{print $3}'

UPDATE Thanks for @degelf's advice. Here is the shell script.

#!/bin/bash

if [ $# -lt 1 ]
then
cat << HELP

dockertags  --  list all tags for a Docker image on a remote registry.

EXAMPLE: 
    - list all tags for ubuntu:
       dockertags ubuntu

    - list all php tags containing apache:
       dockertags php apache

HELP
fi

image="$1"
tags=`wget -q https://registry.hub.docker.com/v1/repositories/${image}/tags -O -  | sed -e 's/[][]//g' -e 's/"//g' -e 's/ //g' | tr '}' '\n'  | awk -F: '{print $3}'`

if [ -n "$2" ]
then
    tags=` echo "${tags}" | grep "$2" `
fi

echo "${tags}"

You can just create a new file name, dockertags, under /usr/local/bin (or add a PATH env to your .bashrc/.zshrc), and put that code in it. Then add the executable permissions(chmod +x dockertags).

Usage:

dockertags ubuntu ---> list all tags of ubuntu

dockertags php apache ---> list all php tags php containing 'apache'

Pandas How to filter a Series

As DACW pointed out, there are method-chaining improvements in pandas 0.18.1 that do what you are looking for very nicely.

Rather than using .where, you can pass your function to either the .loc indexer or the Series indexer [] and avoid the call to .dropna:

test = pd.Series({
383:    3.000000,
663:    1.000000,
726:    1.000000,
737:    9.000000,
833:    8.166667
})

test.loc[lambda x : x!=1]

test[lambda x: x!=1]

Similar behavior is supported on the DataFrame and NDFrame classes.

Running an outside program (executable) in Python?

Use subprocess, it is a smaller module so it runs the .exe quicker.

import subprocess
subprocess.Popen([r"U:\Year 8\kerbal space program\KSP.exe"])

How do I get next month date from today's date and insert it in my database?

If you want a specific date in next month, you can do this:

// Calculate the timestamp
$expire = strtotime('first day of +1 month');

// Format the timestamp as a string
echo date('m/d/Y', $expire);

Note that this actually works more reliably where +1 month can be confusing. For example...

Current Day   | first day of +1 month     | +1 month
---------------------------------------------------------------------------
2015-01-01    | 2015-02-01                | 2015-02-01
2015-01-30    | 2015-02-01                | 2015-03-02  (skips Feb)
2015-01-31    | 2015-02-01                | 2015-03-03  (skips Feb)
2015-03-31    | 2015-04-01                | 2015-05-01  (skips April)
2015-12-31    | 2016-01-01                | 2016-01-31

iframe to Only Show a Certain Part of the Page

I needed an iframe that would embed a portion of an external page with a vertical scroll bar, cropping out the navigation menus on the top and left of the page. I was able to do it with some simple HTML and CSS.

HTML

<div id="container">
    <iframe id="embed" src="http://www.example.com"></iframe>
</div>

CSS

div#container
{
    width:840px;
    height:317px;
    overflow:scroll;     /* if you don't want a scrollbar, set to hidden */
    overflow-x:hidden;   /* hides horizontal scrollbar on newer browsers */

    /* resize and min-height are optional, allows user to resize viewable area */
    -webkit-resize:vertical; 
    -moz-resize:vertical;
    resize:vertical;
    min-height:317px;
}

iframe#embed
{
    width:1000px;       /* set this to approximate width of entire page you're embedding */
    height:2000px;      /* determines where the bottom of the page cuts off */
    margin-left:-183px; /* clipping left side of page */
    margin-top:-244px;  /* clipping top of page */
    overflow:hidden;

    /* resize seems to inherit in at least Firefox */
    -webkit-resize:none;
    -moz-resize:none;
    resize:none;
}

How to handle floats and decimal separators with html5 input type number

Use valueAsNumber instead of .val().

input . valueAsNumber [ = value ]

Returns a number representing the form control's value, if applicable; otherwise, returns null.
Can be set, to change the value.
Throws an INVALID_STATE_ERR exception if the control is neither date- or time-based nor numeric.

How to secure an ASP.NET Web API

in continuation to @ Cuong Le's answer , my approach to prevent replay attack would be

// Encrypt the Unix Time at Client side using the shared private key(or user's password)

// Send it as part of request header to server(WEB API)

// Decrypt the Unix Time at Server(WEB API) using the shared private key(or user's password)

// Check the time difference between the Client's Unix Time and Server's Unix Time, should not be greater than x sec

// if User ID/Hash Password are correct and the decrypted UnixTime is within x sec of server time then it is a valid request

Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor

An explicit call to a parent class constructor is required any time the parent class lacks a no-argument constructor. You can either add a no-argument constructor to the parent class or explicitly call the parent class constructor in your child class.

error: function returns address of local variable

a is an array local to the function.Once the function returns it does not exist anymore and hence you should not return the address of a local variable.
In other words the lifetime of a is within the scope({,}) of the function and if you return a pointer to it what you have is a pointer pointing to some memory which is not valid. Such variables are also called automatic variabels because their lifetime is automatically managed you do not need to manage it explicitly.

Since you need to extend the variable to persist beyond the scope of the function you You need to allocate a array on heap and return a pointer to it.

char *a = malloc(1000); 

This way the array a resides in memory untill you call a free() on the same address.
Do not forget to do so or you end up with a memory leak.

Logarithmic returns in pandas dataframe

Here is one way to calculate log return using .shift(). And the result is similar to but not the same as the gross return calculated by pct_change(). Can you upload a copy of your sample data (dropbox share link) to reproduce the inconsistency you saw?

import pandas as pd
import numpy as np

np.random.seed(0)
df = pd.DataFrame(100 + np.random.randn(100).cumsum(), columns=['price'])
df['pct_change'] = df.price.pct_change()
df['log_ret'] = np.log(df.price) - np.log(df.price.shift(1))

Out[56]: 
       price  pct_change  log_ret
0   101.7641         NaN      NaN
1   102.1642      0.0039   0.0039
2   103.1429      0.0096   0.0095
3   105.3838      0.0217   0.0215
4   107.2514      0.0177   0.0176
5   106.2741     -0.0091  -0.0092
6   107.2242      0.0089   0.0089
7   107.0729     -0.0014  -0.0014
..       ...         ...      ...
92  101.6160      0.0021   0.0021
93  102.5926      0.0096   0.0096
94  102.9490      0.0035   0.0035
95  103.6555      0.0069   0.0068
96  103.6660      0.0001   0.0001
97  105.4519      0.0172   0.0171
98  105.5788      0.0012   0.0012
99  105.9808      0.0038   0.0038

[100 rows x 3 columns]

What is the difference between tree depth and height?

I know it's weird but Leetcode defines depth in terms of number of nodes in the path too. So in such case depth should start from 1 (always count the root) and not 0. In case anybody has the same confusion like me.

Video file formats supported in iPhone

The short answer is the iPhone supports H.264 video, High profile and AAC audio, in container formats .mov, .mp4, or MPEG Segment .ts. MPEG Segment files are used for HTTP Live Streaming.

  • For maximum compatibility with Android and desktop browsers, use H.264 + AAC in an .mp4 container.
  • For extended length videos longer than 10 minutes you must use HTTP Live Streaming, which is H.264 + AAC in a series of small .ts container files (see App Store Review Guidelines rule 2.5.7).

Video

On the iPhone, H.264 is the only game in town. [1]

There are several different feature tiers or "profiles" available in H.264. All modern iPhones (3GS and above) support the High profile. These profiles are basically three different levels of algorithm "tricks" used to compress the video. More tricks give better compression, but require more CPU or dedicated hardware to decode. This is a table that lists the differences between the different profiles.

[1] Interestingly, Apple's own Facetime uses the newer H.265 (HEVC) video codec. However right now (August 2017) there is no Apple-provided library that gives access to a HEVC codec to developers. This is expected to change at some point.

In talking about what video format the iPhone supports, a distinction should be made between what the hardware can support, and what the (much lower) limits are for playback when streaming over a network.

The only data given about hardware video support by Apple about the current generation of iPhones (SE, 6S, 6S Plus, 7, 7 Plus) is that they support

4K [3840x2160] video recording at 30 fps

1080p [1920x1080] HD video recording at 30 fps or 60 fps.

Obviously the phone can play back what it can record, so we can guess that 3840x2160 at 30 fps and 1920x1080 at 60 fps represent design limits of the phone. In addition, the screen size on the 6S Plus and 7 Plus is 1920x1080. So if you're interested in playback on the phone, it doesn't make sense to send over more pixels then the screen can draw.

However, streaming video is a different matter. Since networks are slow and video is huge, it's typical to use lower resolutions, bitrates, and frame rates than the device's theoretical maximum.

The most detailed document giving recommendations for streaming is TN2224 Best Practices for Creating and Deploying HTTP Live Streaming Media for Apple Devices. Figure 3 in that document gives a table of recommended streaming parameters:

Table of Apple recommended video encoding settings This table is from May 2016.

As you can see, Apple recommends the relatively low resolution of 768x432 as the highest recommended resolution for streaming over a cellular network. Of course this is just a recommendation and YMMV.

Audio

The question is about video, but that video generally has one or more audio tracks with it. The iPhone supports a few audio formats, but the most modern and by far most widely used is AAC. The iPhone 7 / 7 Plus, 6S Plus / 6S, SE all support AAC bitrates of 8 to 320 Kbps.

Container

The audio and video tracks go inside a container. The purpose of the container is to combine (interleave) the different tracks together, to store metadata, and to support seeking. The iPhone supports

  1. QuickTime .mov,
  2. MP4, and
  3. MPEG-TS.

The .mov and .mp4 file formats are closely related (.mp4 is in fact based on .mov), however .mp4 is an ISO standard that has much wider support.

As noted above, you have to use MPEG-TS for videos longer than 10 minutes.

Java regex capturing groups indexes

Capturing and grouping

Capturing group (pattern) creates a group that has capturing property.

A related one that you might often see (and use) is (?:pattern), which creates a group without capturing property, hence named non-capturing group.

A group is usually used when you need to repeat a sequence of patterns, e.g. (\.\w+)+, or to specify where alternation should take effect, e.g. ^(0*1|1*0)$ (^, then 0*1 or 1*0, then $) versus ^0*1|1*0$ (^0*1 or 1*0$).

A capturing group, apart from grouping, will also record the text matched by the pattern inside the capturing group (pattern). Using your example, (.*):, .* matches ABC and : matches :, and since .* is inside capturing group (.*), the text ABC is recorded for the capturing group 1.

Group number

The whole pattern is defined to be group number 0.

Any capturing group in the pattern start indexing from 1. The indices are defined by the order of the opening parentheses of the capturing groups. As an example, here are all 5 capturing groups in the below pattern:

(group)(?:non-capturing-group)(g(?:ro|u)p( (nested)inside)(another)group)(?=assertion)
|     |                       |          | |      |      ||       |     |
1-----1                       |          | 4------4      |5-------5     |
                              |          3---------------3              |
                              2-----------------------------------------2

The group numbers are used in back-reference \n in pattern and $n in replacement string.

In other regex flavors (PCRE, Perl), they can also be used in sub-routine calls.

You can access the text matched by certain group with Matcher.group(int group). The group numbers can be identified with the rule stated above.

In some regex flavors (PCRE, Perl), there is a branch reset feature which allows you to use the same number for capturing groups in different branches of alternation.

Group name

From Java 7, you can define a named capturing group (?<name>pattern), and you can access the content matched with Matcher.group(String name). The regex is longer, but the code is more meaningful, since it indicates what you are trying to match or extract with the regex.

The group names are used in back-reference \k<name> in pattern and ${name} in replacement string.

Named capturing groups are still numbered with the same numbering scheme, so they can also be accessed via Matcher.group(int group).

Internally, Java's implementation just maps from the name to the group number. Therefore, you cannot use the same name for 2 different capturing groups.

How to redirect to a different domain using NGINX?

server_name supports suffix matches using .mydomain.com syntax:

server {
  server_name .mydomain.com;
  rewrite ^ http://www.adifferentdomain.com$request_uri? permanent;
}

or on any version 0.9.1 or higher:

server {
  server_name .mydomain.com;
  return 301 http://www.adifferentdomain.com$request_uri;
}

When is a CDATA section necessary within a script tag?

Basically it is to allow to write a document that is both XHTML and HTML. The problem is that within XHTML, the XML parser will interpret the &,<,> characters in the script tag and cause XML parsing error. So, you can write your JavaScript with entities, e.g.:

if (a &gt; b) alert('hello world');

But this is impractical. The bigger problem is that if you read the page in HTML, the tag script is considered CDATA 'by default', and such JavaScript will not run. Therefore, if you want the same page to be OK both using XHTML and HTML parsers, you need to enclose the script tag in CDATA element in XHTML, but NOT to enclose it in HTML.

This trick marks the start of a CDATA element as a JavaScript comment; in HTML the JavaScript parser ignores the CDATA tag (it's a comment). In XHTML, the XML parser (which is run before the JavaScript) detects it and treats the rest until end of CDATA as CDATA.

int *array = new int[n]; what is this function actually doing?

int *array = new int[n];

It declares a pointer to a dynamic array of type int and size n.

A little more detailed answer: new allocates memory of size equal to sizeof(int) * n bytes and return the memory which is stored by the variable array. Also, since the memory is dynamically allocated using new, you've to deallocate it manually by writing (when you don't need anymore, of course):

delete []array;

Otherwise, your program will leak memory of at least sizeof(int) * n bytes (possibly more, depending on the allocation strategy used by the implementation).

How to hide image broken Icon using only CSS/HTML?

If you will add alt with text alt="abc" it will show the show corrupt thumbnail, and alt message abc

<img src="pic_trulli.jpg" alt="abc"/>

1st

If you will not add alt it will show the show corrupt thumbnail

<img src="pic_trulli.jpg"/>

2nd

If you want to hide the broken one just add alt="" it will not show corrupt thumbnail and any alt message(without using js)

<img src="pic_trulli.jpg" alt=""/>

If you want to hide the broken one just add alt="" & onerror="this.style.display='none'" it will not show corrupt thumbnail and any alt message(with js)

<img src="pic_trulli.jpg" alt="abc" onerror="this.style.display='none'"/>

4th one is a little dangerous(not exactly) , if you want to add any image in onerror event, it will not display even if Image exist as style.display is like adding. So, use it when you don't require any alternative image to display.

display: 'none'; // in css

If we give it in CSS, then the item will not display(like image, iframe, div like that).

If you want to display image & you want to display totally blank space if error, then you can use, but also be careful this will not take any space. So, you need to keep it in a div may be

Link https://jsfiddle.net/02d9yshw/

Can you have multiple $(document).ready(function(){ ... }); sections?

Yes it is possible but you can better use a div #mydiv and use both

$(document).ready(function(){});

//and

$("#mydiv").ready(function(){});

Reliable way to convert a file to a byte[]

Not to repeat what everyone already have said but keep the following cheat sheet handly for File manipulations:

  1. System.IO.File.ReadAllBytes(filename);
  2. File.Exists(filename)
  3. Path.Combine(folderName, resOfThePath);
  4. Path.GetFullPath(path); // converts a relative path to absolute one
  5. Path.GetExtension(path);

What is causing "Unable to allocate memory for pool" in PHP?

Running the apc.php script is key to understanding what your problem is, IMO. This helped us size our cache properly and for the moment, seems to have resolved the problem.

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

Directly from the Windows.h header file:

#ifndef WIN32_LEAN_AND_MEAN
    #include <cderr.h>
    #include <dde.h>
    #include <ddeml.h>
    #include <dlgs.h>
    #ifndef _MAC
        #include <lzexpand.h>
        #include <mmsystem.h>
        #include <nb30.h>
        #include <rpc.h>
    #endif
    #include <shellapi.h>
    #ifndef _MAC
        #include <winperf.h>
        #include <winsock.h>
    #endif
    #ifndef NOCRYPT
        #include <wincrypt.h>
        #include <winefs.h>
        #include <winscard.h>
    #endif

    #ifndef NOGDI
        #ifndef _MAC
            #include <winspool.h>
            #ifdef INC_OLE1
                #include <ole.h>
            #else
                #include <ole2.h>
            #endif /* !INC_OLE1 */
        #endif /* !MAC */
        #include <commdlg.h>
    #endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */

if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.

Also, from Microsoft's support page:

To speed the build process, Visual C++ and the Windows Headers provide the following new defines:

VC_EXTRALEAN
WIN32_LEAN_AND_MEAN

You can use them to reduce the size of the Win32 header files.

Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.

Better naming in Tuple classes than "Item1", "Item2"

Reproducing my answer from this post as it is a better fit here.

Starting C# v7.0, now it is possible to name the tuple properties which earlier used to default to predefined names like Item1, Item2 and so on.

Naming the properties of Tuple Literals:

var myDetails = (MyName: "RBT_Yoga", MyAge: 22, MyFavoriteFood: "Dosa");
Console.WriteLine($"Name - {myDetails.MyName}, Age - {myDetails.MyAge}, Passion - {myDetails.MyFavoriteFood}");

The output on console:

Name - RBT_Yoga, Age - 22, Passion - Dosa

Returning Tuple (having named properties) from a method:

static void Main(string[] args)
{
    var empInfo = GetEmpInfo();
    Console.WriteLine($"Employee Details: {empInfo.firstName}, {empInfo.lastName}, {empInfo.computerName}, {empInfo.Salary}");
}

static (string firstName, string lastName, string computerName, int Salary) GetEmpInfo()
{
    //This is hardcoded just for the demonstration. Ideally this data might be coming from some DB or web service call
    return ("Rasik", "Bihari", "Rasik-PC", 1000);
}

The output on console:

Employee Details: Rasik, Bihari, Rasik-PC, 1000

Creating a list of Tuples having named properties

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

foreach (var tuple in tupleList)
    Console.WriteLine($"{tuple.Index} - {tuple.Name}");

Output on console:

1 - cow 5 - chickens 1 - airplane

I hope I've covered everything. In case, there is anything which I've missed then please give me a feedback in comments.

Note: My code snippets are using string interpolation feature of C# v7 as detailed here.

Difference between "and" and && in Ruby?

and has lower precedence, mostly we use it as a control-flow modifier such as if:

next if widget = widgets.pop

becomes

widget = widgets.pop and next

For or:

raise "Not ready!" unless ready_to_rock?

becomes

ready_to_rock? or raise "Not ready!"

I prefer to use if but not and, because if is more intelligible, so I just ignore and and or.

Refer to "Using “and” and “or” in Ruby" for more information.

How do I read CSV data into a record array in NumPy?

Using numpy.loadtxt

A quite simple method. But it requires all the elements being float (int and so on)

import numpy as np 
data = np.loadtxt('c:\\1.csv',delimiter=',',skiprows=0)  

Backporting Python 3 open(encoding="utf-8") to Python 2

If you are using six, you can try this, by which utilizing the latest Python 3 API and can run in both Python 2/3:

import six

if six.PY2:
    # FileNotFoundError is only available since Python 3.3
    FileNotFoundError = IOError
    from io import open

fname = 'index.rst'
try:
    with open(fname, "rt", encoding="utf-8") as f:
        pass
        # do_something_with_f ...
except FileNotFoundError:
    print('Oops.')

And, Python 2 support abandon is just deleting everything related to six.

Move layouts up when soft keyboard is shown?

You can also use this code in onCreate() method:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

How to get a list of all files in Cloud Storage in a Firebase app?

So I had a project that required downloading assets from firebase storage, so I had to solve this problem myself. Here is How :

1- First, make a model data for example class Choice{}, In that class defines a String variable called image Name so it will be like that

class Choice {
    .....
    String imageName;
}

2- from a database/firebase database, go and hardcode the image names to the objects, so if you have image name called Apple.png, create the object to be

Choice myChoice = new Choice(...,....,"Apple.png");

3- Now, get the link for the assets in your firebase storage which will be something like that

gs://your-project-name.appspot.com/

like this one

4- finally, initialize your firebase storage reference and start getting the files by a loop like that

storageRef = storage.getReferenceFromUrl(firebaseRefURL).child(imagePath);

File localFile = File.createTempFile("images", "png");
storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {

@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
    //Dismiss Progress Dialog\\
}

5- that's it

Set the layout weight of a TextView programmatically

TextView txtview = new TextView(v.getContext());
LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f);
txtview.setLayoutParams(params);

1f is denotes as weight=1; you can give 2f or 3f, views will move accoding to the space

tqdm in Jupyter Notebook prints new progress bars repeatedly

Try using tqdm.notebook.tqdm instead of tqdm, as outlined here.

This could be as simple as changing your import to:

from tqdm.notebook import tqdm

Good luck!

EDIT: After testing, it seems that tqdm actually works fine in 'text mode' in Jupyter notebook. It's hard to tell because you haven't provided a minimal example, but it looks like your problem is caused by a print statement in each iteration. The print statement is outputting a number (~0.89) in between each status bar update, which is messing up the output. Try removing the print statement.

Use dynamic variable names in JavaScript

Although this have an accepted answer I would like to add an observation:

In ES6 using let doesn't work:

_x000D_
_x000D_
/*this is NOT working*/_x000D_
let t = "skyBlue",_x000D_
    m = "gold",_x000D_
    b = "tomato";_x000D_
_x000D_
let color = window["b"];_x000D_
console.log(color);
_x000D_
_x000D_
_x000D_

However using var works

_x000D_
_x000D_
/*this IS working*/_x000D_
var t = "skyBlue",_x000D_
    m = "gold",_x000D_
    b = "tomato";_x000D_
_x000D_
let color = window["b"];_x000D_
console.log(color);
_x000D_
_x000D_
_x000D_

I hope this may be useful to some.

WebService Client Generation Error with JDK8

I was also getting similar type of error in Eclipse during testing a webservice program on glassfish 4.0 web server: java.lang.AssertionError: org.xml.sax.SAXParseException; systemId: bundle://158.0:1/com/sun/tools/xjc/reader/xmlschema/bindinfo/binding.xsd; lineNumber: 52; columnNumber: 88; schema_reference: Failed to read schema document 'xjc.xsd', because 'bundle' access is not allowed due to restriction set by the accessExternalSchema property.

I have added javax.xml.accessExternalSchema = All in jaxp.properties, but doesnot work for me.

However I found a solution here below which work for me: For GlassFish Server, I need to modify the domain.xml of the GlassFish, path :<path>/glassfish/domains/domain1 or domain2/config/domain.xml) and add, <jvm-options>-Djavax.xml.accessExternalSchema=all</jvm-options>under the <java-config> tag

....

<java-config> ... <jvm-options>-Djavax.xml.accessExternalSchema=all</jvm-options> </java-config> ...and then restart the GlassFish server

Foreach value from POST from form

First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters

In addition, you don't have to use variable variable names (that sounds odd), instead:

foreach($_POST as $key => $value) {
  echo "POST parameter '$key' has '$value'";
}

To ensure that you have only parameters beginning with 'item_name' you can check it like so:

$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
  // do something
}

Copy files on Windows Command Line with Progress

The Esentutl /y option allows copyng (single) file files with progress bar like this :

enter image description here

the command should look like :

esentutl /y "FILE.EXT" /d "DEST.EXT" /o

The command is available on every windows machine but the y option is presented in windows vista. As it works only with single files does not look very useful for a small ones. Other limitation is that the command cannot overwrite files. Here's a wrapper script that checks the destination and if needed could delete it (help can be seen by passing /h).

How to use (install) dblink in PostgreSQL?

On linux, find dblink.sql, then execute in the postgresql console something like this to create all required functions:

\i /usr/share/postgresql/8.4/contrib/dblink.sql 

you might need to install the contrib packages: sudo apt-get install postgresql-contrib

Finding the indices of matching elements in list in Python

You are using .index() which will only find the first occurrence of your value in the list. So if you have a value 1.0 at index 2, and at index 9, then .index(1.0) will always return 2, no matter how many times 1.0 occurs in the list.

Use enumerate() to add indices to your loop instead:

def find(lst, a, b):
    result = []
    for i, x in enumerate(lst):
        if x<a or x>b:
            result.append(i)
    return result

You can collapse this into a list comprehension:

def find(lst, a, b):
    return [i for i, x in enumerate(lst) if x<a or x>b]

How to display the first few characters of a string in Python?

If you want first 2 letters and last 2 letters of a string then you can use the following code: name = "India" name[0:2]="In" names[-2:]="ia"

PHP Get all subdirectories of a given directory

Non-recursively List Only Directories

The only question that direct asked this has been erroneously closed, so I have to put it here.

It also gives the ability to filter directories.

/**
 * Copyright © 2020 Theodore R. Smith <https://www.phpexperts.pro/>
 * License: MIT
 *
 * @see https://stackoverflow.com/a/61168906/430062
 *
 * @param string $path
 * @param bool   $recursive Default: false
 * @param array  $filtered  Default: [., ..]
 * @return array
 */
function getDirs($path, $recursive = false, array $filtered = [])
{
    if (!is_dir($path)) {
        throw new RuntimeException("$path does not exist.");
    }

    $filtered += ['.', '..'];

    $dirs = [];
    $d = dir($path);
    while (($entry = $d->read()) !== false) {
        if (is_dir("$path/$entry") && !in_array($entry, $filtered)) {
            $dirs[] = $entry;

            if ($recursive) {
                $newDirs = getDirs("$path/$entry");
                foreach ($newDirs as $newDir) {
                    $dirs[] = "$entry/$newDir";
                }
            }
        }
    }

    return $dirs;
}

Creating an Instance of a Class with a variable in Python

This is a very strange question to ask, specifically of python, so being more specific will definitely help me answer it. As is, I'll try to take a stab at it.

I'm going to assume what you want to do is create a new instance of a datastructure and give it a variable. For this example I'll use the dictionary data structure and the variable mydictionary.

mydictionary = dict()

This will create a new instance of the dictionary data structure and place it in the variable named mydictionary. Alternatively the dictionary constructor can also take arguments:

mydictionary = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])

Finally, python will attempt to figure out what data structure I mean from the data I give it. IE

mydictionary = {'jack': 4098, 'sape': 4139}

These examples were taken from Here

Command not found after npm install in zsh

For me the accepted answer for adding export PATH=/usr/local/share/npm/bin:$PATH to .zshrc didn't work. I tried adding the NVM_DIR as well which solved my issue.

  1. Try vi .bashrc
  2. You will find a line like the following. Copy it.

    export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion

  3. Paste the copied content to .zshrc file

  4. Restart the terminal

I hope this solves your issue.

Is there any boolean type in Oracle databases?

No there doesn't exist type boolean,but instead of this you can you 1/0(type number),or 'Y'/'N'(type char),or 'true'/'false' (type varchar2).

Javascript .querySelector find <div> by innerTEXT

You best see if you have a parent element of the div you are querying. If so get the parent element and perform an element.querySelectorAll("div"). Once you get the nodeList apply a filter on it over the innerText property. Assume that a parent element of the div that we are querying has an id of container. You can normally access container directly from the id but let's do it the proper way.

var conty = document.getElementById("container"),
     divs = conty.querySelectorAll("div"),
    myDiv = [...divs].filter(e => e.innerText == "SomeText");

So that's it.

Margin between items in recycler view Android

I faced similar issue, with RelativeLayout as the root element for each row in the recyclerview.

To solve the issue, find the xml file that holds each row and make sure that the root element's height is wrap_content NOT match_parent.

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

In pom.xml file we need to add

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.8</version>
</dependency>

How to pause a vbscript execution?

With 'Enter' is better use ReadLine() or Read(2), because key 'Enter' generate 2 symbols. If user enter any text next Pause() also wil be skipped even with Read(2). So ReadLine() is better:

Sub Pause()
    WScript.Echo ("Press Enter to continue")
    z = WScript.StdIn.ReadLine()
End Sub

More examples look in http://technet.microsoft.com/en-us/library/ee156589.aspx

How do I get the current date in JavaScript?

new Date().toISOString().slice(0,10); 

would work too

Getting the parent of a directory in Bash

Clearly the parent directory is given by simply appending the dot-dot filename:

/home/smith/Desktop/Test/..     # unresolved path

But you must want the resolved path (an absolute path without any dot-dot path components):

/home/smith/Desktop             # resolved path

The problem with the top answers that use dirname, is that they don't work when you enter a path with dot-dots:

$ dir=~/Library/../Desktop/../..
$ parentdir="$(dirname "$dir")"
$ echo $parentdir
/Users/username/Library/../Desktop/..   # not fully resolved

This is more powerful:

dir=/home/smith/Desktop/Test
parentdir=$(builtin cd $dir; pwd)

You can feed it /home/smith/Desktop/Test/.., but also more complex paths like:

$ dir=~/Library/../Desktop/../..
$ parentdir=$(builtin cd $dir; pwd)
$ echo $parentdir
/Users                                  # the fully resolved path!
 

NOTE: use of builtin ensures no user defined function variant of cd is called, but rather the default utility form which has no output.

ASP.NET strange compilation error

If you did deploy this application into your server, it's possible that the *.config files in folder \bin\roslyn were deleted.

Then review if exist the files like:

  • csc.exe.config
  • csi.exe.config
  • vbc.exe.config
  • VBCSCompiler.exe.config

These files can be variate depending on your project references.

How to set a cookie to expire in 1 hour in Javascript?

Code :

var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);
document.cookie = 
'username=' + value + 
'; expires=' + now.toUTCString() + 
'; path=/';

Can regular JavaScript be mixed with jQuery?

Or no JavaScript load function at all...

<html>
<head></head>
<body>
    <canvas id="canvas" width="150" height="150"></canvas>
</body>
<script type="text/javascript">
    var draw = function() {
        var canvas = document.getElementById("canvas");
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");

            ctx.fillStyle = "rgb(200,0,0)";
            ctx.fillRect (10, 10, 55, 50);

            ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
            ctx.fillRect (30, 30, 55, 50);
        }
    }
    draw();

    //or self executing...

    (function(){
        var canvas = document.getElementById("canvas");
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");

            ctx.fillStyle = "rgb(200,0,0)";
            ctx.fillRect (50, 50, 55, 50);

            ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
            ctx.fillRect (70, 70, 55, 50);
        }
    })();
</script>
</html>

curl Failed to connect to localhost port 80

I also had problem with refused connection on port 80. I didn't use localhost.

curl --data-binary "@/textfile.txt" "http://www.myserver.com/123.php"

Problem was that I had umlauts äåö in my textfile.txt.

How to get the url parameters using AngularJS

When using angularjs with express

On my example I was using angularjs with express doing the routing so using $routeParams would mess up with my routing. I used the following code to get what I was expecting:

const getParameters = (temp, path) => {
  const parameters = {};
  const tempParts = temp.split('/');
  const pathParts = path.split('/');
  for (let i = 0; i < tempParts.length; i++) {
    const element = tempParts[i];
    if(element.startsWith(':')) {
      const key = element.substring(1,element.length);
      parameters[key] = pathParts[i];
    }
  }
  return parameters;
};

This receives a URL template and the path of the given location. The I just call it with:

const params = getParameters('/:table/:id/visit/:place_id/on/:interval/something', $location.path()); 

Putting it all together my controller is:

.controller('TestController', ['$scope', function($scope, $window) {
  const getParameters = (temp, path) => {
    const parameters = {};
    const tempParts = temp.split('/');
    const pathParts = path.split('/');
    for (let i = 0; i < tempParts.length; i++) {
      const element = tempParts[i];
      if(element.startsWith(':')) {
        const key = element.substring(1,element.length);
        parameters[key] = pathParts[i];
      }
    }
    return parameters;
  };

const params = getParameters('/:table/:id/visit/:place_id/on/:interval/something', $window.location.pathname);
}]);

The result will be:

{ table: "users", id: "1", place_id: "43", interval: "week" }

Hope this helps someone out there!

How do I import material design library to Android Studio?

First, add the Material Design dependency.

implementation 'com.google.android.material:material:<version>'

To get the latest material design library version. check the official website github repository.

Current version is 1.2.0.

So, you have to add,

implementation 'com.google.android.material:material:1.2.0'

Then, you need to change the app theme to material theme by adding,

<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

in your style.xml. Dont forget to set the same theme in your application theme in your manifest file.

Oracle - How to create a readonly user

Execute the following procedure for example as user system.

Set p_owner to the schema owner and p_readonly to the name of the readonly user.

create or replace
procedure createReadOnlyUser(p_owner in varchar2, p_readonly in varchar2) 
AUTHID CURRENT_USER is
BEGIN
    execute immediate 'create user '||p_readonly||' identified by '||p_readonly;
    execute immediate 'grant create session to '||p_readonly;
    execute immediate 'grant select any dictionary to '||p_readonly;
    execute immediate 'grant create synonym to '||p_readonly;

   FOR R IN (SELECT owner, object_name from all_objects where object_type in('TABLE', 'VIEW') and owner=p_owner) LOOP
      execute immediate 'grant select on '||p_owner||'.'||R.object_name||' to '||p_readonly;
   END LOOP;
   FOR R IN (SELECT owner, object_name from all_objects where object_type in('FUNCTION', 'PROCEDURE') and owner=p_owner) LOOP
      execute immediate 'grant execute on '||p_owner||'.'||R.object_name||' to '||p_readonly;
   END LOOP;
   FOR R IN (SELECT owner, object_name FROM all_objects WHERE object_type in('TABLE', 'VIEW') and owner=p_owner) LOOP
      EXECUTE IMMEDIATE 'create synonym '||p_readonly||'.'||R.object_name||' for '||R.owner||'."'||R.object_name||'"';
   END LOOP;
   FOR R IN (SELECT owner, object_name from all_objects where object_type in('FUNCTION', 'PROCEDURE') and owner=p_owner) LOOP
      execute immediate 'create synonym '||p_readonly||'.'||R.object_name||' for '||R.owner||'."'||R.object_name||'"';
   END LOOP;
END;

Deserializing JSON Object Array with Json.net

For those who don't want to create any models, use the following code:

var result = JsonConvert.DeserializeObject<
  List<Dictionary<string, 
    Dictionary<string, string>>>>(content);

Note: This doesn't work for your JSON string. This is not a general solution for any JSON structure.

Does bootstrap have builtin padding and margin classes?

Bootstrap 5 has changed the ml,mr,pl,pr classes, which no longer work if you're upgrading from a lower version. The l and r have now been replaced with s(...which is confusing) and e(east?) respectively.

From bootstrap website:

Where property is one of:

  • m - for classes that set margin
  • p - for classes that set padding

Where sides is one of:

  • t - for classes that set margin-top or padding-top
  • b - for classes that set margin-bottom or padding-bottom
  • s - for classes that set margin-left or padding-left in LTR, margin-right or padding-right in RTL
  • e - for classes that set margin-right or padding-right in LTR, margin-left or padding-left in RTL
  • x - for classes that set both *-left and *-right
  • y - for classes that set both *-top and *-bottom blank - for classes that set a margin or padding on all 4 sides of the element Where size is one of:

0 - for classes that eliminate the margin or padding by setting it to 0 1 - (by default) for classes that set the margin or padding to $spacer * .25 2 - (by default) for classes that set the margin or padding to $spacer * .5 3 - (by default) for classes that set the margin or padding to $spacer 4 - (by default) for classes that set the margin or padding to $spacer * 1.5 5 - (by default) for classes that set the margin or padding to $spacer * 3 auto - for classes that set the margin to auto (You can add more sizes by adding entries to the $spacers Sass map variable.)

What is the difference between Java RMI and RPC?

The difference between RMI and RPC is that:

  • RMI as the name indicates Remote Method Invoking: it invokes a method or an object. And
  • RPC it invokes a function.

How to initialize a variable of date type in java?

Here's the Javadoc in Oracle's website for the Date class: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html
If you scroll down to "Constructor Summary," you'll see the different options for how a Date object can be instantiated. Like all objects in Java, you create a new one with the following:

Date firstDate = new Date(ConstructorArgsHere);

Now you have a bit of a choice. If you don't pass in any arguments, and just do this,

Date firstDate = new Date();

it will represent the exact date and time at which you called it. Here are some other constructors you may want to make use of:

Date firstDate1 = new Date(int year, int month, int date);
Date firstDate2 = new Date(int year, int month, int date, int hrs, int min);
Date firstDate3 = new Date(int year, int month, int date, int hrs, int min, int sec);

Turn a number into star rating display using jQuery and CSS

using jquery without prototype, update the js code to

$( ".stars" ).each(function() { 
    // Get the value
    var val = $(this).data("rating");
    // Make sure that the value is in 0 - 5 range, multiply to get width
    var size = Math.max(0, (Math.min(5, val))) * 16;
    // Create stars holder
    var $span = $('<span />').width(size);
    // Replace the numerical value with stars
    $(this).html($span);
});

I also added a data attribute by the name of data-rating in the span.

<span class="stars" data-rating="4" ></span>

How to query GROUP BY Month in a Year

I would be inclined to include the year in the output. One way:

select to_char(DATE_CREATED, 'YYYY-MM'), sum(Num_of_Pictures)
from pictures_table
group by to_char(DATE_CREATED, 'YYYY-MM')
order by 1

Another way (more standard SQL):

select extract(year from date_created) as yr, extract(month from date_created) as mon,
       sum(Num_of_Pictures)
from pictures_table
group by extract(year from date_created), extract(month from date_created)
order by yr, mon;

Remember the order by, since you presumably want these in order, and there is no guarantee about the order that rows are returned in after a group by.

How can I copy the content of a branch to a new local branch?

With Git 2.15 (Q4 2017), "git branch" learned "-c/-C" to create a new branch by copying an existing one.

See commit c8b2cec (18 Jun 2017) by Ævar Arnfjörð Bjarmason (avar).
See commit 52d59cc, commit 5463caa (18 Jun 2017) by Sahil Dua (sahildua2305).
(Merged by Junio C Hamano -- gitster -- in commit 3b48045, 03 Oct 2017)

branch: add a --copy (-c) option to go with --move (-m)

Add the ability to --copy a branch and its reflog and configuration, this uses the same underlying machinery as the --move (-m) option except the reflog and configuration is copied instead of being moved.

This is useful for e.g. copying a topic branch to a new version, e.g. work to work-2 after submitting the work topic to the list, while preserving all the tracking info and other configuration that goes with the branch, and unlike --move keeping the other already-submitted branch around for reference.

Note: when copying a branch, you remain on your current branch.
As Junio C Hamano explains, the initial implementation of this new feature was modifying HEAD, which was not good:

When creating a new branch B by copying the branch A that happens to be the current branch, it also updates HEAD to point at the new branch.
It probably was made this way because "git branch -c A B" piggybacked its implementation on "git branch -m A B",

This does not match the usual expectation.
If I were sitting on a blue chair, and somebody comes and repaints it to red, I would accept ending up sitting on a chair that is now red (I am also OK to stand, instead, as there no longer is my favourite blue chair).

But if somebody creates a new red chair, modelling it after the blue chair I am sitting on, I do not expect to be booted off of the blue chair and ending up on sitting on the new red one.

.NET Format a string with fixed spaces

/// <summary>
/// Returns a string With count chars Left or Right value
/// </summary>
/// <param name="val"></param>
/// <param name="count"></param>
/// <param name="space"></param>
/// <param name="right"></param>
/// <returns></returns>
 public static string Formating(object val, int count, char space = ' ', bool right = false)
{
    var value = val.ToString();
    for (int i = 0; i < count - value.Length; i++) value = right ? value + space : space + value;
    return value;
}

Running an Excel macro via Python?

I would expect the error is to do with the macro you're calling, try the following bit of code:

Code

import os, os.path
import win32com.client

if os.path.exists("excelsheet.xlsm"):
    xl=win32com.client.Dispatch("Excel.Application")
    xl.Workbooks.Open(os.path.abspath("excelsheet.xlsm"), ReadOnly=1)
    xl.Application.Run("excelsheet.xlsm!modulename.macroname")
##    xl.Application.Save() # if you want to save then uncomment this line and change delete the ", ReadOnly=1" part from the open function.
    xl.Application.Quit() # Comment this out if your excel script closes
    del xl

How do I get JSON data from RESTful service using Python?

Well first of all I think rolling out your own solution for this all you need is urllib2 or httplib2 . Anyways in case you do require a generic REST client check this out .

https://github.com/scastillo/siesta

However i think the feature set of the library will not work for most web services because they shall probably using oauth etc .. . Also I don't like the fact that it is written over httplib which is a pain as compared to httplib2 still should work for you if you don't have to handle a lot of redirections etc ..