Programs & Examples On #Newlisp

newLISP is an Open Source scripting language in the Lisp family of programming languages developed by Lutz Mueller and released under the GNU General Public License.

problem with <select> and :after with CSS in WebKit

<div class="select">
<select name="you_are" id="dropdown" class="selection">
<option value="0" disabled selected>Select</option>
<option value="1">Student</option>
<option value="2">Full-time Job</option>
<option value="2">Part-time Job</option>
<option value="3">Job-Seeker</option>
<option value="4">Nothing Yet</option>
</select>
</div>

Insted of styling the select why dont you add a div out-side the select.

and style then in CSS

.select{
    width: 100%;
    height: 45px;
    position: relative;
}
.select::after{
    content: '\f0d7';
    position: absolute;
    top: 0px;
    right: 10px;
    font-family: 'Font Awesome 5 Free';
    font-weight: 900;
    color: #0b660b;
    font-size: 45px;
    z-index: 2;

}
#dropdown{
    -webkit-appearance: button;
       -moz-appearance: button;
            appearance: button;
            height: 45px;
            width: 100%;
        outline: none;
        border: none;
        border-bottom: 2px solid #0b660b;
        font-size: 20px;
        background-color: #0b660b23;
        box-sizing: border-box;
        padding-left: 10px;
        padding-right: 10px;
}

Log4j2 configuration - No log4j2 configuration file found

In my case I had to put it in the bin folder of my project even the fact that my classpath is set to the src folder. I have no idea why, but it's worth a try.

Convert UTF-8 to base64 string

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

if A vs if A is not None:

I created a file called test.py and ran it on the interpreter. You may change what you want to, to test for sure how things is going on behind the scenes.

import dis

def func1():

    matchesIterator = None

    if matchesIterator:

        print( "On if." );

def func2():

    matchesIterator = None

    if matchesIterator is not None:

        print( "On if." );

print( "\nFunction 1" );
dis.dis(func1)

print( "\nFunction 2" );
dis.dis(func2)

This is the assembler difference:

Source:

>>> import importlib
>>> reload( test )

Function 1
  6           0 LOAD_CONST               0 (None)
              3 STORE_FAST               0 (matchesIterator)

  8           6 LOAD_FAST                0 (matchesIterator)
              9 POP_JUMP_IF_FALSE       20

 10          12 LOAD_CONST               1 ('On if.')
             15 PRINT_ITEM
             16 PRINT_NEWLINE
             17 JUMP_FORWARD             0 (to 20)
        >>   20 LOAD_CONST               0 (None)
             23 RETURN_VALUE

Function 2
 14           0 LOAD_CONST               0 (None)
              3 STORE_FAST               0 (matchesIterator)

 16           6 LOAD_FAST                0 (matchesIterator)
              9 LOAD_CONST               0 (None)
             12 COMPARE_OP               9 (is not)
             15 POP_JUMP_IF_FALSE       26

 18          18 LOAD_CONST               1 ('On if.')
             21 PRINT_ITEM
             22 PRINT_NEWLINE
             23 JUMP_FORWARD             0 (to 26)
        >>   26 LOAD_CONST               0 (None)
             29 RETURN_VALUE
<module 'test' from 'test.py'>

How to find all occurrences of an element in a list

You can use a list comprehension:

indices = [i for i, x in enumerate(my_list) if x == "whatever"]

What does the "no version information available" error from linux dynamic linker mean?

Have you seen this already? The cause seems to be a very old libpam on one of the sides, probably on that customer.

Or the links for the version might be missing : http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html

Python: How do I make a subclass from a superclass?

In the answers above, the super is initialized without any (keyword) arguments. Often, however, you would like to do that, as well as pass on some 'custom' arguments of your own. Here is an example which illustrates this use case:

class SortedList(list):
    def __init__(self, *args, reverse=False, **kwargs):
        super().__init__(*args, **kwargs)       # Initialize the super class
        self.reverse = reverse
        self.sort(reverse=self.reverse)         # Do additional things with the custom keyword arguments

This is a subclass of list which, when initialized, immediately sorts itself in the direction specified by the reverse keyword argument, as the following tests illustrate:

import pytest

def test_1():
    assert SortedList([5, 2, 3]) == [2, 3, 5]

def test_2():
    SortedList([5, 2, 3], reverse=True) == [5, 3, 2]

def test_3():
    with pytest.raises(TypeError):
        sorted_list = SortedList([5, 2, 3], True)   # This doesn't work because 'reverse' must be passed as a keyword argument

if __name__ == "__main__":
    pytest.main([__file__])

Thanks to the passing on of *args to super, the list can be initialized and populated with items instead of only being empty. (Note that reverse is a keyword-only argument in accordance with PEP 3102).

File Permissions and CHMOD: How to set 777 in PHP upon file creation?

You just need to manually set the desired permissions with chmod():

private function writeFileContent($file, $content){
    $fp = fopen($file, 'w');
    fwrite($fp, $content);
    fclose($fp);

    // Set perms with chmod()
    chmod($file, 0777);
    return true;
}

Key value pairs using JSON

I see what you are trying to ask and I think this is the simplest answer to what you are looking for, given you might not know how many key pairs your are being sent.

Simple Key Pair JSON structure

var data = {
    'XXXXXX' : '100.0',
    'YYYYYYY' : '200.0',
    'ZZZZZZZ' : '500.0',
}

Usage JavaScript code to access the key pairs

for (var key in data) 
  { if (!data.hasOwnProperty(key))
    { continue; } 
    console.log(key + ' -> ' +  data[key]);
  };

Console output should look like this

XXXXXX -> 100.0 
YYYYYYY -> 200.0 
ZZZZZZZ -> 500.0

Here is a JSFiddle to show how it works.

How is "mvn clean install" different from "mvn install"?

clean is its own build lifecycle phase (which can be thought of as an action or task) in Maven. mvn clean install tells Maven to do the clean phase in each module before running the install phase for each module.

What this does is clear any compiled files you have, making sure that you're really compiling each module from scratch.

Remove shadow below actionbar

If you are working with ActionBarSherlock

In your theme add this:

<style name="MyTheme" parent="Theme.Sherlock">
    ....
    <item name="windowContentOverlay">@null</item>
    <item name="android:windowContentOverlay">@null</item>
    ....
</style>

HighCharts Hide Series Name from the Legend

If you don't want to show the series names in the legend you can disable them by setting showInLegend:false.

example:

series: [{
   showInLegend: false,             
   name: "<b><?php echo $title; ?></b>",
   data: [<?php echo $yaxis; ?>],
}]

You get other options here.

Reverse order of foreach list items

array_reverse() does not alter the source array, but returns a new array. (See array_reverse().) So you either need to store the new array first or just use function within the declaration of your for loop.

<?php 
    $input = array('a', 'b', 'c');
    foreach (array_reverse($input) as $value) {
        echo $value."\n";
    }
?>

The output will be:

c
b
a

So, to address to OP, the code becomes:

<?php
    $j=1;     
    foreach ( array_reverse($skills_nav) as $skill ) {
        $a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
        $a .= $skill->name;                 
        $a .= '</a></li>';
        echo $a;
        echo "\n";
        $j++;
}

Lastly, I'm going to guess that the $j was either a counter used in an initial attempt to get a reverse walk of $skills_nav, or a way to count the $skills_nav array. If the former, it should be removed now that you have the correct solution. If the latter, it can be replaced, outside of the loop, with a $j = count($skills_nav).

Simple pthread! C++

You should declare the thread main as:

void* print_message(void*) // takes one parameter, unnamed if you aren't using it

java.io.FileNotFoundException: the system cannot find the file specified

I was reading path from a properties file and didn't mention there was a space in the end. Make sure you don't have one.

How to sort an array based on the length of each element?

We can use Array.sort method to sort this array.

ES5 solution

_x000D_
_x000D_
var array = ["ab", "abcdefgh", "abcd"];

array.sort(function(a, b){return b.length - a.length});

console.log(JSON.stringify(array, null, '\t'));
_x000D_
_x000D_
_x000D_

For ascending sort order: a.length - b.length

For descending sort order: b.length - a.length

ES6 solution

Attention: not all browsers can understand ES6 code!

In ES6 we can use an arrow function expressions.

_x000D_
_x000D_
let array = ["ab", "abcdefgh", "abcd"];

array.sort((a, b) => b.length - a.length);

console.log(JSON.stringify(array, null, '\t'));
_x000D_
_x000D_
_x000D_

Slide up/down effect with ng-show and ng-animate

What's wrong with actually using ng-animate for ng-show as you mentioned?

<script src="lib/angulr.js"></script>
<script src="lib/angulr_animate.js"></script>
<script>
    var app=angular.module('ang_app', ['ngAnimate']);
    app.controller('ang_control01_main', function($scope) {

    });
</script>
<style>
    #myDiv {
        transition: .5s;
        background-color: lightblue;
        height: 100px;
    }
    #myDiv.ng-hide {
        height: 0;
    }
</style>
<body ng-app="ang_app" ng-controller="ang_control01_main">
    <input type="checkbox" ng-model="myCheck">
    <div id="myDiv" ng-show="myCheck"></div>
</body>

Embed YouTube Video with No Ads

For whom can help, nowadays in 2018, youtube have options for this:

(Example in Catalan, sorry :)

enter image description here

Translation of the 3 arrows : "Share" - "Embed" - "Show suggested videos when the video is finished"

Pretty-print a Map in Java

String result = objectMapper.writeValueAsString(map) - as simple as this!

Result:

{"2019-07-04T03:00":1,"2019-07-04T04:00":1,"2019-07-04T01:00":1,"2019-07-04T02:00":1,"2019-07-04T13:00":1,"2019-07-04T06:00":1 ...}

P.S. add Jackson JSON to your classpath.

Render partial from different folder (not shared)

Just include the path to the view, with the file extension.

Razor:

@Html.Partial("~/Views/AnotherFolder/Messages.cshtml", ViewData.Model.Successes)

ASP.NET engine:

<% Html.RenderPartial("~/Views/AnotherFolder/Messages.ascx", ViewData.Model.Successes); %>

If that isn't your issue, could you please include your code that used to work with the RenderUserControl?

How to get DateTime.Now() in YYYY-MM-DDThh:mm:ssTZD format using C#

Try this:

DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");

zzz is the timezone offset.

Using Pandas to pd.read_excel() for multiple worksheets of the same workbook

If you have saved the excel file in the same folder as your python program (relative paths) then you just need to mention sheet number along with file name.

Example:

 data = pd.read_excel("wt_vs_ht.xlsx", "Sheet2")
 print(data)
 x = data.Height
 y = data.Weight
 plt.plot(x,y,'x')
 plt.show()

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

Can I make dynamic styles in React Native?

If you still want to take advantage of StyleSheet.create and also have dynamic styles, try this out:

const Circle = ({initial}) => {


const initial = user.pending ? user.email[0] : user.firstName[0];

    const colorStyles = {
        backgroundColor: randomColor()
    };

    return (
        <View style={[styles.circle, colorStyles]}>
            <Text style={styles.text}>{initial.toUpperCase()}</Text>
        </View>
    );
};

const styles = StyleSheet.create({
    circle: {
        height: 40,
        width: 40,
        borderRadius: 30,
        overflow: 'hidden'
    },
    text: {
        fontSize: 12,
        lineHeight: 40,
        color: '#fff',
        textAlign: 'center'
    }
});

Notice how the style property of the View is set as an array that combines your stylesheet with your dynamic styles.

lambda expression join multiple tables with select and where clause

I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.

    var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
    .Select (m => new 
    {
        UserName = u.UserProfile.UserName,
        RoleName = u.Roles.RoleName
    });

How do I access named capturing groups in a .NET Regex?

This answers improves on Rashmi Pandit's answer, which is in a way better than the rest because that it seems to completely resolve the exact problem detailed in the question.

The bad part is that is inefficient and not uses the IgnoreCase option consistently.

Inefficient part is because regex can be expensive to construct and execute, and in that answer it could have been constructed just once (calling Regex.IsMatch was just constructing the regex again behind the scene). And Match method could have been called only once and stored in a variable and then linkand name should call Result from that variable.

And the IgnoreCase option was only used in the Match part but not in the Regex.IsMatch part.

I also moved the Regex definition outside the method in order to construct it just once (I think is the sensible approach if we are storing that the assembly with the RegexOptions.Compiled option).

private static Regex hrefRegex = new Regex("<td>\\s*<a\\s*href\\s*=\\s*(?:\"(?<link>[^\"]*)\"|(?<link>\\S+))\\s*>(?<name>.*)\\s*</a>\\s*</td>",  RegexOptions.IgnoreCase | RegexOptions.Compiled);

public static bool TryGetHrefDetails(string htmlTd, out string link, out string name)
{
    var matches = hrefRegex.Match(htmlTd);
    if (matches.Success)
    {
        link = matches.Result("${link}");
        name = matches.Result("${name}");
        return true;
    }
    else
    {
        link = null;
        name = null;
        return false;
    }
}

Is there any way to configure multiple registries in a single npmrc file

Some steps you can try. (its how we do it at my workplace)

  • Create a registry group with two (or more) repository source address. One would be your internal private and the other a proxy to npmjs giving priority to the internal one.
  • Make this group your registry in the .npmrc file. This way npm will always try to get it from the internal one, if not found get it from the proxy

Hope that helps.

how to pass parameter from @Url.Action to controller function

should you pass it in this way :

public ActionResult CreatePerson(int id) //controller 
window.location.href = "@Url.Action("CreatePerson", "Person",new { @id = 1});

Check if date is a valid one

Was able to find the solution. Since the date I am getting is in ISO format, only providing date to moment will validate it, no need to pass the dateFormat.

var date = moment("2016-10-19");

And then date.isValid() gives desired result.

How can I submit a POST form using the <a href="..."> tag?

You have to use Javascript submit function on your form object. Take a look in other functions.

<form action="showMessage.jsp" method="post">
    <a href="javascript:;" onclick="parentNode.submit();"><%=n%></a>
    <input type="hidden" name="mess" value=<%=n%>/>
</form>

How to change screen resolution of Raspberry Pi

TV Sony Bravia KLV-32T550A Below mention config works greatly You should add the following into the /boot/config.txt to force the output to HDMI and set the

resolution 82   1920x1080   60Hz    1080p

hdmi_ignore_edid=0xa5000080
hdmi_force_hotplug=1
hdmi_boost=7
hdmi_group=2
hdmi_mode=82
hdmi_drive=1

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

I guess it would work to use reflection to get whatever property you want to sort on:

IEnumerable<T> myEnumerables
var query=from enumerable in myenumerables
          where some criteria
          orderby GetPropertyValue(enumerable,"SomeProperty")
          select enumerable

private static object GetPropertyValue(object obj, string property)
{
    System.Reflection.PropertyInfo propertyInfo=obj.GetType().GetProperty(property);
    return propertyInfo.GetValue(obj, null);
}

Note that using reflection is considerably slower than accessing the property directly, so the performance would have to be investigated.

Managing jQuery plugin dependency in webpack

Add this to your plugins array in webpack.config.js

new webpack.ProvidePlugin({
    'window.jQuery': 'jquery',
    'window.$': 'jquery',
})

then require jquery normally

require('jquery');

If pain persists getting other scripts to see it, try explicitly placing it in the global context via (in the entry js)

window.$ = jQuery;

Cancel split window in Vim

to close all windows but the current one use:

CTRL+w, o

That is, first CTRL+w and then o.

CodeIgniter - Correct way to link to another page in a view

I assume you are meaning "internally" within your application.

you can create your own <a> tag and insert a url in the href like this

<a href="<?php echo site_url('controller/function/uri') ?>">Link</a>

OR you can use the URL helper this way to generate an <a> tag

anchor(uri segments, text, attributes)

So... to use it...

<?php echo anchor('controller/function/uri', 'Link', 'class="link-class"') ?>

and that will generate

<a href="http://domain.com/index.php/controller/function/uri" class="link-class">Link</a>

For the additional commented question

I would use my first example

so...

<a href="<?php echo site_url('controller/function') ?>"><img src="<?php echo base_url() ?>img/path/file.jpg" /></a>

for images (and other assets) I wouldn't put the file path within the php, I would just echo the base_url() and then add the path normally.

python: sys is not defined

In addition to the answers given above, check the last line of the error message in your console. In my case, the 'site-packages' path in sys.path.append('.....') was wrong.

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

You need to do the following:

public class CountryInfoResponse {

   @JsonProperty("geonames")
   private List<Country> countries; 

   //getter - setter
}

RestTemplate restTemplate = new RestTemplate();
List<Country> countries = restTemplate.getForObject("http://api.geonames.org/countryInfoJSON?username=volodiaL",CountryInfoResponse.class).getCountries();

It would be great if you could use some kind of annotation to allow you to skip levels, but it's not yet possible (see this and this)

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

I was getting this warning when I wanted to show a popup (bootstrap modal) on success/failure callback of Ajax request. Additionally setState was not working and my popup modal was not being shown.

Below was my situation-

<Component /> (Containing my Ajax function)
    <ChildComponent />
        <GrandChildComponent /> (Containing my PopupModal, onSuccess callback)

I was calling ajax function of component from grandchild component passing a onSuccess Callback (defined in grandchild component) which was setting state to show popup modal.

I changed it to -

<Component /> (Containing my Ajax function, PopupModal)
    <ChildComponent />
        <GrandChildComponent /> 

Instead I called setState (onSuccess Callback) to show popup modal in component (ajax callback) itself and problem solved.

In 2nd case: component was being rendered twice (I had included bundle.js two times in html).

How to check that a JCheckBox is checked?

Use the isSelected method.

You can also use an ItemListener so you'll be notified when it's checked or unchecked.

How to query MongoDB with "like"?

db.customer.find({"customerid": {"$regex": "CU_00000*", "$options": "i"}}).pretty()

When we are searching for string patterns, always it is better to use the above pattern as when we are not sure about case. Hope that helps!!!

Format number to 2 decimal places

How about CAST(2229.999 AS DECIMAL(6,2)) to get a decimal with 2 decimal places

The program can't start because cygwin1.dll is missing... in Eclipse CDT

This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.

There is a nice tool called DependencyWalker that you can download from http://www.dependencywalker.com . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.

Using DISTINCT and COUNT together in a MySQL Query

I would do something like this:

Select count(*), productid
from products
where keyword = '$keyword'
group by productid

that will give you a list like

count(*)    productid  
----------------------
 5           12345   
 3           93884   
 9           93493    

This allows you to see how many of each distinct productid ID is associated with the keyword.

Jquery validation plugin - TypeError: $(...).validate is not a function

It looks like the JavaScript error your getting is probably being caused by

password: {
    required:true,
    rangelenght:[4.20]
},

As the [4.20] should be [4,20], which i'd guess is throwing off the validation code in additional-methods hence giving the type error's you posted.

Edit: As others have noted in the below comments rangelenght is also misspelled & jquery.validate.js library appears to be missing (assuming its not compiled in to one of your other assets)

Generating a random & unique 8 character string using MySQL

I woudn't bother with the likelihood of collision. Just generate a random string and check if it exists. If it does, try again and you shouldn't need to do it more that a couple of times unless you have a huge number of plates already assigned.

Another solution for generating an 8-character long pseudo-random string in pure (My)SQL:

SELECT LEFT(UUID(), 8);

You can try the following (pseudo-code):

DO 
    SELECT LEFT(UUID(), 8) INTO @plate;
    INSERT INTO plates (@plate);
WHILE there_is_a_unique_constraint_violation
-- @plate is your newly assigned plate number

Since this post has received a unexpected level of attention, let me highlight ADTC's comment : the above piece of code is quite dumb and produces sequential digits.

For slightly less stupid randomness try something like this instead :

SELECT LEFT(MD5(RAND()), 8)

And for true (cryptograpically secure) randomness, use RANDOM_BYTES() rather than RAND() (but then I would consider moving this logic up to the application layer).

PHP Regex to check date is in YYYY-MM-DD format

You can use a preg_match with a checkdate php function

$date  = "2012-10-05";
$split = array();
if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $split))
{
    return checkdate($split[2], $split[3], $split[1]);
}

return false;

Centering a canvas

Given that canvas is nothing without JavaScript, use JavaScript too for sizing and positionning (you know: onresize, position:absolute, etc.)

Language Books/Tutorials for popular languages

Haskell:

O'Reilly Book:

  1. Real World Haskell, a great tutorial-oriented book on Haskell, available online and in print.

My favorite general, less academic online tutorials:

  1. The Haskell wikibook which contains all of the excellent Yet Another Haskell Tutorial. (This tutorial helps with specifics of setting up a Haskell distro and running example programs, for example.)
  2. Learn you a Haskell for Great Good, in the spirit of Why's Poignant Guide to Ruby but more to the point.
  3. Write yourself a Scheme in 48 hours. Get your hands dirty learning Haskell with a real project.

Books on Functional Programming with Haskell:

  1. Lambda calculus, combinators, more theoretical, but in a very down to earth manner: Davie's Introduction to Functional Programming Systems Using Haskell
  2. Laziness and program correctness, thinking functionally: Bird's Introduction to Functional Programming Using Haskell

Run parallel multiple commands at once in the same terminal

Use GNU Parallel:

(echo command1; echo command2) | parallel
parallel ::: command1 command2

To kill:

parallel ::: command1 command2 &
PID=$!
kill -TERM $PID
kill -TERM $PID

Sort a Custom Class List<T>

List<cTag> week = new List<cTag>();
week.Sort((x, y) => 
    DateTime.ParseExact(x.date, "dd.MM.yyyy", CultureInfo.InvariantCulture).CompareTo(
    DateTime.ParseExact(y.date, "dd.MM.yyyy", CultureInfo.InvariantCulture))
);

Convert base64 string to image

ImageIO.write() will compress the image by default - the compressed image has a smaller size but looks strange sometimes. I use BufferedOutputStream to save the byte array data - this will keep the original image size.

Here is the code:

import javax.xml.bind.DatatypeConverter;
import java.io.*;

public class ImageTest {
    public static void main(String[] args) {
        String base64String = "data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAHkAAAB5C...";
        String[] strings = base64String.split(",");
        String extension;
        switch (strings[0]) {//check image's extension
            case "data:image/jpeg;base64":
                extension = "jpeg";
                break;
            case "data:image/png;base64":
                extension = "png";
                break;
            default://should write cases for more images types
                extension = "jpg";
                break;
        }
        //convert base64 string to binary data
        byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
        String path = "C:\\Users\\Ene\\Desktop\\test_image." + extension;
        File file = new File(path);
        try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) {
            outputStream.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Is it better to use C void arguments "void foo(void)" or not "void foo()"?

C99 quotes

This answer aims to quote and explain the relevant parts of the C99 N1256 standard draft.

Definition of declarator

The term declarator will come up a lot, so let's understand it.

From the language grammar, we find that the following underline characters are declarators:

int f(int x, int y);
    ^^^^^^^^^^^^^^^

int f(int x, int y) { return x + y; }
    ^^^^^^^^^^^^^^^

int f();
    ^^^

int f(x, y) int x; int y; { return x + y; }
    ^^^^^^^

Declarators are part of both function declarations and definitions.

There are 2 types of declarators:

  • parameter type list
  • identifier list

Parameter type list

Declarations look like:

int f(int x, int y);

Definitions look like:

int f(int x, int y) { return x + y; }

It is called parameter type list because we must give the type of each parameter.

Identifier list

Definitions look like:

int f(x, y)
    int x;
    int y;
{ return x + y; }

Declarations look like:

int g();

We cannot declare a function with a non-empty identifier list:

int g(x, y);

because 6.7.5.3 "Function declarators (including prototypes)" says:

3 An identifier list in a function declarator that is not part of a definition of that function shall be empty.

It is called identifier list because we only give the identifiers x and y on f(x, y), types come after.

This is an older method, and shouldn't be used anymore. 6.11.6 Function declarators says:

1 The use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature.

and the Introduction explains what is an obsolescent feature:

Certain features are obsolescent, which means that they may be considered for withdrawal in future revisions of this International Standard. They are retained because of their widespread use, but their use in new implementations (for implementation features) or new programs (for language [6.11] or library features [7.26]) is discouraged

f() vs f(void) for declarations

When you write just:

void f();

it is necessarily an identifier list declaration, because 6.7.5 "Declarators" says defines the grammar as:

direct-declarator:
    [...]
    direct-declarator ( parameter-type-list )
    direct-declarator ( identifier-list_opt )

so only the identifier-list version can be empty because it is optional (_opt).

direct-declarator is the only grammar node that defines the parenthesis (...) part of the declarator.

So how do we disambiguate and use the better parameter type list without parameters? 6.7.5.3 Function declarators (including prototypes) says:

10 The special case of an unnamed parameter of type void as the only item in the list specifies that the function has no parameters.

So:

void f(void);

is the way.

This is a magic syntax explicitly allowed, since we cannot use a void type argument in any other way:

void f(void v);
void f(int i, void);
void f(void, int);

What can happen if I use an f() declaration?

Maybe the code will compile just fine: 6.7.5.3 Function declarators (including prototypes):

14 The empty list in a function declarator that is not part of a definition of that function specifies that no information about the number or types of the parameters is supplied.

So you can get away with:

void f();
void f(int x) {}

Other times, UB can creep up (and if you are lucky the compiler will tell you), and you will have a hard time figuring out why:

void f();
void f(float x) {}

See: Why does an empty declaration work for definitions with int arguments but not for float arguments?

f() and f(void) for definitions

f() {}

vs

f(void) {}

are similar, but not identical.

6.7.5.3 Function declarators (including prototypes) says:

14 An empty list in a function declarator that is part of a definition of that function specifies that the function has no parameters.

which looks similar to the description of f(void).

But still... it seems that:

int f() { return 0; }
int main(void) { f(1); }

is conforming undefined behavior, while:

int f(void) { return 0; }
int main(void) { f(1); }

is non conforming as discussed at: Why does gcc allow arguments to be passed to a function defined to be with no arguments?

TODO understand exactly why. Has to do with being a prototype or not. Define prototype.

dotnet ef not found in .NET Core 3

See the announcement for ASP.NET Core 3 Preview 4, which explains that this tool is no longer built-in and requires an explicit install:

The dotnet ef tool is no longer part of the .NET Core SDK

This change allows us to ship dotnet ef as a regular .NET CLI tool that can be installed as either a global or local tool. For example, to be able to manage migrations or scaffold a DbContext, install dotnet ef as a global tool typing the following command:

dotnet tool install --global dotnet-ef

To install a specific version of the tool, use the following command:

dotnet tool install --global dotnet-ef --version 3.1.4

The reason for the change is explained in the docs:

Why

This change allows us to distribute and update dotnet ef as a regular .NET CLI tool on NuGet, consistent with the fact that the EF Core 3.0 is also always distributed as a NuGet package.

In addition, you might need to add the following NuGet packages to your project:

IF... OR IF... in a windows batch file

Thanks for this post, it helped me a lot.

Dunno if it can help but I had the issue and thanks to you I found what I think is another way to solve it based on this boolean equivalence:

"A or B" is the same as "not(not A and not B)"

Thus:

IF [%var%] == [1] OR IF [%var%] == [2] ECHO TRUE

Becomes:

IF not [%var%] == [1] IF not [%var%] == [2] ECHO FALSE

A simple algorithm for polygon intersection

If you do not care about predictable run time you could try by first splitting your polygons into unions of convex polygons and then pairwise computing the intersection between the sub-polygons.

This would give you a collection of convex polygons such that their union is exactly the intersection of your starting polygons.

How to center a navigation bar with CSS or HTML?

You could also use float and inline-block to center your nav like the following:

nav li {
   float: left;
}
nav {
   display: inline-block;
}

Javascript how to parse JSON array

In a for-in-loop the running variable holds the property name, not the property value.

for (var counter in jsonData.counters) {
    console.log(jsonData.counters[counter].counter_name);
}

But as counters is an Array, you have to use a normal for-loop:

for (var i=0; i<jsonData.counters.length; i++) {
    var counter = jsonData.counters[i];
    console.log(counter.counter_name);
}

How to target the href to div

From what I know this will not be possible only with css. Heres a solution how you could make it work with jQuery which is a javascript Library. More about jquery here: http://jquery.com/

Here is a working example : http://jsfiddle.net/uyDbL/

$(document).ready(function(){
    $('a').on('click',function(){
        var aID = $(this).attr('href');
        var elem = $(''+aID).html();

        $('.target').html(elem);
    });
});

Update 2018 (as this still gets upvoted) here is a plain javascript solution without jQuery

_x000D_
_x000D_
var target = document.querySelector('.target');_x000D_
[...document.querySelectorAll('table a')].forEach(function(element){_x000D_
    element.addEventListener('click', function(){_x000D_
        target.innerHTML = document.querySelector(element.getAttribute('href')).innerHTML;_x000D_
    });_x000D_
});
_x000D_
a{_x000D_
    text-decoration:none;_x000D_
    color:black;_x000D_
}_x000D_
_x000D_
.target{_x000D_
    width:50%;_x000D_
    height:200px;_x000D_
    border:solid black 1px; _x000D_
}_x000D_
_x000D_
#m1, #m2, #m3, #m4, #m5, #m6, #m7, #m8, #m9{_x000D_
    display:none;_x000D_
}
_x000D_
<table border="0">_x000D_
<tr>_x000D_
<td>_x000D_
<hr>_x000D_
<a href="#m1">fea1</a><br><hr>_x000D_
<a href="#m2">fea2</a><br><hr>_x000D_
<a href="#m3">fea3</a><br><hr>_x000D_
<a href="#m4">fea4</a><br><hr>_x000D_
<a href="#m5">fea5</a><br><hr>_x000D_
<a href="#m6">fea6</a><br><hr>_x000D_
<a href="#m7">fea7</a><br><hr>_x000D_
<a href="#m8">fea8</a><br><hr>_x000D_
<a href="#m9">fea9</a>_x000D_
<hr>_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
_x000D_
<div class="target">_x000D_
_x000D_
</div>_x000D_
_x000D_
_x000D_
<div id="m1">dasdasdasd</div>_x000D_
<div id="m2">dadasdasdasd</div>_x000D_
<div id="m3">sdasdasds</div>_x000D_
<div id="m4">dasdasdsad</div>_x000D_
<div id="m5">dasdasd</div>_x000D_
<div id="m6">asdasdad</div>_x000D_
<div id="m7">asdasda</div>_x000D_
<div id="m8">dasdasd</div>_x000D_
<div id="m9">dasdasdsgaswa</div>
_x000D_
_x000D_
_x000D_

How can I get the concatenation of two lists in Python without modifying either one?

And if you have more than two lists to concatenate:

import operator
from functools import reduce  # For Python 3
list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
reduce(operator.add, [list1, list2, list3])

# or with an existing list
all_lists = [list1, list2, list3]
reduce(operator.add, all_lists)

It doesn't actually save you any time (intermediate lists are still created) but nice if you have a variable number of lists to flatten, e.g., *args.

Error - replacement has [x] rows, data has [y]

TL;DR ...and late to the party, but that short explanation might help future googlers..

In general that error message means that the replacement doesn't fit into the corresponding column of the dataframe.

A minimal example:

df <- data.frame(a = 1:2); df$a <- 1:3

throws the error

Error in $<-.data.frame(*tmp*, a, value = 1:3) : replacement has 3 rows, data has 2

which is clear, because the vector a of df has 2 entries (rows) whilst the vector we try to replace it has 3 entries (rows).

change type of input field with jQuery

I haven't tested in IE (since I needed this for an iPad site) - a form I couldn't change the HTML but I could add JS:

document.getElementById('phonenumber').type = 'tel';

(Old school JS is ugly next to all the jQuery!)

But, http://bugs.jquery.com/ticket/1957 links to MSDN: "As of Microsoft Internet Explorer 5, the type property is read/write-once, but only when an input element is created with the createElement method and before it is added to the document." so maybe you could duplicate the element, change the type, add to DOM and remove the old one?

.prop('checked',false) or .removeAttr('checked')?

I recommend to use both, prop and attr because I had problems with Chrome and I solved it using both functions.

if ($(':checkbox').is(':checked')){
    $(':checkbox').prop('checked', true).attr('checked', 'checked');
}
else {
    $(':checkbox').prop('checked', false).removeAttr('checked');
}

Bootstrap push div content to new line

If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.

This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
  <div class="row">_x000D_
    <div class="col-sm-3">Under me should be a DIV</div>_x000D_
    <div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
    <div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Selecting rows where remainder (modulo) is 1 after division by 2?

MySQL, SQL Server, PostgreSQL, SQLite support using the percent sign as the modulus:

WHERE column % 2 = 1

For Oracle, you have to use the MOD function:

WHERE MOD(column, 2) = 1

Disabled form fields not submitting data

add CSS or class to the input element which works in select and text tags like

style="pointer-events: none;background-color:#E9ECEF"

fatal: git-write-tree: error building trees

Use:

git reset --mixed

instead of git reset --hard. You will not lose any changes.

How do I display the current value of an Android Preference in the Preference summary?

My option is to extend ListPreference and it's clean:

public class ListPreferenceShowSummary extends ListPreference {

    private final static String TAG = ListPreferenceShowSummary.class.getName();

    public ListPreferenceShowSummary(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ListPreferenceShowSummary(Context context) {
        super(context);
        init();
    }

    private void init() {

        setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

            @Override
            public boolean onPreferenceChange(Preference arg0, Object arg1) {
                arg0.setSummary(getEntry());
                return true;
            }
        });
    }

    @Override
    public CharSequence getSummary() {
        return super.getEntry();
    }
}

Then you add in your settings.xml:

<yourpackage.ListPreferenceShowSummary
    android:key="key" android:title="title"
    android:entries="@array/entries" android:entryValues="@array/values"
    android:defaultValue="first value"/>

Is it possible to make abstract classes in Python?

Here's a very easy way without having to deal with the ABC module.

In the __init__ method of the class that you want to be an abstract class, you can check the "type" of self. If the type of self is the base class, then the caller is trying to instantiate the base class, so raise an exception. Here's a simple example:

class Base():
    def __init__(self):
        if type(self) is Base:
            raise Exception('Base is an abstract class and cannot be instantiated directly')
        # Any initialization code
        print('In the __init__  method of the Base class')

class Sub(Base):
    def __init__(self):
        print('In the __init__ method of the Sub class before calling __init__ of the Base class')
        super().__init__()
        print('In the __init__ method of the Sub class after calling __init__ of the Base class')

subObj = Sub()
baseObj = Base()

When run, it produces:

In the __init__ method of the Sub class before calling __init__ of the Base class
In the __init__  method of the Base class
In the __init__ method of the Sub class after calling __init__ of the Base class
Traceback (most recent call last):
  File "/Users/irvkalb/Desktop/Demo files/Abstract.py", line 16, in <module>
    baseObj = Base()
  File "/Users/irvkalb/Desktop/Demo files/Abstract.py", line 4, in __init__
    raise Exception('Base is an abstract class and cannot be instantiated directly')
Exception: Base is an abstract class and cannot be instantiated directly

This shows that you can instantiate a subclass that inherits from a base class, but you cannot instantiate the base class directly.

How to get all groups that a user is a member of?

Studying all comments presented gave me a starting point (thanks for such) but left me with several unresolved issues. As result here is my answer. The code snippet provided does a little more than what is asked for but it provides helpful debugging info.

[array] $script:groupsdns = @()
function Get-ADPrincipalGroupMembershipRecursive() 
{
  Param( [string] $dn, [int] $level = 0, [array] $groups = @() )

  #if(($groupsdns | where { $_.DistinguishedName -eq $dn }).Count -ne 0 ) { return $groups } # dependency on next statement
  #$groupsdns += (Get-ADObject $dn -Properties MemberOf) # Get-ADObject cannot find an object with identity
  if ($script:groupsdns.Contains($dn)) { return $groups }
  $script:groupsdns += $dn
  $mo = $Null
  $mo = Get-ADObject $dn -Properties MemberOf # Get-ADObject cannot find an object with identity
  $group = ($dn + " (" + $level.ToString())
  if ($mo -eq $Null) { $group += "!" }
  $group += ")"
  $groups += $group
  foreach( $groupdn in $mo.MemberOf )
  {
    $groups = Get-ADPrincipalGroupMembershipRecursive -dn $groupdn -level ($level+1) -groups $groups
  }
  if ($level -le 0) 
  { 
    $primarygroupdn = (Get-ADUser -Identity $dn -Properties PrimaryGroup).PrimaryGroup 
    $groups = Get-ADPrincipalGroupMembershipRecursive -dn $primarygroupdn -level ($level+1) -groups $groups
  }
  return $groups
}
$adusergroups = Get-ADPrincipalGroupMembershipRecursive -dn $aduser.DistinguishedName
$adusergroups | ft -AutoSize | `
              Out-File -Width 512 Get-ADPrincipalGroupMembershipRecursive.txt #-Append #-Wrap # | Sort-Object -Property Name

The real difference between "int" and "unsigned int"

the type just tells you what the bit pattern is supposed to represent. the bits are only what you make of them. the same sequences can be interpreted in different ways.

R Markdown - changing font size and font type in html output

I had the same issue and solved by making sure that 1. when you make the style.css file, make sure you didn't just rename a text file as "style.css", make sure it's really the .css format (e.g, use visual studio code); 2. put that style.css file in the same folder with your .rmd file. Hopefully this works for you.

Getting attributes of Enum's value

Performance matters

If you want better performance this is the way to go:

public static class AdvancedEnumExtensions
{
    /// <summary>
    /// Gets the custom attribute <typeparamref name="T"/> for the enum constant, if such a constant is defined and has such an attribute; otherwise null.
    /// </summary>
    public static T GetCustomAttribute<T>(this Enum value) where T : Attribute
    {
        return GetField(value)?.GetCustomAttribute<T>(inherit: false);
    }

    /// <summary>
    /// Gets the FieldInfo for the enum constant, if such a constant is defined; otherwise null.
    /// </summary>
    public static FieldInfo GetField(this Enum value)
    {
        ulong u64 = ToUInt64(value);
        return value
            .GetType()
            .GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
            .Where(f => ToUInt64(f.GetRawConstantValue()) == u64)
            .FirstOrDefault();
    }

    /// <summary>
    /// Checks if an enum constant is defined for this enum value
    /// </summary>
    public static bool IsDefined(this Enum value)
    {
        return GetField(value) != null;
    }

    /// <summary>
    /// Converts the enum value to UInt64
    /// </summary>
    public static ulong ToUInt64(this Enum value) => ToUInt64((object)value);

    private static ulong ToUInt64(object value)
    {
        switch (Convert.GetTypeCode(value))
        {
            case TypeCode.SByte:
            case TypeCode.Int16:
            case TypeCode.Int32:
            case TypeCode.Int64:
                return unchecked((ulong)Convert.ToInt64(value, CultureInfo.InvariantCulture));

            case TypeCode.Byte:
            case TypeCode.UInt16:
            case TypeCode.UInt32:
            case TypeCode.UInt64:
            case TypeCode.Char:
            case TypeCode.Boolean:
                return Convert.ToUInt64(value, CultureInfo.InvariantCulture);

            default: throw new InvalidOperationException("UnknownEnumType");
        }
    }
}

Why does this have better performance?

Because the built-in methods all use code very similar to this except they also run a bunch of other code we don't care about. C#'s Enum code is quite horrible in general.

The above code has been Linq-ified and streamlined so it only contains the bits we care about.

Why is the built-in code slow?

First regarding Enum.ToString() -vs- Enum.GetName(..)

Always use the latter. (Or better yet neither, as will become clear below.)

ToString() uses the latter internally, but again, also does a bunch of other stuff we don't want, e.g. tries to combine flags, print out numbers etc. We are only interested in constants defined inside the enum.

Enum.GetName in turn gets all fields, creates a string array for all names, uses the above ToUInt64 on all of their RawConstantValues to create an UInt64 array of all values, sorts both arrays according to the UInt64 value, and finally gets the name from the name-array by doing a BinarySearch in the UInt64-array to find the index of the value we wanted.

...and then we throw the fields and the sorted arrays away use that name to find the field again.

One word: "Ugh!"

T-SQL stored procedure that accepts multiple Id values

Erland Sommarskog has maintained the authoritative answer to this question for the last 16 years: Arrays and Lists in SQL Server.

There are at least a dozen ways to pass an array or list to a query; each has their own unique pros and cons.

I really can't recommend enough to read the article to learn about the tradeoffs among all these options.

Postgres where clause compare timestamp

Assuming you actually mean timestamp because there is no datetime in Postgres

Cast the timestamp column to a date, that will remove the time part:

select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

This will return all rows from July, 15th.

Note that the above will not use an index on the_timestamp_column. If performance is critical, you need to either create an index on that expression or use a range condition:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

how to convert date to a format `mm/dd/yyyy`

As your data already in varchar, you have to convert it into date first:

select convert(varchar(10), cast(ts as date), 101) from <your table>

Why don't self-closing script elements work?

The self closing script tag won't work, because the script tag can contain inline code, and HTML is not smart enough to turn on or off that feature based on the presence of an attribute.

On the other hand, HTML does have an excellent tag for including references to outside resources: the <link> tag, and it can be self-closing. It's already used to include stylesheets, RSS and Atom feeds, canonical URIs, and all sorts of other goodies. Why not JavaScript?

If you want the script tag to be self enclosed you can't do that as I said, but there is an alternative, though not a smart one. You can use the self closing link tag and link to your JavaScript by giving it a type of text/javascript and rel as script, something like below:

<link type="text/javascript" rel ="script" href="/path/tp/javascript" />

How to use PrintWriter and File classes in Java?

You should have a clear idea of exceptions in java. In java there are checked exceptions and unchecked exceptions.

Checked exceptions are checked (not thrown,just checked) by the compiler at Compile time for the smooth execution of the program at run time.

NOTE: And in our program if their is a chance that a checked exception will rise, then we should handle that checked exception either by try catch or by throws key word.Otherwise we will get a compile time Error:

CE:Unexpected Exception java.io.FileNotFoundException;must be caught or declared to be thrown.

How to resolve: 1.Put your code in try catch block:

2.use throws keyword as shown by other guys above.

Advice:Read more about Exceptions.(I personally love this topic)

High-precision clock in Python

The original question specifically asked for Unix but multiple answers have touched on Windows, and as a result there is misleading information on windows. The default timer resolution on windows is 15.6ms you can verify here.

Using a slightly modified script from cod3monk3y I can show that windows timer resolution is ~15milliseconds by default. I'm using a tool available here to modify the resolution.

Script:

import time

# measure the smallest time delta by spinning until the time changes
def measure():
    t0 = time.time()
    t1 = t0
    while t1 == t0:
        t1 = time.time()
    return t1-t0

samples = [measure() for i in range(30)]

for s in samples:
    print(f'time delta: {s:.4f} seconds') 

enter image description here

enter image description here

These results were gathered on windows 10 pro 64-bit running python 3.7 64-bit.

Loop through all the rows of a temp table and call a stored procedure for each row

you could use a cursor:

DECLARE @id int
DECLARE @pass varchar(100)

DECLARE cur CURSOR FOR SELECT Id, Password FROM @temp
OPEN cur

FETCH NEXT FROM cur INTO @id, @pass

WHILE @@FETCH_STATUS = 0 BEGIN
    EXEC mysp @id, @pass ... -- call your sp here
    FETCH NEXT FROM cur INTO @id, @pass
END

CLOSE cur    
DEALLOCATE cur

how to prevent adding duplicate keys to a javascript array

The logic is wrong. Consider this:

x = ["a","b","c"]
x[0]     // "a"
x["0"]   // "a"
0 in x   // true
"0" in x // true
x.hasOwnProperty(0)   // true
x.hasOwnProperty("0") // true

There is no reason to loop to check for key (or indices for arrays) existence. Now, values are a different story...

Happy coding

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

How to use onClick event on react Link component?

You are passing hello() as a string, also hello() means execute hello immediately.

try

onClick={hello}

Dynamically create an array of strings with malloc

char **orderIds;

orderIds = malloc(variableNumberOfElements * sizeof(char*));

for(int i = 0; i < variableNumberOfElements; i++) {
  orderIds[i] = malloc((ID_LEN + 1) * sizeof(char));
  strcpy(orderIds[i], your_string[i]);
}

How to create a WPF Window without a border that can be resized via a grip only?

I was having difficulty getting the answer by @fernando-aguirre using WindowChrome to work. It was not working in my case because I was overriding OnSourceInitialized in the MainWindow and not calling the base class method.

protected override void OnSourceInitialized(EventArgs e)
{
    ViewModel.Initialize(this);
    base.OnSourceInitialized(e); // <== Need to call this!
}

This stumped me for a very long time.

How do I include a pipe | in my linux find -exec command?

You can also pipe to a while loop that can do multiple actions on the file which find locates. So here is one for looking in jar archives for a given java class file in folder with a large distro of jar files

find /usr/lib/eclipse/plugins -type f -name \*.jar | while read jar; do echo $jar; jar tf $jar | fgrep IObservableList ; done

the key point being that the while loop contains multiple commands referencing the passed in file name separated by semicolon and these commands can include pipes. So in that example I echo the name of the matching file then list what is in the archive filtering for a given class name. The output looks like:

/usr/lib/eclipse/plugins/org.eclipse.core.contenttype.source_3.4.1.R35x_v20090826-0451.jar /usr/lib/eclipse/plugins/org.eclipse.core.databinding.observable_1.2.0.M20090902-0800.jar org/eclipse/core/databinding/observable/list/IObservableList.class /usr/lib/eclipse/plugins/org.eclipse.search.source_3.5.1.r351_v20090708-0800.jar /usr/lib/eclipse/plugins/org.eclipse.jdt.apt.core.source_3.3.202.R35x_v20091130-2300.jar /usr/lib/eclipse/plugins/org.eclipse.cvs.source_1.0.400.v201002111343.jar /usr/lib/eclipse/plugins/org.eclipse.help.appserver_3.1.400.v20090429_1800.jar

in my bash shell (xubuntu10.04/xfce) it really does make the matched classname bold as the fgrep highlights the matched string; this makes it really easy to scan down the list of hundreds of jar files that were searched and easily see any matches.

on windows you can do the same thing with:

for /R %j in (*.jar) do @echo %j & @jar tf %j | findstr IObservableList

note that in that on windows the command separator is '&' not ';' and that the '@' suppresses the echo of the command to give a tidy output just like the linux find output above; although findstr is not make the matched string bold so you have to look a bit closer at the output to see the matched class name. It turns out that the windows 'for' command knows quite a few tricks such as looping through text files...

enjoy

SFTP in Python? (platform independent)

fsspec is a great option for this, it offers a filesystem like implementation of sftp.

from fsspec.implementations.sftp import SFTPFileSystem
fs = SFTPFileSystem(host=host, username=username, password=password)

# list a directory
fs.ls("/")

# open a file
with fs.open(file_name) as file:
    content = file.read()

Also worth noting that fsspec uses paramiko in the implementation.

XMLHttpRequest (Ajax) Error

I see 2 possible problems:

Problem 1

  • the XMLHTTPRequest object has not finished loading the data at the time you are trying to use it

Solution: assign a callback function to the objects "onreadystatechange" -event and handle the data in that function

xmlhttp.onreadystatechange = callbackFunctionName;

Once the state has reached DONE (4), the response content is ready to be read.

Problem 2

  • the XMLHTTPRequest object does not exist in all browsers (by that name)

Solution: Either use a try-catch for creating the correct object for correct browser ( ActiveXObject in IE) or use a framework, for example jQuery ajax-method

Note: if you decide to use jQuery ajax-method, you assign the callback-function with jqXHR.done()

How to update Xcode from command line

Hello I solved it like this:

Install Application> Xcode.app> Contents> Resources> Packages> XcodeSystemResources.pkg.

Use python requests to download CSV

From a little search, that I understand the file should be opened in universal newline mode, which you cannot directly do with a response content (I guess).

To finish the task, you can either save the downloaded content to a temporary file, or process it in memory.

Save as file:

import requests
import csv
import os

temp_file_name = 'temp_csv.csv'
url = 'http://url.to/file.csv'
download = requests.get(url)

with open(temp_file_name, 'w') as temp_file:
    temp_file.writelines(download.content)

with open(temp_file_name, 'rU') as temp_file:
    csv_reader = csv.reader(temp_file, dialect=csv.excel_tab)
    for line in csv_reader:
        print line

# delete the temp file after process
os.remove(temp_file_name)

In memory:

(To be updated)

Algorithm to detect overlapping periods

--logic FOR OVERLAPPING DATES
DECLARE @StartDate datetime  --Reference start date
DECLARE @EndDate datetime    --Reference end date
DECLARE @NewStartDate datetime --New Start date
DECLARE @NewEndDate datetime   --New End Date

Select 
(Case 
    when @StartDate is null 
        then @NewStartDate
    when (@StartDate<@NewStartDate and  @EndDate < @NewStartDate)
        then @NewStartDate
    when (@StartDate<@NewStartDate and  @EndDate > @NewEndDate)
        then @NewStartDate
    when (@StartDate<@NewStartDate and  @EndDate > @NewStartDate)
        then @NewStartDate  
    when (@StartDate>@NewStartDate and  @NewEndDate < @StartDate)
        then @NewStartDate
    else @StartDate end) as StartDate,  

(Case 
    when @EndDate is null   
        then @NewEndDate
    when (@EndDate>@NewEndDate and @Startdate < @NewEndDate)
        then @NewEndDate
    when (@EndDate>@NewEndDate and @Startdate > @NewEndDate)
        then @NewEndDate
    when (@EndDate<@NewEndDate and @NewStartDate > @EndDate)
        then @NewEndDate
    else @EndDate end) as EndDate

Distrubution logic

How can I use querySelector on to pick an input element by name?

You can try 'input[name="pwd"]':

function checkForm(){
     var form = document.forms[0];
     var selectElement = form.querySelector('input[name="pwd"]');
     var selectedValue = selectElement.value;
}

take a look a this http://jsfiddle.net/2ZL4G/1/

force line break in html table cell

You could put the text into a div (or other container) with a width of 50%.

http://jsfiddle.net/6gjsd/

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

0000 0000 -> this is an 8-bit binary number. A digit represents a bit.

You count like so:

0000 0000 ? (0)

0000 0001 ? (1)

0000 0010 ? (2)

0000 0011 ? (3)

Each bit can be one of two values: on or off. The total highest number can be represented by multiplication:

2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 - 1 = 255

Or

2^8 - 1. 

We subtract one because the first number is 0.

255 can hold quite a bit (no pun intended) of values.

As we use more bits the max value goes up exponentially. Therefore for many purposes, adding more bits is overkill.

How to check if an element is off-screen

There's a jQuery plugin here which allows users to test whether an element falls within the visible viewport of the browser, taking the browsers scroll position into account.

$('#element').visible();

You can also check for partial visibility:

$('#element').visible( true);

One drawback is that it only works with vertical positioning / scrolling, although it should be easy enough to add horizontal positioning into the mix.

What are carriage return, linefeed, and form feed?

\f is used for page break. You cannot see any effect in the console. But when you use this character constant in your file then you can see the difference.

Other example is that if you can redirect your output to a file then you don't have to write a file or use file handling.

For ex:

Write this code in c++

void main()    
{
    clrscr();
    cout<<"helloooooo" ;

    cout<<"\f";
    cout<<"hiiiii" ;

}

and when you compile this it generate an exe(for ex. abc.exe)

then you can redirect your output to a file using this:

abc > xyz.doc

then open the file xyz.doc you can see the actual page break between hellooo and hiiii....

Printing 2D array in matrix format

like so:

long[,] arr = new long[4, 4] { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 } };

var rowCount = arr.GetLength(0);
var colCount = arr.GetLength(1);
for (int row = 0; row < rowCount; row++)
{
    for (int col = 0; col < colCount; col++)               
        Console.Write(String.Format("{0}\t", arr[row,col]));
    Console.WriteLine();
} 

jQuery - select the associated label element of a input field

You shouldn't rely on the order of elements by using prev or next. Just use the for attribute of the label, as it should correspond to the ID of the element you're currently manipulating:

var label = $("label[for='" + $(this).attr('id') + "']");

However, there are some cases where the label will not have for set, in which case the label will be the parent of its associated control. To find it in both cases, you can use a variation of the following:

var label = $('label[for="' + $(this).attr('id') + '"]');

if(label.length <= 0) {
    var parentElem = $(this).parent(),
        parentTagName = parentElem.get(0).tagName.toLowerCase();

    if(parentTagName == "label") {
        label = parentElem;
    }
}

I hope this helps!

How can I remount my Android/system as read-write in a bash script using adb?

Otherwise... if

getenforce

returns

Enforcing

Then maybe you should call

setenforce 0 
mount -o rw,remount /system 
setenforce 1

How to cd into a directory with space in the name?

As an alternative to using quotes, for a directory you want to go to often, you could use the cdable_vars shell option:

shopt -s cdable_vars
docs='/cygdrive/c/Users/my dir/Documents'

Now, to change into that directory from anywhere, you can use

cd docs

and the shell will indicate which directory it changed to:

$ cd docs
/cygdrive/c/Users/my dir/Documents

What is the ideal data type to use when storing latitude / longitude in a MySQL database?

Based on this wiki article http://en.wikipedia.org/wiki/Decimal_degrees#Accuracy the appropriate data type in MySQL is Decimal(9,6) for storing the longitude and latitude in separate fields.

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

If you need to override IE's Compatibility View Settings for intranet sites you can do so in the web.config (IIS7) or through the custom HTTP headers in the web site's properties (IIS6) and set X-UA-Compatible there. The meta tag doesn't override IE's intranet setting in Compatibility View Settings, but if you set it at the hosting server it will override the compatibility.

Example for web.config in IIS7:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="X-UA-Compatible" value="IE=EmulateIE8" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

Edit: I removed the clear code from just before the add; it was an unnecessary oversight from copying and pasting. Good catch, commenters!

Element-wise addition of 2 lists?

  • The zip function is useful here, used with a list comprehension v1, v2.
  • If you have a list of lists (instead of just two lists) you can use v3.
  • For lists with different length (for example: By adding 1 to the end of the first/secound list), then you can try something like this (using zip_longest) - v4
first = [1, 2, 3, 1]
second = [4, 5, 6]

output: [5, 7, 9, 1]
  • If you have an unknown number of lists of the same length, you can use the function v5.

  • v6 - The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y.

  • v7 - Assuming both lists first and second have same length, you do not need zip or anything else.

################
first = [1, 2, 3]
second = [4, 5, 6]

####### v1 ########
third1 = [sum(i) for i in zip(first,second)]

####### v2 ########
third2 = [x + y for x, y in zip(first, second)]

####### v3 ########
lists_of_lists = [[1, 2, 3], [4, 5, 6]]
third3 = [sum(x) for x in zip(*lists_of_lists)]

####### v4 ########
from itertools import zip_longest
third4 = list(map(sum, zip_longest(first, second, fillvalue=0)))

####### v5 ########
def sum_lists(*args):
    return list(map(sum, zip(*args)))

third5 = sum_lists(first, second)

####### v6 ########
import operator
third6 = list(map(operator.add, first,second))

####### v7 ########
third7 =[first[i]+second[i] for i in range(len(first))]

####### v(i) ########

print(third1) # [5, 7, 9]
print(third2) # [5, 7, 9]
print(third3) # [5, 7, 9]
print(third4) # [5, 7, 9]
print(third5) # [5, 7, 9]
print(third6) # [5, 7, 9]
print(third7) # [5, 7, 9]

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

The inner exception of bug says Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304'

Changing the AppPool setting False for Enable 32-bit Application solved the issue

Conditionally ignoring tests in JUnit 4

You should checkout Junit-ext project. They have RunIf annotation that performs conditional tests, like:

@Test
@RunIf(DatabaseIsConnected.class)
public void calculateTotalSalary() {
    //your code there
}

class DatabaseIsConnected implements Checker {
   public boolean satisify() {
        return Database.connect() != null;
   }
}

[Code sample taken from their tutorial]

How can I calculate divide and modulo for integers in C#?

Before asking questions of this kind, please check MSDN documentation.

When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2. To determine the remainder of 7 / 3, use the remainder operator (%).

int a = 5;
int b = 3;

int div = a / b; //quotient is 1
int mod = a % b; //remainder is 2

Android: how to hide ActionBar on certain activities

For selectively hiding Actionbar in activities:

Add the following code to onCreate (preferably on the last line of the function)

Kotlin:

supportActionBar?.hide()

Java:

getSupportActionBar().hide();

Laravel 4: Redirect to a given url

Yes, it's

use Illuminate\Support\Facades\Redirect;

return Redirect::to('http://heera.it');

Check the documentation.

Update: Redirect::away('url') (For external link, Laravel Version 4.19):

public function away($path, $status = 302, $headers = array())
{
    return $this->createRedirect($path, $status, $headers);
}

List append() in for loop

No need to re-assign.

a=[]
for i in range(5):    
    a.append(i)
a

casting Object array to Integer array error

You can't cast an Object array to an Integer array. You have to loop through all elements of a and cast each one individually.

Object[] a = new Object[1];
Integer b=1;
a[0]=b;
Integer[] c = new Integer[a.length];
for(int i = 0; i < a.length; i++)
{
    c[i] = (Integer) a[i];
}

Edit: I believe the rationale behind this restriction is that when casting, the JVM wants to ensure type-safety at runtime. Since an array of Objects can be anything besides Integers, the JVM would have to do what the above code is doing anyway (look at each element individually). The language designers decided they didn't want the JVM to do that (I'm not sure why, but I'm sure it's a good reason).

However, you can cast a subtype array to a supertype array (e.g. Integer[] to Object[])!

How to sort findAll Doctrine's method?

This works for me:

$entities = $em->getRepository('MyBundle:MyTable')->findBy(array(),array('name' => 'ASC'));

Keeping the first array empty fetches back all data, it worked in my case.

How to embed HTML into IPython output?

Some time ago Jupyter Notebooks started stripping JavaScript from HTML content [#3118]. Here are two solutions:

Serving Local HTML

If you want to embed an HTML page with JavaScript on your page now, the easiest thing to do is to save your HTML file to the directory with your notebook and then load the HTML as follows:

from IPython.display import IFrame

IFrame(src='./nice.html', width=700, height=600)

Serving Remote HTML

If you prefer a hosted solution, you can upload your HTML page to an Amazon Web Services "bucket" in S3, change the settings on that bucket so as to make the bucket host a static website, then use an Iframe component in your notebook:

from IPython.display import IFrame

IFrame(src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600)

This will render your HTML content and JavaScript in an iframe, just like you can on any other web page:

_x000D_
_x000D_
<iframe src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600></iframe>
_x000D_
_x000D_
_x000D_

How to receive JSON as an MVC 5 action method parameter

fwiw, this didn't work for me until I had this in the ajax call:

contentType: "application/json; charset=utf-8",

using Asp.Net MVC 4.

Display image at 50% of its "native" size

This should work:

img {
    max-width: 50%;
    height: auto;
}

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

You can have an auto-Incrementing column that is not the PRIMARY KEY, as long as there is an index (key) on it:

CREATE TABLE members ( 
  id int(11)  UNSIGNED NOT NULL AUTO_INCREMENT,
  memberid VARCHAR( 30 ) NOT NULL , 
  `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP , 
  firstname VARCHAR( 50 ) NULL , 
  lastname VARCHAR( 50 ) NULL , 
  PRIMARY KEY (memberid) ,
  KEY (id)                          --- or:    UNIQUE KEY (id)
) ENGINE = MYISAM; 

How to install psycopg2 with "pip" on Python?

If you using Mac OS, you should install PostgreSQL from source. After installation is finished, you need to add this path using:

export PATH=/local/pgsql/bin:$PATH

or you can append the path like this:

export PATH=.../:usr/local/pgsql/bin

in your .profile file or .zshrc file.

This maybe vary by operating system.

You can follow the installation process from http://www.thegeekstuff.com/2009/04/linux-postgresql-install-and-configure-from-source/

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

One solution for this can be found with find.

$ mkdir foo bar
$ touch foo/a.txt foo/Music.txt
$ find foo -type f ! -name '*Music*' -exec cp {} bar \;
$ ls bar
a.txt

Find has quite a few options, you can get pretty specific on what you include and exclude.

Edit: Adam in the comments noted that this is recursive. find options mindepth and maxdepth can be useful in controlling this.

Best Regular Expression for Email Validation in C#

I would like to suggest new EmailAddressAttribute().IsValid(emailTxt) for additional validation before/after validating using RegEx

Remember EmailAddressAttribute is part of System.ComponentModel.DataAnnotations namespace.

How to delete last character in a string in C#?

string str="This is test string.";
str=str.Remove(str.Length-1);

Faking an RS232 Serial Port

i used eltima make virtual serial port for my modbus application debug work. it is really very good application at development stage to check serial port program without connecting hardware.

Why do I keep getting 'SVN: Working Copy XXXX locked; try performing 'cleanup'?

This happened to me when I copied a directory from another subversion project and tried to commit. The soluction was to delete the .svn director inside the directory I wanted to commit.

Why doesn't wireshark detect my interface?

Just uninstall NPCAP and install wpcap. This will fix the issue.

Calling startActivity() from outside of an Activity?

You didn't paste the part where you call startActivity, that's the interesting part.

You might be calling startActivity in a Service context, or in an Application context.

Print "this" to log cat before making the startActivity call, and see what it refers to, it's sometimes a case of using an inner "this" accidentally.

Adding one day to a date

I always just add 86400 (seconds in a day):

$stop_date = date('Y-m-d H:i:s', strtotime("2009-09-30 20:24:00") + 86400);

echo 'date after adding 1 day: '.$stop_date; 

It's not the slickest way you could probably do it, but it works!

How do we check if a pointer is NULL pointer?

The actual representation of a null pointer is irrelevant here. An integer literal with value zero (including 0 and any valid definition of NULL) can be converted to any pointer type, giving a null pointer, whatever the actual representation. So p != NULL, p != 0 and p are all valid tests for a non-null pointer.

You might run into problems with non-zero representations of the null pointer if you wrote something twisted like p != reinterpret_cast<void*>(0), so don't do that.

Although I've just noticed that your question is tagged C as well as C++. My answer refers to C++, and other languages may be different. Which language are you using?

How can I create a Java method that accepts a variable number of arguments?

The variable arguments must be the last of the parameters specified in your function declaration. If you try to specify another parameter after the variable arguments, the compiler will complain since there is no way to determine how many of the parameters actually belong to the variable argument.

void print(final String format, final String... arguments) {
    System.out.format( format, arguments );
}

How to check if an alert exists using WebDriver?

public boolean isAlertPresent() 
{ 
    try 
    { 
        driver.switchTo().alert(); 
        return true; 
    }   // try 
    catch (NoAlertPresentException Ex) 
    { 
        return false; 
    }   // catch 
}   // isAlertPresent()

check the link here https://groups.google.com/forum/?fromgroups#!topic/webdriver/1GaSXFK76zY

Export query result to .csv file in SQL Server 2008

I know this is a bit old, but here is a much easier way...

  1. Run your query with default settings (puts results in grid format, if your's is not in grid format, see below)

  2. Right click on grid results and click "Save Results As" and save it.

If your results are not in grid format, right click where you write the query, hover "Results To" and click "Results To Grid"

Be aware you do NOT capture the column headers!

Good Luck!

How to convert a string of numbers to an array of numbers?

You can use JSON.parse, adding brakets to format Array

_x000D_
_x000D_
const a = "1,2,3,4";
const myArray = JSON.parse(`[${a}]`)
console.log(myArray)
console.info('pos 2 = ',  myArray[2])
_x000D_
_x000D_
_x000D_

Remove useless zero digits from decimals in PHP

Thats my small solution... Can included to a class and set vars

private $dsepparator = '.'; // decimals private $tsepparator= ','; // thousand

That can be set by constructor and change to users lang.

class foo
{
    private $dsepparator;
    private $tsepparator;

    function __construct(){
        $langDatas = ['en' => ['dsepparator' => '.', 'tsepparator' => ','], 'de' => ['dsepparator' => ',', 'tsepparator' => '.']];
        $usersLang = 'de'; // set iso code of lang from user
        $this->dsepparator = $langDatas[$usersLang]['dsepparator'];
        $this->tsepparator = $langDatas[$usersLang]['tsepparator'];
    }

    public function numberOmat($amount, $decimals = 2, $hideByZero = false)
    {
        return ( $hideByZero === true AND ($amount-floor($amount)) <= 0 ) ? number_format($amount, 0, $this->dsepparator, $this->tsepparator) : number_format($amount, $decimals, $this->dsepparator, $this->tsepparator);
    }
    /*
     * $bar = new foo();
     * $bar->numberOmat('5.1234', 2, true); // returns: 5,12
     * $bar->numberOmat('5', 2); // returns: 5,00
     * $bar->numberOmat('5.00', 2, true); // returns: 5
     */

}

How to check if smtp is working from commandline (Linux)

Not sure if this help or not but this is a command line tool which let you simply send test mails from a SMTP server priodically. http://code.google.com/p/woodpecker-tester/

How to display string that contains HTML in twig template?

{{ word|striptags('<b>,<a>,<pre>')|raw }}

if you want to allow multiple tags

Is there a decorator to simply cache function return values?

There is yet another example of a memoize decorator at Python Wiki:

http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize

That example is a bit smart, because it won't cache the results if the parameters are mutable. (check that code, it's very simple and interesting!)

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

All of these solutions are ugly because multiprocessing and pickling is broken and limited unless you jump outside the standard library.

If you use a fork of multiprocessing called pathos.multiprocesssing, you can directly use classes and class methods in multiprocessing's map functions. This is because dill is used instead of pickle or cPickle, and dill can serialize almost anything in python.

pathos.multiprocessing also provides an asynchronous map function… and it can map functions with multiple arguments (e.g. map(math.pow, [1,2,3], [4,5,6]))

See: What can multiprocessing and dill do together?

and: http://matthewrocklin.com/blog/work/2013/12/05/Parallelism-and-Serialization/

>>> import pathos.pools as pp
>>> p = pp.ProcessPool(4)
>>> 
>>> def add(x,y):
...   return x+y
... 
>>> x = [0,1,2,3]
>>> y = [4,5,6,7]
>>> 
>>> p.map(add, x, y)
[4, 6, 8, 10]
>>> 
>>> class Test(object):
...   def plus(self, x, y): 
...     return x+y
... 
>>> t = Test()
>>> 
>>> p.map(Test.plus, [t]*4, x, y)
[4, 6, 8, 10]
>>> 
>>> p.map(t.plus, x, y)
[4, 6, 8, 10]

And just to be explicit, you can do exactly want you wanted to do in the first place, and you can do it from the interpreter, if you wanted to.

>>> import pathos.pools as pp
>>> class someClass(object):
...   def __init__(self):
...     pass
...   def f(self, x):
...     return x*x
...   def go(self):
...     pool = pp.ProcessPool(4)
...     print pool.map(self.f, range(10))
... 
>>> sc = someClass()
>>> sc.go()
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> 

Get the code here: https://github.com/uqfoundation/pathos

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

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

@NgModule({
  imports: [
             BrowserModule,

             FormsModule      //<----------make sure you have added this.
           ],
  ....
})

How to deny access to a file in .htaccess

Place the below line in your .htaccess file and replace the file name as you wish

RewriteRule ^(test\.php) - [F,L,NC]

parsing a tab-separated file in Python

You can use the csv module to parse tab seperated value files easily.

import csv

with open("tab-separated-values") as tsv:
    for line in csv.reader(tsv, dialect="excel-tab"): #You can also use delimiter="\t" rather than giving a dialect.
        ... 

Where line is a list of the values on the current row for each iteration.

Edit: As suggested below, if you want to read by column, and not by row, then the best thing to do is use the zip() builtin:

with open("tab-separated-values") as tsv:
    for column in zip(*[line for line in csv.reader(tsv, dialect="excel-tab")]):
        ...

How to set the style -webkit-transform dynamically using JavaScript?

If you want to do it via setAttribute you would change the style attribute like so:

element.setAttribute('style','transform:rotate(90deg); -webkit-transform: rotate(90deg)') //etc

This would be helpful if you want to reset all other inline style and only set your needed style properties' values again, BUT in most cases you may not want that. That's why everybody advised to use this:

element.style.transform = 'rotate(90deg)';
element.style.webkitTransform = 'rotate(90deg)';

The above is equivalent to

element.style['transform'] = 'rotate(90deg)';
element.style['-webkit-transform'] = 'rotate(90deg)';

PostgreSQL wildcard LIKE for any of a list of words

One 'elegant' solution would be to use full text search: http://www.postgresql.org/docs/9.0/interactive/textsearch.html. Then you would use full text search queries.

Emulator: ERROR: x86 emulation currently requires hardware acceleration

Enable virtualization Technology

This is worked in my case

Restart Computer Continuously press Esc and then F10 to enter BIOS setup configuration Check Virtualization technology

My PC is HP Zbook 1. Boot the unit to BIOS (Reboot the unit and keep tapping on F10).

  1. Navigate to Advanced>Device or System Configuration> Click on the check box Virtualization Technology (VTx) and Virtualization Technology for Directed I/O (VTd)

  2. Save changes and Exit.

How to upload a file in Django?

Demo

See the github repo, works with Django 3

A minimal Django file upload example

1. Create a django project

Run startproject::

$ django-admin.py startproject sample

now a folder(sample) is created.

2. create an app

Create an app::

$ cd sample
$ python manage.py startapp uploader

Now a folder(uploader) with these files are created::

uploader/
  __init__.py
  admin.py
  app.py
  models.py
  tests.py
  views.py
  migrations/
    __init__.py

3. Update settings.py

On sample/settings.py add 'uploader' to INSTALLED_APPS and add MEDIA_ROOT and MEDIA_URL, ie::

INSTALLED_APPS = [
    'uploader',
    ...<other apps>...      
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

4. Update urls.py

in sample/urls.py add::

...<other imports>...
from django.conf import settings
from django.conf.urls.static import static
from uploader import views as uploader_views

urlpatterns = [
    ...<other url patterns>...
    path('', uploader_views.UploadView.as_view(), name='fileupload'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

5. Update models.py

update uploader/models.py::

from django.db import models
class Upload(models.Model):
    upload_file = models.FileField()    
    upload_date = models.DateTimeField(auto_now_add =True)

6. Update views.py

update uploader/views.py::

from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from .models import Upload
class UploadView(CreateView):
    model = Upload
    fields = ['upload_file', ]
    success_url = reverse_lazy('fileupload')
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['documents'] = Upload.objects.all()
        return context

7. create templates

Create a folder sample/uploader/templates/uploader

Create a file upload_form.html ie sample/uploader/templates/uploader/upload_form.html::

<div style="padding:40px;margin:40px;border:1px solid #ccc">
    <h1>Django File Upload</h1>
    <form method="post" enctype="multipart/form-data">
      {% csrf_token %}
      {{ form.as_p }}
      <button type="submit">Submit</button>
    </form><hr>
    <ul>
    {% for document in documents %}
        <li>
            <a href="{{ document.upload_file.url }}">{{ document.upload_file.name }}</a>
            <small>({{ document.upload_file.size|filesizeformat }}) - {{document.upload_date}}</small>
        </li>
    {% endfor %}
    </ul>
</div>

8. Syncronize database

Syncronize database and runserver::

$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py runserver

visit http://localhost:8000/

Convert all data frame character columns to factors

DF <- data.frame(x=letters[1:5], y=1:5, stringsAsFactors=FALSE)

str(DF)
#'data.frame':  5 obs. of  2 variables:
# $ x: chr  "a" "b" "c" "d" ...
# $ y: int  1 2 3 4 5

The (annoying) default of as.data.frame is to turn all character columns into factor columns. You can use that here:

DF <- as.data.frame(unclass(DF))
str(DF)
#'data.frame':  5 obs. of  2 variables:
# $ x: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
# $ y: int  1 2 3 4 5

How to get row count in an Excel file using POI library?

If you do a check

if
(getLastRowNum()<1){
 res="Sheet Cannot be empty";
return
}

This will make sure you have at least one row with data except header. Below is my program which works fine. Excel file has three columns ie. ID, NAME , LASTNAME

XSSFWorkbook workbook = new XSSFWorkbook(inputstream);
        XSSFSheet sheet = workbook.getSheetAt(0);
        Row header = sheet.getRow(0);
        int n = header.getLastCellNum();
        String header1 = header.getCell(0).getStringCellValue();
        String header2 = header.getCell(1).getStringCellValue();
        String header3 = header.getCell(2).getStringCellValue();
        if (header1.equals("ID") && header2.equals("NAME")
                && header3.equals("LASTNAME")) {
            if(sheet.getLastRowNum()<1){
                System.out.println("Sheet empty");
                         return;
            }   
                        iterate over sheet to get cell values
        }else{
                          SOP("invalid format");
                          return;
                          }

Could not load file or assembly 'System.Web.Mvc'

I ran into the same issue as sgriffinusa. In addition to the references Phil's article suggests: http://www.haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx . I added these:

* Microsoft.Web.Infrastructure
* System.Web.Razor
* System.Web.WebPages.Deployment
* System.Web.WebPages.Razor

Godaddy Deployment worked perfectly. Turn custom errors off and add references to correct the errors. That should lead you in the right direction.

mysql -> insert into tbl (select from another table) and some default values

If you you want to copy a sub-set of the source table you can do:

INSERT INTO def (field_1, field_2, field3)

SELECT other_field_1, other_field_2, other_field_3 from `abc`

or to copy ALL fields from the source table to destination table you can do more simply:

INSERT INTO def 
SELECT * from `abc`

PHP session lost after redirect

Now that GDPR is a thing, people visiting this question probably use a cookie script. Well, that script caused the problem for me. Apparently, PHP uses a cookie called PHPSESSID to track the session. If that script deletes it, you lose your data.

I used this cookie script. It has an option to enable "essential" cookies. I added PHPSESSID to the list, the script stopped deleting the cookie, and everything started to work again.

You could probably enable some PHP setting to avoid using PHPSESSID, but if your cookie script is the cause of the problem, why not fix that.

Export/import jobs in Jenkins

There's a plugin called Job Import Plugin that may be what you are looking for. I have used it. It does have issues with importing projects from a server that doesn't allow anonymous access.

For Completeness: If you have command line access to both, you can do the procedure already mentioned by Khez for Moving, Copying and Renaming Jenkins Jobs.

How to get .pem file from .key and .crt files?

Trying to upload a GoDaddy certificate to AWS I failed several times, but in the end it was pretty simple. No need to convert anything to .pem. You just have to be sure to include the GoDaddy bundle certificate in the chain parameter, e.g.

aws iam upload-server-certificate
    --server-certificate-name mycert
    --certificate-body file://try2/40271b1b25236fd1.crt
    --private-key file://server.key
    --path /cloudfront/production/
    --certificate-chain file://try2/gdig2_bundle.crt

And to delete your previous failed upload you can do

aws iam delete-server-certificate --server-certificate-name mypreviouscert

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

I had this issue and the cause was actually a NullPointerException. But it was not presented to me as one!

my Output: screen was stuck for a very long period and ANR

My State : the layout xml file was included another layout, but referenced the included view without giving id in the attached layout. (i had two more similar implementations of the same child view, so the resource id was created with the given name)

Note : it was a Custom Dialog layout, so checking dialogs first may help a bit

Conclusion : There is some memory leak happened on searching the id of the child view.

Javascript require() function giving ReferenceError: require is not defined

By default require() is not a valid function in client side javascript. I recommend you look into require.js as this does extend the client side to provide you with that function.

Android change SDK version in Eclipse? Unable to resolve target android-x

In Build: v22.6.2-1085508 ADT you need to add(select Android 4.4.2)

Goto project --> properties --> Android(This is second in listed item order leftPanel) and in the RightPanel Project Build Target, select Android 4.4.2 as Target name and apply changes It will rebuild the workspace.

In my case unable to resolve target 'android-17' eclipse was being shown as compile error and in code: import java.util.HashMap was not being referenced.

How to set Spinner default value to null?

is it possible have a spinner that loads with nothing selected

Only if there is no data. If you have 1+ items in the SpinnerAdapter, the Spinner will always have a selection.

Spinners are not designed to be command widgets. Users will not expect a selection in a Spinner to start an activity. Please consider using something else, like a ListView or GridView, instead of a Spinner.


EDIT

BTW, I forgot to mention -- you can always put an extra entry in your adapter that represents "no selection", and make it the initial selected item in the Spinner.

How do I push a new local branch to a remote Git repository and track it too?

You can do it in 2 steeps:

1. Use the checkout for create the local branch:

git checkout -b yourBranchName

Work with your Branch as you want.

2. Use the push command to autocreate the branch and send the code to the remote repository:

git push -u origin yourBanchName

There are mutiple ways to do this but I think that this way is really simple.

Redirect stderr and stdout in Bash

# Close STDOUT file descriptor
exec 1<&-
# Close STDERR FD
exec 2<&-

# Open STDOUT as $LOG_FILE file for read and write.
exec 1<>$LOG_FILE

# Redirect STDERR to STDOUT
exec 2>&1

echo "This line will appear in $LOG_FILE, not 'on screen'"

Now, simple echo will write to $LOG_FILE. Useful for daemonizing.

To the author of the original post,

It depends what you need to achieve. If you just need to redirect in/out of a command you call from your script, the answers are already given. Mine is about redirecting within current script which affects all commands/built-ins(includes forks) after the mentioned code snippet.


Another cool solution is about redirecting to both std-err/out AND to logger or log file at once which involves splitting "a stream" into two. This functionality is provided by 'tee' command which can write/append to several file descriptors(files, sockets, pipes, etc) at once: tee FILE1 FILE2 ... >(cmd1) >(cmd2) ...

exec 3>&1 4>&2 1> >(tee >(logger -i -t 'my_script_tag') >&3) 2> >(tee >(logger -i -t 'my_script_tag') >&4)
trap 'cleanup' INT QUIT TERM EXIT


get_pids_of_ppid() {
    local ppid="$1"

    RETVAL=''
    local pids=`ps x -o pid,ppid | awk "\\$2 == \\"$ppid\\" { print \\$1 }"`
    RETVAL="$pids"
}


# Needed to kill processes running in background
cleanup() {
    local current_pid element
    local pids=( "$$" )

    running_pids=("${pids[@]}")

    while :; do
        current_pid="${running_pids[0]}"
        [ -z "$current_pid" ] && break

        running_pids=("${running_pids[@]:1}")
        get_pids_of_ppid $current_pid
        local new_pids="$RETVAL"
        [ -z "$new_pids" ] && continue

        for element in $new_pids; do
            running_pids+=("$element")
            pids=("$element" "${pids[@]}")
        done
    done

    kill ${pids[@]} 2>/dev/null
}

So, from the beginning. Let's assume we have terminal connected to /dev/stdout(FD #1) and /dev/stderr(FD #2). In practice, it could be a pipe, socket or whatever.

  • Create FDs #3 and #4 and point to the same "location" as #1 and #2 respectively. Changing FD #1 doesn't affect FD #3 from now on. Now, FDs #3 and #4 point to STDOUT and STDERR respectively. These will be used as real terminal STDOUT and STDERR.
  • 1> >(...) redirects STDOUT to command in parens
  • parens(sub-shell) executes 'tee' reading from exec's STDOUT(pipe) and redirects to 'logger' command via another pipe to sub-shell in parens. At the same time it copies the same input to FD #3(terminal)
  • the second part, very similar, is about doing the same trick for STDERR and FDs #2 and #4.

The result of running a script having the above line and additionally this one:

echo "Will end up in STDOUT(terminal) and /var/log/messages"

...is as follows:

$ ./my_script
Will end up in STDOUT(terminal) and /var/log/messages

$ tail -n1 /var/log/messages
Sep 23 15:54:03 wks056 my_script_tag[11644]: Will end up in STDOUT(terminal) and /var/log/messages

If you want to see clearer picture, add these 2 lines to the script:

ls -l /proc/self/fd/
ps xf

ASP.NET Bundles how to disable minification

If you have debug="true" in web.config and are using Scripts/Styles.Render to reference the bundles in your pages, that should turn off both bundling and minification. BundleTable.EnableOptimizations = false will always turn off both bundling and minification as well (irrespective of the debug true/false flag).

Are you perhaps not using the Scripts/Styles.Render helpers? If you are directly rendering references to the bundle via BundleTable.Bundles.ResolveBundleUrl() you will always get the minified/bundled content.

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

That problem happens when you try to access from a different domain or different port.

If you're using Visual Studio, then go to Tools > NuGet Package Manager > Package Manager Console. There you have to install the NuGet Package Microsoft.AspNet.WebApi.Cors

Install-Package Microsoft.AspNet.WebApi.Cors

Then, in PROJECT > App_Start > WebApiConfig, enable CORS

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        
        //Enable CORS. Note that the domain doesn't have / in the end.
        config.EnableCors(new EnableCorsAttribute("https://tiagoperes.eu",headers:"*",methods:"*"));

        ....

    }
}

Once installed successfully, build the solution and that should suffice

How to access host port from docker container

For me (Windows 10, Docker Engine v19.03.8) it was a mix of https://stackoverflow.com/a/43541732/7924573 and https://stackoverflow.com/a/50866007/7924573 .

  1. change the host/ip to host.docker.internal
    e.g.: LOGGER_URL = "http://host.docker.internal:8085/log"
  2. set the network_mode to bridge (if you want to maintain the port forwarding; if not use host):
    version: '3.7' services: server: build: . ports: - "5000:5000" network_mode: bridge or alternatively: Use --net="bridge" if you are not using docker-compose (similar to https://stackoverflow.com/a/48806927/7924573)
    As pointed out in previous answers: This should only be used in a local development environment.
    For more information read: https://docs.docker.com/compose/compose-file/#network_mode and https://docs.docker.com/docker-for-windows/networking/#use-cases-and-workarounds

Controlling a USB power supply (on/off) with Linux

I have found these solutions that at least work for properly configured Terminus FE 1.1 USB hub chip:

1.To turn off power on all USB ports of a hub, you may unbind the hub from kernel using:

echo "1-4.4.4" > /sys/bus/usb/drivers/usb/unbind

to turn power back on - you may bind it back using

echo "1-4.4.4" > /sys/bus/usb/drivers/usb/bind

2.Switching power at each port individually is trickier: I was able to use hubpower to control each port - but it comes with a downside: hubpower first disconnects the usbdevfs wich causes all of the USB devices to disconect from system, at least on ubuntu:

usb_ioctl.ioctl_code = USBDEVFS_DISCONNECT;
rc = ioctl(fd, USBDEVFS_IOCTL, &usb_ioctl);

With this ioctl disabled I was able to switch off individual port power without detaching all devices - but the power goes back on immediately (probably due to kernel seeing an uninitialized device) which causes USB device just to do a "cold restart" which is what I generally wanted to do. My patched hubpower is here

Bootstrap modal: is not a function

This warning may also be shown if jQuery is declared more than once in your code. The second jQuery declaration prevents bootstrap.js from working correctly.

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
...
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

How do I set environment variables from Java?

Poking around online, it looks like it might be possible to do this with JNI. You'd then have to make a call to putenv() from C, and you'd (presumably) have to do it in a way that worked on both Windows and UNIX.

If all that can be done, it surely wouldn't be too hard for Java itself to support this instead of putting me in a straight jacket.

A Perl-speaking friend elsewhere suggests that this is because environment variables are process global and Java is striving for good isolation for good design.

How to edit CSS style of a div using C# in .NET

Add the runat="server" attribute to it so you have:

<div id="formSpinner" runat="server">
    <img src="images/spinner.gif">
    <p>Saving...</p>
</div>

That way you can access the class attribute by using:

formSpinner.Attributes["class"] = "classOfYourChoice";

It's also worth mentioning that the asp:Panel control is virtually synonymous (at least as far as rendered markup is concerned) with div, so you could also do:

<asp:Panel id="formSpinner" runat="server">
    <img src="images/spinner.gif">
    <p>Saving...</p>
</asp:Panel>

Which then enables you to write:

formSpinner.CssClass = "classOfYourChoice";

This gives you more defined access to the property and there are others that may, or may not, be of use to you.

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

Count the number of commits on a Git branch

To count the commits for the branch you are on:

git rev-list --count HEAD

for a branch

git rev-list --count <branch-name>

If you want to count the commits on a branch that are made since you created the branch

git rev-list --count HEAD ^<branch-name>

This will count all commits ever made that are not on the branch-name as well.

Examples

git checkout master
git checkout -b test
<We do 3 commits>
git rev-list --count HEAD ^master

Result: 3

If your branch comes of a branch called develop:

git checkout develop
git checkout -b test
<We do 3 commits>
git rev-list --count HEAD ^develop

Result: 3

Ignoring Merges

If you merge another branch into the current branch without fast forward and you do the above, the merge is also counted. This is because for git a merge is a commit.

If you don't want to count these commits add --no-merges:

git rev-list --no-merges --count HEAD ^develop

ASP.NET Identity reset password

In case of password reset, it is recommended to reset it through sending password reset token to registered user email and ask user to provide new password. If have created a easily usable .NET library over Identity framework with default configuration settins. You can find details at blog link and source code at github.

SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?

Cross join :Cross Joins produce results that consist of every combination of rows from two or more tables. That means if table A has 3 rows and table B has 2 rows, a CROSS JOIN will result in 6 rows. There is no relationship established between the two tables – you literally just produce every possible combination.

Full outer Join : A FULL OUTER JOIN is neither "left" nor "right"— it's both! It includes all the rows from both of the tables or result sets participating in the JOIN. When no matching rows exist for rows on the "left" side of the JOIN, you see Null values from the result set on the "right." Conversely, when no matching rows exist for rows on the "right" side of the JOIN, you see Null values from the result set on the "left."

How to show code but hide output in RMarkdown?

For what it's worth.

```{r eval=FALSE}

The document will display the code by default but will prevent the code block from being executed, and thus will also not display any results.

How to expand 'select' option width after the user wants to select an option

If you have the option pre-existing in a fixed-with <select>, and you don't want to change the width programmatically, you could be out of luck unless you get a little creative.

  • You could try and set the title attribute to each option. This is non-standard HTML (if you care for this minor infraction here), but IE (and Firefox as well) will display the entire text in a mouse popup on mouse hover.
  • You could use JavaScript to show the text in some positioned DIV when the user selects something. IMHO this is the not-so-nice way to do it, because it requires JavaScript on to work at all, and it works only after something has been selected - before there is a change in value no events fire for the select box.
  • You don't use a select box at all, but implement its functionality using other markup and CSS. Not my favorite but I wanted to mention it.

If you are adding a long option later through JavaScript, look here: How to update HTML “select” box dynamically in IE

How to change JAVA.HOME for Eclipse/ANT

If you are using Eclipse, try the following:

  • Right click on the ant build file, then choose "Properties".
  • Click on the "Run/Debug Settings", then click on the launch configuration file. You should be able to edit it then.
  • After you click "Edit", you should see a new window with a "Properties" tab which will show you a list of Ant build properties. There is a "java.home" property in the list. Make sure it refers to the correct path.

creating charts with angularjs

The ZingChart library has an AngularJS directive that was built in-house. Features include:

  • Full access to the entire ZingChart library (all charts, maps, and features)
  • Takes advantage of Angular's 2-way data binding, making data and chart elements easy to update
  • Support from the development team

    ...
    $scope.myJson = {
    type : 'line',
       series : [
          { values : [54,23,34,23,43] },{ values : [10,15,16,20,40] }
       ]
    };
    ...
    
    <zingchart id="myChart" zc-json="myJson" zc-height=500 zc-width=600></zingchart>
    

There is a full demo with code examples available.

How to loop and render elements in React-native?

render() {
  return (
    <View style={...}>
       {initialArr.map((prop, key) => {
         return (
           <Button style={{borderColor: prop[0]}}  key={key}>{prop[1]}</Button>
         );
      })}
     </View>
  )
}

should do the trick

What is the canonical way to trim a string in Ruby without creating a new string?

If you want to use another method after you need something like this:

( str.strip || str ).split(',')

This way you can strip and still do something after :)

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

This is how you should be using mysql_fetch_assoc():

$result = mysql_query($query);

while ($row = mysql_fetch_assoc($result)) {
    // Do stuff with $row
}

$result should be a resource. Even if the query returns no rows, $result is still a resource. The only time $result is a boolean value, is if there was an error when querying the database. In which case, you should find out what that error is by using mysql_error() and ensure that it can't happen. Then you don't have to hide from any errors.

You should always cover the base that errors may happen by doing:

if (!$result) {
    die(mysql_error());
}

At least then you'll be more likely to actually fix the error, rather than leave the users with a glaring ugly error in their face.

python plot normal distribution

Unutbu answer is correct. But because our mean can be more or less than zero I would still like to change this :

x = np.linspace(-3 * sigma, 3 * sigma, 100)

to this :

x = np.linspace(-3 * sigma + mean, 3 * sigma + mean, 100)

How do I style appcompat-v7 Toolbar like Theme.AppCompat.Light.DarkActionBar?

To customize tool bar style, first create tool bar custom style inheriting Widget.AppCompat.Toolbar, override properties and then add it to custom app theme as shown below, see http://www.zoftino.com/android-toolbar-tutorial for more information tool bar and styles.

   <style name="MyAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="toolbarStyle">@style/MyToolBarStyle</item>
    </style>
    <style name="MyToolBarStyle" parent="Widget.AppCompat.Toolbar">
        <item name="android:background">#80deea</item>
        <item name="titleTextAppearance">@style/MyTitleTextAppearance</item>
        <item name="subtitleTextAppearance">@style/MySubTitleTextAppearance</item>
    </style>
    <style name="MyTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
        <item name="android:textSize">35dp</item>
        <item name="android:textColor">#ff3d00</item>
    </style>
    <style name="MySubTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Subtitle">
        <item name="android:textSize">30dp</item>
        <item name="android:textColor">#1976d2</item>
    </style>

Java Replace Character At Specific Position Of String?

Petar Ivanov's answer to replace a character at a specific index in a string question

String are immutable in Java. You can't change them.

You need to create a new string with the character replaced.

String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);

Or you can use a StringBuilder:

StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);

How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)

I was doing an install of an apk:

adb install /home/me/jones_android-arm.apk

And I was getting an error message telling me that

/data/local/tmp/jones_android-arm.apk

was too big. Using the sdk tools from r15, and ADT 15 I was able to use the AVD manager to manipulate some of my existing emulator's settings:

Window-> AVD Manager -> (select you virtual machine) -> Edit

then going to the Hardware properties window just below "Skin:" I was able to select with the Hardware: New button 'Ideal size of partition'. I was not, however, able to set the value other than to '0'. Undaunted, I went to my ${HOME}/.android/avd directory There was a 'MyVm.avd' directory. Going into that directory I found a 'config.ini' file. There was the entry :

disk.dataPartition.size=0

I set this to:

disk.dataPartition.size=1024

.. then went back to the AVD Manager, selected MyVm, selected 'Start', opted to wipe user data win the dialog following, and was able to run and install.

How to save a Seaborn plot into a file

The suggested solutions are incompatible with Seaborn 0.8.1

giving the following errors because the Seaborn interface has changed:

AttributeError: 'AxesSubplot' object has no attribute 'fig'
When trying to access the figure

AttributeError: 'AxesSubplot' object has no attribute 'savefig'
when trying to use the savefig directly as a function

The following calls allow you to access the figure (Seaborn 0.8.1 compatible):

swarm_plot = sns.swarmplot(...)
fig = swarm_plot.get_figure()
fig.savefig(...) 

as seen previously in this answer.

UPDATE: I have recently used PairGrid object from seaborn to generate a plot similar to the one in this example. In this case, since GridPlot is not a plot object like, for example, sns.swarmplot, it has no get_figure() function. It is possible to directly access the matplotlib figure by

fig = myGridPlotObject.fig

Like previously suggested in other posts in this thread.

Convert an integer to a byte array

Sorry, this might be a bit late. But I think I found a better implementation on the go docs.

buf := new(bytes.Buffer)
var num uint16 = 1234
err := binary.Write(buf, binary.LittleEndian, num)
if err != nil {
    fmt.Println("binary.Write failed:", err)
}
fmt.Printf("% x", buf.Bytes())

MyISAM versus InnoDB

I think this is an excellent article on explaining the differences and when you should use one over the other: http://tag1consulting.com/MySQL_Engines_MyISAM_vs_InnoDB

Find if a textbox is disabled or not using jquery

.prop('disabled') will return a Boolean:

var isDisabled = $('textbox').prop('disabled');

Here's the fiddle: http://jsfiddle.net/unhjM/

C# generic list <T> how to get the type of T?

Marc's answer is the approach I use for this, but for simplicity (and a friendlier API?) you can define a property in the collection base class if you have one such as:

public abstract class CollectionBase<T> : IList<T>
{
   ...

   public Type ElementType
   {
      get
      {
         return typeof(T);
      }
   }
}

I have found this approach useful, and is easy to understand for any newcomers to generics.

CodeIgniter: How To Do a Select (Distinct Fieldname) MySQL Query

$record = '123';

$this->db->distinct();

$this->db->select('accessid');

$this->db->where('record', $record); 

$query = $this->db->get('accesslog');

then

$query->num_rows();

should go a long way towards it.

How can I avoid getting this MySQL error Incorrect column specifier for column COLUMN NAME?

Quoting the doc:

Some attributes do not apply to all data types. AUTO_INCREMENT applies only to integer and floating-point types. DEFAULT does not apply to the BLOB or TEXT types.

In your case, you're trying to apply AUTO_INCREMENT modifier to char column. To solve this, either drop AUTO_INCREMENT altogether (that means you'll have to generate a unique id on the application level) or just change topic_id type to the relevant integer one.

As a sidenote, it makes little sense using char(36) to store the posts count, so that column's type probably has to be changed as well. It looks like you're going this way to prevent integer overflow - but if you're dealing with more than 18446744073709551615 posts (the biggest number that can be stored in BIGINT UNSIGNED column) in a single topic, you have far bigger problem on your side probably. )

"id cannot be resolved or is not a field" error?

Just Clean your project so R will be generated automatically. This worked for me.

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

How to set a Javascript object values dynamically?

When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.

You can access these dictionaries in two ways:

  • Like an array (e.g. myObj[name]); or
  • Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.

You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.

myObj["name"]

Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.

Replace line break characters with <br /> in ASP.NET MVC Razor view

I prefer this method as it doesn't require manually emitting markup. I use this because I'm rendering Razor Pages to strings and sending them out via email, which is an environment where the white-space styling won't always work.

public static IHtmlContent RenderNewlines<TModel>(this IHtmlHelper<TModel> html, string content)
{
    if (string.IsNullOrEmpty(content) || html is null)
    {
        return null;
    }

    TagBuilder brTag = new TagBuilder("br");
    IHtmlContent br = brTag.RenderSelfClosingTag();
    HtmlContentBuilder htmlContent = new HtmlContentBuilder();

    // JAS: On the off chance a browser is using LF instead of CRLF we strip out CR before splitting on LF.
    string lfContent = content.Replace("\r", string.Empty, StringComparison.InvariantCulture);
    string[] lines = lfContent.Split('\n', StringSplitOptions.None);
    foreach(string line in lines)
    {
        _ = htmlContent.Append(line);
        _ = htmlContent.AppendHtml(br);
    }

    return htmlContent;
}

Difference between "while" loop and "do while" loop

Probably wdlen starts with a value >=2, so in the second case the loop condition is initially false and the loop is never entered.

In the second case the loop body is executed before the wdlen<2 condition is checked for the first time, so the printf/scanf is executed at least once.

How change default SVN username and password to commit changes?

In TortiseSVN settings

right-click menu >> settings >> Saved data >> Authentication data [Clear]

The side effect is that it clears out all authentication data and you have to re-enter your own username/password.

How can I change the color of a Google Maps marker?

To customize markers, you can do it from this online tool: https://materialdesignicons.com/

In your case, you want the map-marker which is available here: https://materialdesignicons.com/icon/map-marker and which you can customize online.

If you simply want to change the default Red color to Blue, you can load this icon: http://maps.google.com/mapfiles/ms/icons/blue-dot.png

It's been mentioned in this thread: https://stackoverflow.com/a/32651327/6381715

HTTP Range header

As Wrikken suggested, it's a valid request. It's also quite common when the client is requesting media or resuming a download.

A client will often test to see if the server handles ranged requests other than just looking for an Accept-Ranges response. Chrome always sends a Range: bytes=0- with its first GET request for a video, so it's something you can't dismiss.

Whenever a client includes Range: in its request, even if it's malformed, it's expecting a partial content (206) response. When you seek forward during HTML5 video playback, the browser only requests the starting point. For example:

Range: bytes=3744-

So, in order for the client to play video properly, your server must be able to handle these incomplete range requests.

You can handle the type of 'range' you specified in your question in two ways:

First, You could reply with the requested starting point given in the response, then the total length of the file minus one (the requested byte range is zero-indexed). For example:

Request:

GET /BigBuckBunny_320x180.mp4 
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/64656927

Second, you could reply with the starting point given in the request and an open-ended file length (size). This is for webcasts or other media where the total length is unknown. For example:

Request:

GET /BigBuckBunny_320x180.mp4
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/*

Tips:

You must always respond with the content length included with the range. If the range is complete, with start to end, then the content length is simply the difference:

Request: Range: bytes=500-1000

Response: Content-Range: bytes 500-1000/123456

Remember that the range is zero-indexed, so Range: bytes=0-999 is actually requesting 1000 bytes, not 999, so respond with something like:

Content-Length: 1000
Content-Range: bytes 0-999/123456

Or:

Content-Length: 1000
Content-Range: bytes 0-999/*

But, avoid the latter method if possible because some media players try to figure out the duration from the file size. If your request is for media content, which is my hunch, then you should include its duration in the response. This is done with the following format:

X-Content-Duration: 63.23 

This must be a floating point. Unlike Content-Length, this value doesn't have to be accurate. It's used to help the player seek around the video. If you are streaming a webcast and only have a general idea of how long it will be, it's better to include your estimated duration rather than ignore it altogether. So, for a two-hour webcast, you could include something like:

X-Content-Duration: 7200.00 

With some media types, such as webm, you must also include the content-type, such as:

Content-Type: video/webm 

All of these are necessary for the media to play properly, especially in HTML5. If you don't give a duration, the player may try to figure out the duration (to allow for seeking) from its file size, but this won't be accurate. This is fine, and necessary for webcasts or live streaming, but not ideal for playback of video files. You can extract the duration using software like FFMPEG and save it in a database or even the filename.

X-Content-Duration is being phased out in favor of Content-Duration, so I'd include that too. A basic, response to a "0-" request would include at least the following:

HTTP/1.1 206 Partial Content
Date: Sun, 08 May 2013 06:37:54 GMT
Server: Apache/2.0.52 (Red Hat)
Accept-Ranges: bytes
Content-Length: 3980
Content-Range: bytes 0-3979/3980
Content-Type: video/webm
X-Content-Duration: 2054.53
Content-Duration: 2054.53

One more point: Chrome always starts its first video request with the following:

Range: bytes=0-

Some servers will send a regular 200 response as a reply, which it accepts (but with limited playback options), but try to send a 206 instead to show than your server handles ranges. RFC 2616 says it's acceptable to ignore range headers.

Can I have a video with transparent background using HTML5 video tag?

Yes, this sort of thing is possible without Flash:

However, only very modern browsers supports HTML5 videos, and this should be your consideration when deploying in HTML 5, and you should provide a fallback (probably Flash or just omit the transparency).

How do I get the function name inside a function in PHP?

<?php

  class Test {
     function MethodA(){
         echo __FUNCTION__ ;
     }
 }
 $test = new Test;
 echo $test->MethodA();
?>

Result: "MethodA";

How to close current tab in a browser window?

Try this as well. Working for me on all three major browsers.

<!-- saved from url=(0014)about:internet -->
<a href="#" onclick="javascript:window.close();opener.window.focus();" >Close Window</a>

MySQL - DATE_ADD month interval

Well, for me this is the expected result; adding six months to Jan. 1st July.

mysql> SELECT DATE_ADD( '2011-01-01', INTERVAL 6 month );
+--------------------------------------------+
| DATE_ADD( '2011-01-01', INTERVAL 6 month ) |
+--------------------------------------------+
| 2011-07-01                                 | 
+--------------------------------------------+

What is the best way to implement nested dictionaries?

defaultdict() is your friend!

For a two dimensional dictionary you can do:

d = defaultdict(defaultdict)
d[1][2] = 3

For more dimensions you can:

d = defaultdict(lambda :defaultdict(defaultdict))
d[1][2][3] = 4

Text in a flex container doesn't wrap in IE11

.grandparent{
   display: table;
}

.parent{
  display: table-cell
  vertical-align: middle
}

This worked for me.

Node.js setting up environment specific configs to be used with everyauth

set environment variable in deployment server(ex: like NODE_ENV=production). You can access your environmental variable through process.env.NODE_ENV. Find the following config file for the global settings

const env = process.env.NODE_ENV || "development"

const configs = {
    base: {
        env,
        host: '0.0.0.0',
        port: 3000,
        dbPort: 3306,
        secret: "secretKey for sessions",
        dialect: 'mysql',
        issuer : 'Mysoft corp',
        subject : '[email protected]',
    },
    development: {
        port: 3000,
        dbUser: 'root',
        dbPassword: 'root',

    },
    smoke: {
        port: 3000,
        dbUser: 'root',
    },
    integration: {
        port: 3000,
        dbUser: 'root',
    },
    production: {
        port: 3000,
        dbUser: 'root',
    }
};

const config = Object.assign(configs.base, configs[env]);

module.exports= config;

base contains common config for all environments.

then import in other modules like

const config =  require('path/to/config.js')
console.log(config.port)

Happy Coding...