Programs & Examples On #Diophantine

Suppress Scientific Notation in Numpy When Creating Array From Nested List

I guess what you need is np.set_printoptions(suppress=True), for details see here: http://pythonquirks.blogspot.fr/2009/10/controlling-printing-in-numpy.html

For SciPy.org numpy documentation, which includes all function parameters (suppress isn't detailed in the above link), see here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html

Explain ggplot2 warning: "Removed k rows containing missing values"

The behavior you're seeing is due to how ggplot2 deals with data that are outside the axis ranges of the plot. You can change this behavior depending on whether you use scale_y_continuous (or, equivalently, ylim) or coord_cartesian to set axis ranges, as explained below.

library(ggplot2)

# All points are visible in the plot
ggplot(mtcars, aes(mpg, hp)) + 
  geom_point()

In the code below, one point with hp = 335 is outside the y-range of the plot. Also, because we used scale_y_continuous to set the y-axis range, this point is not included in any other statistics or summary measures calculated by ggplot, such as the linear regression line.

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() +
  scale_y_continuous(limits=c(0,300)) +  # Change this to limits=c(0,335) and the warning disappars
  geom_smooth(method="lm")

Warning messages:
1: Removed 1 rows containing missing values (stat_smooth). 
2: Removed 1 rows containing missing values (geom_point).

In the code below, the point with hp = 335 is still outside the y-range of the plot, but this point is nevertheless included in any statistics or summary measures that ggplot calculates, such as the linear regression line. This is because we used coord_cartesian to set the y-axis range, and this function does not exclude points that are outside the plot ranges when it does other calculations on the data.

If you compare this and the previous plot, you can see that the linear regression line in the second plot has a slightly steeper slope, because the point with hp=335 is included when calculating the regression line, even though it's not visible in the plot.

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() +
  coord_cartesian(ylim=c(0,300)) +
  geom_smooth(method="lm")

Jenkins returned status code 128 with github

Also make sure you using the ssh github url and not the https

Checking Date format from a string in C#

https://msdn.microsoft.com/es-es/library/h9b85w22(v=vs.110).aspx

string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                     "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                     "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                     "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                     "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
  string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", 
                          "5/1/2009 6:32:00", "05/01/2009 06:32", 
                          "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"}; 
  DateTime dateValue;

  foreach (string dateString in dateStrings)
  {
     if (DateTime.TryParseExact(dateString, formats, 
                                new CultureInfo("en-US"), 
                                DateTimeStyles.None, 
                                out dateValue))
        Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
     else
        Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
  }

How to use UIPanGestureRecognizer to move object? iPhone/iPad

UIPanGestureRecognizer * pan1 = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(moveObject:)];
pan1.minimumNumberOfTouches = 1;
[image1 addGestureRecognizer:pan1];

-(void)moveObject:(UIPanGestureRecognizer *)pan;
{
 image1.center = [pan locationInView:image1.superview];
}

How to filter input type="file" dialog by specific file type?

<asp:FileUpload ID="FileUploadExcel" ClientIDMode="Static" runat="server" />
<asp:Button ID="btnUpload" ClientIDMode="Static" runat="server" Text="Upload Excel File" />

.

$('#btnUpload').click(function () {
    var uploadpath = $('#FileUploadExcel').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);

    if ($('#FileUploadExcel').val().length == 0) {
        // write error message
        return false;
    }

    if (fileExtension == "xls" || fileExtension == "xlsx") {
        //write code for success
    }
    else {
        //error code - select only excel files
        return false;
    }

});

flutter remove back button on appbar

  appBar: new AppBar(title: new Text("SmartDocs SPAY"),backgroundColor: Colors.blueAccent, automaticallyImplyLeading:false,
        leading: new Container(),
      ),

It is working Fine

Decimal separator comma (',') with numberDecimal inputType in EditText

I decided to change comma to dot only while editing. Here is my tricky and relative simple workaround:

    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            EditText editText = (EditText) v; 
            String text = editText.getText().toString();
            if (hasFocus) {
                editText.setText(text.replace(",", "."));
            } else {
                if (!text.isEmpty()) {
                    Double doubleValue = Double.valueOf(text.replace(",", "."));
                    editText.setText(someDecimalFormatter.format(doubleValue));
                }
            }
        }
    });

someDecimalFormatter will use comma or dot depends on Locale

The import org.junit cannot be resolved

In case you want to create your own Test Class. In Eclipse go to File -> New -> J Unit Test Case. You can then choose all your paths and testing class setup within the wizard pop-up.

How do I return multiple values from a function?

For small projects I find it easiest to work with tuples. When that gets too hard to manage (and not before) I start grouping things into logical structures, however I think your suggested use of dictionaries and ReturnValue objects is wrong (or too simplistic).

Returning a dictionary with keys "y0", "y1", "y2", etc. doesn't offer any advantage over tuples. Returning a ReturnValue instance with properties .y0, .y1, .y2, etc. doesn't offer any advantage over tuples either. You need to start naming things if you want to get anywhere, and you can do that using tuples anyway:

def get_image_data(filename):
    [snip]
    return size, (format, version, compression), (width,height)

size, type, dimensions = get_image_data(x)

IMHO, the only good technique beyond tuples is to return real objects with proper methods and properties, like you get from re.match() or open(file).

Android getting value from selected radiobutton

just use getCheckedRadioButtonId() function to determine wether if anything is checked, if -1 is return, you can avoid toast appear

How do I specify the JDK for a GlassFish domain?

According to the GF Administration Guide:

For a valid JVM installation, locations are checked in the following order: a. domain.xml (java-home inside java-config) b. asenv.conf (setting AS_JAVA="path to java home")

I had to add both these settings to make it work. Otherwise 'asadmin stop-domain domain1' wouldn't work. I guess that GF uses a. and asadmin uses b.

(On Windows: b. asenv.bat)

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

This Works For me !!!

Call a Function without Parameter

$("#CourseSelect").change(function(e1) {
   loadTeachers();
});

Call a Function with Parameter

$("#CourseSelect").change(function(e1) {
    loadTeachers($(e1.target).val());
});

How to rename with prefix/suffix?

If it's open to a modification, you could use a suffix instead of a prefix. Then you could use tab-completion to get the original filename and add the suffix.

Otherwise, no this isn't something that is supported by the mv command. A simple shell script could cope though.

Android Studio - Importing external Library/Jar

I use android studio 0.8.6 and for importing external library in project , paste that library in libs folder and inside build.gradle write path of that library inside dependencies like this compile files('libs/google-play-services.jar')

How do I pass a command line argument while starting up GDB in Linux?

Once gdb starts, you can run the program using "r args".

So if you are running your code by:

$ executablefile arg1 arg2 arg3 

Debug it on gdb by:

$ gdb executablefile  
(gdb) r arg1 arg2 arg3

Delete all local git branches

Make sure you do this first

git fetch

Once you have all remote branches information, use the following command to remove every single branch except master

 git branch -a | grep -v "master" | grep remotes | sed 's/remotes\/origin\///g' | xargs git push origin --delete

MySql with JAVA error. The last packet sent successfully to the server was 0 milliseconds ago

The problem is mostly due to a MySQL service that is not running, so make sure it is. If it isn't, run this CMD with administrator privilege in order to start it:

sc start [Your MySQL Service name]

SLF4J: Class path contains multiple SLF4J bindings

<!--<dependency>-->
     <!--<groupId>org.springframework.boot</groupId>-->
     <!--<artifactId>spring-boot-starter-log4j2</artifactId>-->
<!--</dependency>-->

I solved by delete this:spring-boot-starter-log4j2

How to create empty constructor for data class in Kotlin Android

If you give a default value to each primary constructor parameter:

data class Item(var id: String = "",
            var title: String = "",
            var condition: String = "",
            var price: String = "",
            var categoryId: String = "",
            var make: String = "",
            var model: String = "",
            var year: String = "",
            var bodyStyle: String = "",
            var detail: String = "",
            var latitude: Double = 0.0,
            var longitude: Double = 0.0,
            var listImages: List<String> = emptyList(),
            var idSeller: String = "")

and from the class where the instances you can call it without arguments or with the arguments that you have that moment

var newItem = Item()

var newItem2 = Item(title = "exampleTitle",
            condition = "exampleCondition",
            price = "examplePrice",
            categoryId = "exampleCategoryId")

How do I simulate a low bandwidth, high latency environment?

I would try using netem on linux. With it you can simulate additional delay, corruption, packet loss and duplication. It even works on the loopback device.

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

Just use

filter_input(INPUT_METHOD_NAME, 'var_name') instead of $_INPUT_METHOD_NAME['var_name'] filter_input_array(INPUT_METHOD_NAME) instead of $_INPUT_METHOD_NAME

e.g

    $host= filter_input(INPUT_SERVER, 'HTTP_HOST');
    echo $host;

instead of

    $host= $_SERVER['HTTP_HOST'];
    echo $host;

And use

    var_dump(filter_input_array(INPUT_SERVER));

instead of

    var_dump($_SERVER);

N.B: Apply to all other Super Global variable

catch forEach last iteration

Updated answer for ES6+ is here.


arr = [1, 2, 3]; 

arr.forEach(function(i, idx, array){
   if (idx === array.length - 1){ 
       console.log("Last callback call at index " + idx + " with value " + i ); 
   }
});

would output:

Last callback call at index 2 with value 3

The way this works is testing arr.length against the current index of the array, passed to the callback function.

HTML table: keep the same width for columns

give this style to td: width: 1%;

How to run a script at the start up of Ubuntu?

First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local.

Another simple way is to use @reboot in your crontab. Read the cron manpage for details.

However, if you want to do things properly, in addition to adding a script to /etc/init.d you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d which creates a symlink from some of the /etc/rc* directories to your script. So, you'd need to do something like:

update-rc.d yourscriptname start 2

However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README has some details and further pointers.

How can I see the size of a GitHub repository before cloning it?

There's a way to access this information through the GitHub API.

When retrieving information about a repository, a property named size is valued with the size of the whole repository (including all of its history), in kilobytes.

For instance, the Git repository weights around 124 MB. The size property of the returned JSON payload is valued to 124283.

Update

The size is indeed expressed in kilobytes based on the disk usage of the server-side bare repository. However, in order to avoid wasting too much space with repositories with a large network, GitHub relies on Git Alternates. In this configuration, calculating the disk usage against the bare repository doesn't account for the shared object store and thus returns an "incomplete" value through the API call.

This information has been given by GitHub support.

Can I limit the length of an array in JavaScript?

You're not using splice correctly:

arr.splice(4, 1)

this will remove 1 item at index 4. see here

I think you want to use slice:

arr.slice(0,5)

this will return elements in position 0 through 4.

This assumes all the rest of your code (cookies etc) works correctly

jquery - fastest way to remove all rows from a very large table

Using detach is magnitudes faster than any of the other answers here:

$('#mytable').find('tbody').detach();

Don't forget to put the tbody element back into the table since detach removed it:

$('#mytable').append($('<tbody>'));  

Also note that when talking efficiency $(target).find(child) syntax is faster than $(target > child). Why? Sizzle!

Elapsed Time to Empty 3,161 Table Rows

Using the Detach() method (as shown in my example above):

  • Firefox: 0.027s
  • Chrome: 0.027s
  • Edge: 1.73s
  • IE11: 4.02s

Using the empty() method:

  • Firefox: 0.055s
  • Chrome: 0.052s
  • Edge: 137.99s (might as well be frozen)
  • IE11: Freezes and never returns

ORA-12516, TNS:listener could not find available handler

You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.

A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.

Courtesy of this thread: https://community.oracle.com/thread/362226?tstart=-1

How to check if all of the following items are in a list?

I like these two because they seem the most logical, the latter being shorter and probably fastest (shown here using set literal syntax which has been backported to Python 2.7):

all(x in {'a', 'b', 'c'} for x in ['a', 'b'])
#   or
{'a', 'b'}.issubset({'a', 'b', 'c'})

Facebook Access Token for Pages

See here if you want to grant a Facebook App permanent access to a page (even when you / the app owner are logged out):

http://developers.facebook.com/docs/opengraph/using-app-tokens/

"An App Access Token does not expire unless you refresh the application secret through your app settings."

How to download source in ZIP format from GitHub?

As of June 2016, the Download ZIP button is still under the <> Code tab, however it is now inside a button with two options clone or download:

Symfony image example

HTML table sort

Check if you could go with any of the below mentioned JQuery plugins. Simply awesome and provide wide range of options to work through, and less pains to integrate. :)

https://github.com/paulopmx/Flexigrid - Flexgrid
http://datatables.net/index - Data tables.
https://github.com/tonytomov/jqGrid

If not, you need to have a link to those table headers that calls a server-side script to invoke the sort.

Is there a way to cast float as a decimal without rounding and preserving its precision?

cast (field1 as decimal(53,8)
) field 1

The default is: decimal(18,0)

Getting only Month and Year from SQL DATE

Try SELECT CONCAT(month(datefield), '.', year(datefield)) FROM YOURTABLE;

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

If it happens, then it means you have to upgrade your node.js. Simply uninstall your current node from your pc or mac and download the latest version from https://nodejs.org/en/

Java dynamic array sizes?

You can do some thing

private  static Person []  addPersons(Person[] persons, Person personToAdd) {
    int currentLenght = persons.length;

    Person [] personsArrayNew = Arrays.copyOf(persons, currentLenght +1);
    personsArrayNew[currentLenght]  = personToAdd;

    return personsArrayNew;

}

How do I get the current date in Cocoa

+ (NSString *)displayCurrentTimeWithAMPM 
{
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:@"h:mm aa"];

    NSString *dateTime = [NSString stringWithFormat:@"%@",[outputFormatter stringFromDate:[NSDate date]]];

    return dateTime;
}

return 3:33 AM

Change package name for Android in React Native

very simple way :

cd /your/project/dir

run this command :

grep -rl "com.your.app" . | xargs sed -i 's/com.your.app/com.yournew.newapp/g'

rename your folder

android/app/src/main/java/com/your/app

change to

android/app/src/main/java/com/yournew/newapp

Find the host name and port using PSQL commands

SELECT CURRENT_USER usr, :'HOST' host, inet_server_port() port;

This uses psql's built in HOST variable, documented here

And postgres System Information Functions, documented here

"Insert if not exists" statement in SQLite

For a unique column, use this:

INSERT OR REPLACE INTO table () values();

For more information, see: sqlite.org/lang_insert

Setting cursor at the end of any text of a textbox

You can set the caret position using TextBox.CaretIndex. If the only thing you need is to set the cursor at the end, you can simply pass the string's length, eg:

txtBox.CaretIndex=txtBox.Text.Length;

You need to set the caret index at the length, not length-1, because this would put the caret before the last character.

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

Here it was the "Work Folders" feature having been added on a Server 2012 R2. By default it is listening for HTTPS client requests on port 443 via the "System" process. There is a Technet blog post explaining how to change that port number. Don't forget to add a corresponding firewall rule for your custom port and disable the existing one for port 443 though.

How to determine if .NET Core is installed

It doesn't need a installation process.

I have pinned "VSCore" on my taskbar (win10), so open it, and open a task manager choose "Visual Studio Core" process expand left arrow and over any of them child process right button over it and click in "Open File Location" menu.

If you don't remember where is installed search "Code.exe" file in all your hard drives.

d3 add text to circle

Extended the example above to fit the actual requirements, where circled is filled with solid background color, then with striped pattern & after that text node is placed on the center of the circle.

_x000D_
_x000D_
var width = 960,_x000D_
  height = 500,_x000D_
  json = {_x000D_
    "nodes": [{_x000D_
      "x": 100,_x000D_
      "r": 20,_x000D_
      "label": "Node 1",_x000D_
      "color": "red"_x000D_
    }, {_x000D_
      "x": 200,_x000D_
      "r": 25,_x000D_
      "label": "Node 2",_x000D_
      "color": "blue"_x000D_
    }, {_x000D_
      "x": 300,_x000D_
      "r": 30,_x000D_
      "label": "Node 3",_x000D_
      "color": "green"_x000D_
    }]_x000D_
  };_x000D_
_x000D_
var svg = d3.select("body").append("svg")_x000D_
  .attr("width", width)_x000D_
  .attr("height", height)_x000D_
_x000D_
svg.append("defs")_x000D_
  .append("pattern")_x000D_
  .attr({_x000D_
    "id": "stripes",_x000D_
    "width": "8",_x000D_
    "height": "8",_x000D_
    "fill": "red",_x000D_
    "patternUnits": "userSpaceOnUse",_x000D_
    "patternTransform": "rotate(60)"_x000D_
  })_x000D_
  .append("rect")_x000D_
  .attr({_x000D_
    "width": "4",_x000D_
    "height": "8",_x000D_
    "transform": "translate(0,0)",_x000D_
    "fill": "grey"_x000D_
  });_x000D_
_x000D_
function plotChart(json) {_x000D_
  /* Define the data for the circles */_x000D_
  var elem = svg.selectAll("g myCircleText")_x000D_
    .data(json.nodes)_x000D_
_x000D_
  /*Create and place the "blocks" containing the circle and the text */_x000D_
  var elemEnter = elem.enter()_x000D_
    .append("g")_x000D_
    .attr("class", "node-group")_x000D_
    .attr("transform", function(d) {_x000D_
      return "translate(" + d.x + ",80)"_x000D_
    })_x000D_
_x000D_
  /*Create the circle for each block */_x000D_
  var circleInner = elemEnter.append("circle")_x000D_
    .attr("r", function(d) {_x000D_
      return d.r_x000D_
    })_x000D_
    .attr("stroke", function(d) {_x000D_
      return d.color;_x000D_
    })_x000D_
    .attr("fill", function(d) {_x000D_
      return d.color;_x000D_
    });_x000D_
_x000D_
  var circleOuter = elemEnter.append("circle")_x000D_
    .attr("r", function(d) {_x000D_
      return d.r_x000D_
    })_x000D_
    .attr("stroke", function(d) {_x000D_
      return d.color;_x000D_
    })_x000D_
    .attr("fill", "url(#stripes)");_x000D_
_x000D_
  /* Create the text for each block */_x000D_
  elemEnter.append("text")_x000D_
    .text(function(d) {_x000D_
      return d.label_x000D_
    })_x000D_
    .attr({_x000D_
      "text-anchor": "middle",_x000D_
      "font-size": function(d) {_x000D_
        return d.r / ((d.r * 10) / 100);_x000D_
      },_x000D_
      "dy": function(d) {_x000D_
        return d.r / ((d.r * 25) / 100);_x000D_
      }_x000D_
    });_x000D_
};_x000D_
_x000D_
plotChart(json);
_x000D_
.node-group {_x000D_
  fill: #ffffff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
_x000D_
_x000D_
_x000D_

Output:

enter image description here

Below is the link to codepen also:

See the Pen D3-Circle-Pattern-Text by Manish Kumar (@mkdudeja) on CodePen.

Thanks, Manish Kumar

How to create multiple page app using react

The second part of your question is answered well. Here is the answer for the first part: How to output multiple files with webpack:

    entry: {
            outputone: './source/fileone.jsx',
            outputtwo: './source/filetwo.jsx'
            },
    output: {
            path: path.resolve(__dirname, './wwwroot/js/dist'),
            filename: '[name].js'      
            },

This will generate 2 files: outputone.js und outputtwo.js in the target folder.

What is this CSS selector? [class*="span"]

The Following:

.show-grid [class*="span"] {

means that all child elements of '.show-grid' with a class that CONTAINS the word 'span' in it will acquire those CSS properties.

<div class="show-grid">
  <div class="span">.span</div>
  <div class="span6">span6</div>
  <div class="attention-span">attention</div>
  <div class="spanish">spanish</div>
  <div class="mariospan">mariospan</div>
  <div class="espanol">espanol</div>

  <div>
    <div class="span">.span</div>
  </div>

  <p class="span">span</p>
  <span class="span">I do GET HIT</span>

  <span>I DO NOT GET HIT since I need a class of 'span'</span>
</div>

<div class="span">I DO NOT GET HIT since I'm outside of .show-grid</span>

All of the elements get hit except for the <span> by itself.


In Regards to Bootstrap:

  • span6 : this was Bootstrap 2's scaffolding technique which divided a section into a horizontal grid, based on parts of 12. Thus span6 would have a width of 50%.
  • In the current day implementation of Bootstrap (v.3 and v.4), you now use the .col-* classes (e.g. col-sm-6), which also specifies a media breakpoint to handle responsiveness when the window shrinks below a certain size. Check Bootstrap 4.1 and Bootstrap 3.3.7 for more documentation. I would recommend going with a later Bootstrap nowadays

Global Git ignore

From here.

If you create a file in your repo named .gitignore git will use its rules when looking at files to commit. Note that git will not ignore a file that was already tracked before a rule was added to this file to ignore it. In such a case the file must be un-tracked, usually with :

git rm --cached filename

Is it your case ?

JavaScript function to add X months to a date

Easiest solution is:

const todayDate = Date.now();
return new Date(todayDate + 1000 * 60 * 60 * 24 * 30* X); 

where X is the number of months we want to add.

How to efficiently build a tree from a flat structure?

The accepted answer looks way too complex to me so I am adding a Ruby and NodeJS versions of it

Suppose that flat nodes list have the following structure:

nodes = [
  { id: 7, parent_id: 1 },
  ...
] # ruby

nodes = [
  { id: 7, parentId: 1 },
  ...
] # nodeJS

The functions which will turn the flat list structure above into a tree look the following way

for Ruby:

def to_tree(nodes)

  nodes.each do |node|

    parent = nodes.find { |another| another[:id] == node[:parent_id] }
    next unless parent

    node[:parent] = parent
    parent[:children] ||= []
    parent[:children] << node

  end

  nodes.select { |node| node[:parent].nil? }

end

for NodeJS:

const toTree = (nodes) => {

  nodes.forEach((node) => {

    const parent = nodes.find((another) => another.id == node.parentId)
    if(parent == null) return;

    node.parent = parent;
    parent.children = parent.children || [];
    parent.children = parent.children.concat(node);

  });

  return nodes.filter((node) => node.parent == null)

};

Converting String to Int using try/except in Python

It is important to be specific about what exception you're trying to catch when using a try/except block.

string = "abcd"
try:
    string_int = int(string)
    print(string_int)
except ValueError:
    # Handle the exception
    print('Please enter an integer')

Try/Excepts are powerful because if something can fail in a number of different ways, you can specify how you want the program to react in each fail case.

What is the @Html.DisplayFor syntax for?

Html.DisplayFor() will render the DisplayTemplate that matches the property's type.

If it can't find any, I suppose it invokes .ToString().


If you don't know about display templates, they're partial views that can be put in a DisplayTemplates folder inside the view folder associated to a controller.


Example:

If you create a view named String.cshtml inside the DisplayTemplates folder of your views folder (e.g Home, or Shared) with the following code:

@model string

@if (string.IsNullOrEmpty(Model)) {
   <strong>Null string</strong>
}
else {
   @Model
}

Then @Html.DisplayFor(model => model.Title) (assuming that Title is a string) will use the template and display <strong>Null string</strong> if the string is null, or empty.

Open a URL in a new tab (and not a new window)

Whether to open the URL in a new tab or a new window, is actually controlled by the user's browser preferences. There is no way to override it in JavaScript.

window.open() behaves differently depending on how it is being used. If it is called as a direct result of a user action, let us say a button click, it should work fine and open a new tab (or window):

const button = document.querySelector('#openTab');

// add click event listener
button.addEventListener('click', () => {
    // open a new tab
    const tab = window.open('https://attacomsian.com', '_blank');
});

However, if you try to open a new tab from an AJAX request callback, the browser will block it as it was not a direct user action.

To bypass the popup blocker and open a new tab from a callback, here is a little hack:

const button = document.querySelector('#openTab');

// add click event listener
button.addEventListener('click', () => {

    // open an empty window
    const tab = window.open('about:blank');

    // make an API call
    fetch('/api/validate')
        .then(res => res.json())
        .then(json => {

            // TODO: do something with JSON response

            // update the actual URL
            tab.location = 'https://attacomsian.com';
            tab.focus();
        })
        .catch(err => {
            // close the empty window
            tab.close();
        });
});

Stop Chrome Caching My JS Files

The problem is that Chrome needs to have must-revalidate in the Cache-Control` header in order to re-check files to see if they need to be re-fetched.

You can always SHIFT-F5 and force Chrome to refresh, but if you want to fix this problem on the server, include this response header:

Cache-Control: must-revalidate

This tells Chrome to check with the server, and see if there is a newer file. IF there is a newer file, it will receive it in the response. If not, it will receive a 304 response, and the assurance that the one in the cache is up to date.

If you do NOT set this header, then in the absence of any other setting that invalidates the file, Chrome will never check with the server to see if there is a newer version.

Here is a blog post that discusses the issue further.

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

To add ANDROID_HOME value permanently,

gedit ~/.bashrc

and add the following lines

export ANDROID_HOME=/root/Android/Sdk
PATH=$PATH:$ANDROID_HOME/tools

Save the file and you need not update ANDROID_HOME value everytime.

ImportError: No module named Image

On a system with both Python 2 and 3 installed and with pip2-installed Pillow failing to provide Image, it is possible to install PIL for Python 2 in a way that will solve ImportError: No module named Image:

easy_install-2.7 --user PIL

or

sudo easy_install-2.7 PIL

Access VBA | How to replace parts of a string with another string

Use Access's VBA function Replace(text, find, replacement):

Dim result As String

result = Replace("Some sentence containing Avenue in it.", "Avenue", "Ave")

Getting "A potentially dangerous Request.Path value was detected from the client (&)"

I have faced this type of error. to call a function from the razor.

public ActionResult EditorAjax(int id, int? jobId, string type = ""){}

solved that by changing the line

from

<a href="/ScreeningQuestion/EditorAjax/5&jobId=2&type=additional" /> 

to

<a href="/ScreeningQuestion/EditorAjax/?id=5&jobId=2&type=additional" />

where my route.config is

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new string[] { "RPMS.Controllers" } // Parameter defaults
        );

Check if specific input file is empty

<input type="file" class="custom-file-input" id="imagefile" name="imagefile[]"  multiple lang="en">
<input type="hidden" name="hidden_imagefile[]" value="<?=$row[2]; ?>" class="form-control border-input" >

    if($_FILES['imagefile']['name'] == '')
        {
          $img = $_POST['hidden_imagefile'];
        }
        else{
          $img = '';
          $uploadFolder = 'uploads/gallery/';
          foreach ($_FILES['imagefile']['tmp_name'] as $key => $image) {
            $imageTmpName = time() .$_FILES['imagefile']['tmp_name'][$key];
            $imageName = time() .$_FILES['imagefile']['name'][$key];
            $img .= $imageName.',';
            $result = move_uploaded_file($imageTmpName, $uploadFolder.$img);
          }
          
        }

Shell - Write variable contents to a file

If I understood you right, you want to copy $var in a file (if it's a string).

echo $var > $destdir

Reverse Y-Axis in PyPlot

using ylim() might be the best approach for your purpose:

xValues = list(range(10))
quads = [x** 2 for x in xValues]
plt.ylim(max(quads), 0)
plt.plot(xValues, quads)

will result:enter image description here

Measuring text height to be drawn on Canvas ( Android )

There are different ways to measure the height depending on what you need.

getTextBounds

If you are doing something like precisely centering a small amount of fixed text, you probably want getTextBounds. You can get the bounding rectangle like this

Rect bounds = new Rect();
mTextPaint.getTextBounds(mText, 0, mText.length(), bounds);
int height = bounds.height();

As you can see for the following images, different strings will give different heights (shown in red).

enter image description here

These differing heights could be a disadvantage in some situations when you just need a constant height no matter what the text is. See the next section.

Paint.FontMetrics

You can calculate the hight of the font from the font metrics. The height is always the same because it is obtained from the font, not any particular text string.

Paint.FontMetrics fm = mTextPaint.getFontMetrics();
float height = fm.descent - fm.ascent;

The baseline is the line that the text sits on. The descent is generally the furthest a character will go below the line and the ascent is generally the furthest a character will go above the line. To get the height you have to subtract ascent because it is a negative value. (The baseline is y=0 and y descreases up the screen.)

Look at the following image. The heights for both of the strings are 234.375.

enter image description here

If you want the line height rather than just the text height, you could do the following:

float height = fm.bottom - fm.top + fm.leading; // 265.4297

These are the bottom and top of the line. The leading (interline spacing) is usually zero, but you should add it anyway.

The images above come from this project. You can play around with it to see how Font Metrics work.

StaticLayout

For measuring the height of multi-line text you should use a StaticLayout. I talked about it in some detail in this answer, but the basic way to get this height is like this:

String text = "This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.";

TextPaint myTextPaint = new TextPaint();
myTextPaint.setAntiAlias(true);
myTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
myTextPaint.setColor(0xFF000000);

int width = 200;
Layout.Alignment alignment = Layout.Alignment.ALIGN_NORMAL;
float spacingMultiplier = 1;
float spacingAddition = 0;
boolean includePadding = false;

StaticLayout myStaticLayout = new StaticLayout(text, myTextPaint, width, alignment, spacingMultiplier, spacingAddition, includePadding);

float height = myStaticLayout.getHeight(); 

Difference between xcopy and robocopy

The most important difference is that robocopy will (usually) retry when an error occurs, while xcopy will not. In most cases, that makes robocopy far more suitable for use in a script.

Addendum: for completeness, there is one known edge case issue with robocopy; it may silently fail to copy files or directories whose names contain invalid UTF-16 sequences. If that's a problem for you, you may need to look at third-party tools, or write your own.

ld.exe: cannot open output file ... : Permission denied

Problem Cause : The process of the current program is still running without interuption. (This is the reason why you haven't got this issue after a restart)

The fix is simple : Go to cmd and type the command taskkill -im process-name.exe -f

Eg:

 taskkill -im demo.exe -f

here,

demo - is my program name

Best way to remove items from a collection

Similar to Dictionary Collection point of view, I have done this.

Dictionary<string, bool> sourceDict = new Dictionary<string, bool>();
sourceDict.Add("Sai", true);
sourceDict.Add("Sri", false);
sourceDict.Add("SaiSri", true);
sourceDict.Add("SaiSriMahi", true);

var itemsToDelete = sourceDict.Where(DictItem => DictItem.Value == false);

foreach (var item in itemsToDelete)
{
    sourceDict.Remove(item.Key);
}

Note: Above code will fail in .Net Client Profile (3.5 and 4.5) also some viewers mentioned it is Failing for them in .Net4.0 as well not sure which settings are causing the problem.

So replace with below code (.ToList()) for Where statement, to avoid that error. “Collection was modified; enumeration operation may not execute.”

var itemsToDelete = sourceDict.Where(DictItem => DictItem.Value == false).ToList();

Per MSDN From .Net4.5 onwards Client Profile are discontinued. http://msdn.microsoft.com/en-us/library/cc656912(v=vs.110).aspx

Insert Unicode character into JavaScript

The answer is correct, but you don't need to declare a variable. A string can contain your character:

"This string contains omega, that looks like this: \u03A9"

Unfortunately still those codes in ASCII are needed for displaying UTF-8, but I am still waiting (since too many years...) the day when UTF-8 will be same as ASCII was, and ASCII will be just a remembrance of the past.

Smooth scrolling with just pure css

You can do this with pure CSS but you will need to hard code the offset scroll amounts, which may not be ideal should you be changing page content- or should dimensions of your content change on say window resize.

You're likely best placed to use e.g. jQuery, specifically:

$('html, body').stop().animate({
   scrollTop: element.offset().top
}, 1000);

A complete implementation may be:

$('#up, #down').on('click', function(e){
    e.preventDefault();
    var target= $(this).get(0).id == 'up' ? $('#down') : $('#up');
    $('html, body').stop().animate({
       scrollTop: target.offset().top
    }, 1000);
});

Where element is the target element to scroll to and 1000 is the delay in ms before completion.

Demo Fiddle

The benefit being, no matter what changes to your content dimensions, the function will not need to be altered.

How can I retrieve the remote git address of a repo?

The long boring solution, which is not involved with CLI, you can manually navigate to:

your local repo folder ? .git folder (hidden) ? config file

then choose your text editor to open it and look for url located under the [remote "origin"] section.

"While .. End While" doesn't work in VBA?

VBA is not VB/VB.NET

The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:

Do While counter < 20
    counter = counter + 1
Loop

(But a For..Next might be more appropriate here.)

Happy coding.

Generic Interface

If I understand correctly, you want to have one class implement multiple of those interfaces with different input/output parameters? This will not work in Java, because the generics are implemented via erasure.

The problem with the Java generics is that the generics are in fact nothing but compiler magic. At runtime, the classes do not keep any information about the types used for generic stuff (class type parameters, method type parameters, interface type parameters). Therefore, even though you could have overloads of specific methods, you cannot bind those to multiple interface implementations which differ in their generic type parameters only.

In general, I can see why you think that this code has a smell. However, in order to provide you with a better solution, it would be necessary to know a little more about your requirements. Why do you want to use a generic interface in the first place?

Why do I always get the same sequence of random numbers with rand()?

None of you guys are answering his question.

with this code i get the same sequance everytime the code but it generates random sequences if i add srand(/somevalue/) before the for loop . can someone explain why ?

From what my professor has told me, it is used if you want to make sure your code is running properly and to see if there is something wrong or if you can change something.

Copy a file from one folder to another using vbscripting

Try this. It will check to see if the file already exists in the destination folder, and if it does will check if the file is read-only. If the file is read-only it will change it to read-write, replace the file, and make it read-only again.

Const DestinationFile = "c:\destfolder\anyfile.txt"
Const SourceFile = "c:\sourcefolder\anyfile.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
    'Check to see if the file already exists in the destination folder
    If fso.FileExists(DestinationFile) Then
        'Check to see if the file is read-only
        If Not fso.GetFile(DestinationFile).Attributes And 1 Then 
            'The file exists and is not read-only.  Safe to replace the file.
            fso.CopyFile SourceFile, "C:\destfolder\", True
        Else 
            'The file exists and is read-only.
            'Remove the read-only attribute
            fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
            'Replace the file
            fso.CopyFile SourceFile, "C:\destfolder\", True
            'Reapply the read-only attribute
            fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
        End If
    Else
        'The file does not exist in the destination folder.  Safe to copy file to this folder.
        fso.CopyFile SourceFile, "C:\destfolder\", True
    End If
Set fso = Nothing

Signed versus Unsigned Integers

Just a few points for completeness:

  • this answer is discussing only integer representations. There may be other answers for floating point;

  • the representation of a negative number can vary. The most common (by far - it's nearly universal today) in use today is two's complement. Other representations include one's complement (quite rare) and signed magnitude (vanishingly rare - probably only used on museum pieces) which is simply using the high bit as a sign indicator with the remain bits representing the absolute value of the number.

  • When using two's complement, the variable can represent a larger range (by one) of negative numbers than positive numbers. This is because zero is included in the 'positive' numbers (since the sign bit is not set for zero), but not the negative numbers. This means that the absolute value of the smallest negative number cannot be represented.

  • when using one's complement or signed magnitude you can have zero represented as either a positive or negative number (which is one of a couple of reasons these representations aren't typically used).

Align Div at bottom on main Div

Give your parent div position: relative, then give your child div position: absolute, this will absolute position the div inside of its parent, then you can give the child bottom: 0px;

See example here:

http://jsfiddle.net/PGMqs/1/

How to cancel a Task in await?

Read up on Cancellation (which was introduced in .NET 4.0 and is largely unchanged since then) and the Task-Based Asynchronous Pattern, which provides guidelines on how to use CancellationToken with async methods.

To summarize, you pass a CancellationToken into each method that supports cancellation, and that method must check it periodically.

private async Task TryTask()
{
  CancellationTokenSource source = new CancellationTokenSource();
  source.CancelAfter(TimeSpan.FromSeconds(1));
  Task<int> task = Task.Run(() => slowFunc(1, 2, source.Token), source.Token);

  // (A canceled task will raise an exception when awaited).
  await task;
}

private int slowFunc(int a, int b, CancellationToken cancellationToken)
{
  string someString = string.Empty;
  for (int i = 0; i < 200000; i++)
  {
    someString += "a";
    if (i % 1000 == 0)
      cancellationToken.ThrowIfCancellationRequested();
  }

  return a + b;
}

How to change icon on Google map marker

var marker = new google.maps.Marker({
                position: new google.maps.LatLng(23.016427,72.571156),
                map: map,
                icon: 'images/map_marker_icon.png',
                title: 'Hi..!'
            });

apply local path on icon only

ArrayAdapter in android to create simple listview

ArrayAdapter uses a TextView to display each item within it. Behind the scenes, it uses the toString() method of each object that it holds and displays this within the TextView. ArrayAdapter has a number of constructors that can be used and the one that you have used in your example is:

ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)

By default, ArrayAdapter uses the default TextView to display each item. But if you want, you could create your own TextView and implement any complex design you'd like by extending the TextView class. This would then have to go into the layout for your use. You could reference this in the textViewResourceId field to bind the objects to this view instead of the default.

For your use, I would suggest that you use the constructor:

ArrayAdapter(Context context, int resource, T[] objects). 

In your case, this would be:

ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values)

and it should be fine. This will bind each string to the default TextView display - plain and simple white background.

So to answer your question, you do not have to use the textViewResourceId.

SQL recursive query on self referencing table (Oracle)

What about using PRIOR,

so

SELECT id, parent_id, PRIOR name
   FROM tbl 
START WITH id = 1 
CONNECT BY PRIOR id = parent_id`

or if you want to get the root name

SELECT id, parent_id, CONNECT_BY_ROOT name
   FROM tbl 
START WITH id = 1 
CONNECT BY PRIOR id = parent_id

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

Adding skipLibCheck: true in compilerOptions inside tsconfig.json file fixed my issue.

"compilerOptions": {
   "skipLibCheck": true,
},

How do I convert an object to an array?

You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:

$array = json_decode(json_encode($response->response->docs), true);

How to reformat JSON in Notepad++?

Update:

As of Notepad++ v7.6, use Plugin Admin to install JSTool per this answer

INSTALL

Download it from http://sourceforge.net/projects/jsminnpp/ and copy JSMinNpp.dll to plugin directory of Notepad++. Or you can just install "JSTool" from Plugin Manager in Notepad++.

New Notepad++ install and where did PluginManager go? See How to view Plugin Manager in Notepad++

{
  "menu" : {
    "id" : "file",
    "value" : "File",
    "popup" : {
      "menuitem" : [{
      "value" : "New",
          "onclick" : "CreateNewDoc()"
        }, {
          "value" : "Open",
          "onclick" : "OpenDoc()"
        }, {
          "value" : "Close",
          "onclick" : "CloseDoc()"
        }
      ]
    }
  }
}

enter image description here Tip: Select the code you want to reformat, then Plugins | JSTool | JSFormat.

Console app arguments, how arguments are passed to Main method

Command line arguments is one way to pass the arguments in. This msdn sample is worth checking out. The MSDN Page for command line arguments is also worth reading.

From within visual studio you can set the command line arguments by Choosing the properties of your console application then selecting the Debug tab

How to catch segmentation fault in Linux?

Sometimes we want to catch a SIGSEGV to find out if a pointer is valid, that is, if it references a valid memory address. (Or even check if some arbitrary value may be a pointer.)

One option is to check it with isValidPtr() (worked on Android):

int isValidPtr(const void*p, int len) {
    if (!p) {
    return 0;
    }
    int ret = 1;
    int nullfd = open("/dev/random", O_WRONLY);
    if (write(nullfd, p, len) < 0) {
    ret = 0;
    /* Not OK */
    }
    close(nullfd);
    return ret;
}
int isValidOrNullPtr(const void*p, int len) {
    return !p||isValidPtr(p, len);
}

Another option is to read the memory protection attributes, which is a bit more tricky (worked on Android):

re_mprot.c:

#include <errno.h>
#include <malloc.h>
//#define PAGE_SIZE 4096
#include "dlog.h"
#include "stdlib.h"
#include "re_mprot.h"

struct buffer {
    int pos;
    int size;
    char* mem;
};

char* _buf_reset(struct buffer*b) {
    b->mem[b->pos] = 0;
    b->pos = 0;
    return b->mem;
}

struct buffer* _new_buffer(int length) {
    struct buffer* res = malloc(sizeof(struct buffer)+length+4);
    res->pos = 0;
    res->size = length;
    res->mem = (void*)(res+1);
    return res;
}

int _buf_putchar(struct buffer*b, int c) {
    b->mem[b->pos++] = c;
    return b->pos >= b->size;
}

void show_mappings(void)
{
    DLOG("-----------------------------------------------\n");
    int a;
    FILE *f = fopen("/proc/self/maps", "r");
    struct buffer* b = _new_buffer(1024);
    while ((a = fgetc(f)) >= 0) {
    if (_buf_putchar(b,a) || a == '\n') {
        DLOG("/proc/self/maps: %s",_buf_reset(b));
    }
    }
    if (b->pos) {
    DLOG("/proc/self/maps: %s",_buf_reset(b));
    }
    free(b);
    fclose(f);
    DLOG("-----------------------------------------------\n");
}

unsigned int read_mprotection(void* addr) {
    int a;
    unsigned int res = MPROT_0;
    FILE *f = fopen("/proc/self/maps", "r");
    struct buffer* b = _new_buffer(1024);
    while ((a = fgetc(f)) >= 0) {
    if (_buf_putchar(b,a) || a == '\n') {
        char*end0 = (void*)0;
        unsigned long addr0 = strtoul(b->mem, &end0, 0x10);
        char*end1 = (void*)0;
        unsigned long addr1 = strtoul(end0+1, &end1, 0x10);
        if ((void*)addr0 < addr && addr < (void*)addr1) {
            res |= (end1+1)[0] == 'r' ? MPROT_R : 0;
            res |= (end1+1)[1] == 'w' ? MPROT_W : 0;
            res |= (end1+1)[2] == 'x' ? MPROT_X : 0;
            res |= (end1+1)[3] == 'p' ? MPROT_P
                 : (end1+1)[3] == 's' ? MPROT_S : 0;
            break;
        }
        _buf_reset(b);
    }
    }
    free(b);
    fclose(f);
    return res;
}

int has_mprotection(void* addr, unsigned int prot, unsigned int prot_mask) {
    unsigned prot1 = read_mprotection(addr);
    return (prot1 & prot_mask) == prot;
}

char* _mprot_tostring_(char*buf, unsigned int prot) {
    buf[0] = prot & MPROT_R ? 'r' : '-';
    buf[1] = prot & MPROT_W ? 'w' : '-';
    buf[2] = prot & MPROT_X ? 'x' : '-';
    buf[3] = prot & MPROT_S ? 's' : prot & MPROT_P ? 'p' :  '-';
    buf[4] = 0;
    return buf;
}

re_mprot.h:

#include <alloca.h>
#include "re_bits.h"
#include <sys/mman.h>

void show_mappings(void);

enum {
    MPROT_0 = 0, // not found at all
    MPROT_R = PROT_READ,                                 // readable
    MPROT_W = PROT_WRITE,                                // writable
    MPROT_X = PROT_EXEC,                                 // executable
    MPROT_S = FIRST_UNUSED_BIT(MPROT_R|MPROT_W|MPROT_X), // shared
    MPROT_P = MPROT_S<<1,                                // private
};

// returns a non-zero value if the address is mapped (because either MPROT_P or MPROT_S will be set for valid addresses)
unsigned int read_mprotection(void* addr);

// check memory protection against the mask
// returns true if all bits corresponding to non-zero bits in the mask
// are the same in prot and read_mprotection(addr)
int has_mprotection(void* addr, unsigned int prot, unsigned int prot_mask);

// convert the protection mask into a string. Uses alloca(), no need to free() the memory!
#define mprot_tostring(x) ( _mprot_tostring_( (char*)alloca(8) , (x) ) )
char* _mprot_tostring_(char*buf, unsigned int prot);

PS DLOG() is printf() to the Android log. FIRST_UNUSED_BIT() is defined here.

PPS It may not be a good idea to call alloca() in a loop -- the memory may be not freed until the function returns.

Navigation Controller Push View Controller

Use this code in your button action (Swift 3.0.1):

let vc = self.storyboard?.instantiateViewController(
    withIdentifier: "YourSecondVCIdentifier") as! SecondVC

navigationController?.pushViewController(vc, animated: true)

Cast from VARCHAR to INT - MySQL

For casting varchar fields/values to number format can be little hack used:

SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`

Socket.IO handling disconnect event

Ok, instead of identifying players by name track with sockets through which they have connected. You can have a implementation like

Server

var allClients = [];
io.sockets.on('connection', function(socket) {
   allClients.push(socket);

   socket.on('disconnect', function() {
      console.log('Got disconnect!');

      var i = allClients.indexOf(socket);
      allClients.splice(i, 1);
   });
});

Hope this will help you to think in another way

How do I correct the character encoding of a file?

And then there is the somewhat older recode program.

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

If you changed the ruby version you're using with rvm use, remove Gemfile.lock and try again.

Pytorch reshape tensor dimension

import torch
t = torch.ones((2, 3, 4))
t.size()
>>torch.Size([2, 3, 4])
a = t.view(-1,t.size()[1]*t.size()[2])
a.size()
>>torch.Size([2, 12])

Equivalent VB keyword for 'break'

In case you're inside a Sub of Function and you want to exit it, you can use :

Exit Sub

or

Exit Function 

How can I apply styles to multiple classes at once?

Don’t Repeat Your CSS

 a.abc, a.xyz{
    margin-left:20px;
 }

OR

 a{
    margin-left:20px;
 }

How to center a label text in WPF?

use the HorizontalContentAlignment property.

Sample

<Label HorizontalContentAlignment="Center"/>

error: pathspec 'test-branch' did not match any file(s) known to git

just follow three steps, git branch problem will be solved.

git remote update
git fetch
git checkout --track origin/test-branch

Location for session files in Apache/PHP

The default session.save_path is set to "" which will evaluate to your system's temp directory. See this comment at https://bugs.php.net/bug.php?id=26757 stating:

The new default for save_path in upcoming releaess (sic) will be the empty string, which causes the temporary directory to be probed.

You can use sys_get_temp_dir to return the directory path used for temporary files

To find the current session save path, you can use

Refer to this answer to find out what the temp path is when this function returns an empty string.

Remove Primary Key in MySQL

First backup the database. Then drop any foreign key associated with the table. truncate the foreign key table.Truncate the current table. Remove the required primary keys. Use sqlyog or workbench or heidisql or dbeaver or phpmyadmin.

How to get the indices list of all NaN value in numpy array?

Since x!=x returns the same boolean array with np.isnan(x) (because np.nan!=np.nan would return True), you could also write:

np.argwhere(x!=x)

However, I still recommend writing np.argwhere(np.isnan(x)) since it is more readable. I just try to provide another way to write the code in this answer.

FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison

Can't beat Eric Leschinski's awesomely detailed answer, but here's a quick workaround to the original question that I don't think has been mentioned yet - put the string in a list and use .isin instead of ==

For example:

import pandas as pd
import numpy as np

df = pd.DataFrame({"Name": ["Peter", "Joe"], "Number": [1, 2]})

# Raises warning using == to compare different types:
df.loc[df["Number"] == "2", "Number"]

# No warning using .isin:
df.loc[df["Number"].isin(["2"]), "Number"]

Line Break in HTML Select Option?

HTML Code

<section style="background-color:rgb(237.247.249);">
    <h2>Test of select menu (SelectboxIt plugin)</h2>
    <select name="select_this" id="testselectset">
        <option value="01">Option 1</option>
        <option value="02">Option 2</option>
        <option value="03">Option 3</option>
        <option value="04">Option 4</option>
        <option value="05">Option 5</option>
        <option value="06">Option 6</option>
        <option value="07">Option 7 with a really, really long text line that we shall use in order to test the wrapping of text within an option or optgroup</option>
        <option value="08">Option 8</option>
        <option value="09">Option 9</option>
        <option value="10">Option 10</option>
    </select>
</section>

Javascript Code

$(function(){
    $("#testselectset").selectBoxIt({
        theme: "default",
        defaultText: "Make a selection...",
        autoWidth: false
    });
});

CSS Code

.selectboxit-container .selectboxit, .selectboxit-container .selectboxit-options {
    width: 400px; /* Width of the dropdown button */
    border-radius:0;
    max-height:100px;
}

.selectboxit-options .selectboxit-option .selectboxit-option-anchor {
    white-space: normal;
    min-height: 30px;
    height: auto;
}

and you have to add some Jquery Library select Box Jquery CSS

Jquery Ui Min JS

SelectBox Js

Please check this link JsFiddle Link

how to change language for DataTable

French translations:

$('#my_table').DataTable({
  "language": {
    "sProcessing": "Traitement en cours ...",
    "sLengthMenu": "Afficher _MENU_ lignes",
    "sZeroRecords": "Aucun résultat trouvé",
    "sEmptyTable": "Aucune donnée disponible",
    "sInfo": "Lignes _START_ à _END_ sur _TOTAL_",
    "sInfoEmpty": "Aucune ligne affichée",
    "sInfoFiltered": "(Filtrer un maximum de_MAX_)",
    "sInfoPostFix": "",
    "sSearch": "Chercher:",
    "sUrl": "",
    "sInfoThousands": ",",
    "sLoadingRecords": "Chargement...",
    "oPaginate": {
      "sFirst": "Premier", "sLast": "Dernier", "sNext": "Suivant", "sPrevious": "Précédent"
    },
    "oAria": {
      "sSortAscending": ": Trier par ordre croissant", "sSortDescending": ": Trier par ordre décroissant"
    }
  }
});

});

ionic 2 - Error Could not find an installed version of Gradle either in Android Studio

I was already installed Android Studio and it's just need to add gradle PATH to ~/.bash_profile on my MacOSX Mojave. Also if gradle is upgraded then path might need to update again.

Example .bash_profile :

export ANDROID_SDK_ROOT="~/Library/Android/sdk"
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
export JAVA_HOME=$(/usr/libexec/java_home)
export GRADLE_PATH="~/.gradle/wrapper/dists/gradle-4.10.1-all/455itskqi2qtf0v2sja68alqd/gradle-4.10.1/bin"
export ANDROID_STUDIO="/Applications/Android Studio.app/Contents/MacOS"
export PATH="$PATH:$GRADLE_PATH:$ANDROID_STUDIO"

When edited your .bash_profile then run a command below to read it again.

source ~/.bash_profile

Is there a W3C valid way to disable autocomplete in a HTML form?

No, but browser auto-complete is often triggered by the field having the same name attribute as fields that were previously filled out. If you could rig up a clever way to have a randomized field name, autocomplete wouldn't be able to pull any previously entered values for the field.

If you were to give an input field a name like "email_<?= randomNumber() ?>", and then have the script that receives this data loop through the POST or GET variables looking for something matching the pattern "email_[some number]", you could pull this off, and this would have (practically) guaranteed success, regardless of browser.

SQL is null and = null

It's important to note, that NULL doesn't equal NULL.

NULL is not a value, and therefore cannot be compared to another value.

where x is null checks whether x is a null value.

where x = null is checking whether x equals NULL, which will never be true

HashMaps and Null values?

Acording to your first code snipet seems ok, but I've got similar behavior caused by bad programing. Have you checked the "options" variable is not null before the put call?

I'm using Struts2 (2.3.3) webapp and use a HashMap for displaying results. When is executed (in a class initialized by an Action class) :

if(value != null) pdfMap.put("date",value.toString());
else pdfMap.put("date","");

Got this error:

Struts Problem Report

Struts has detected an unhandled exception:

Messages:   
File:   aoc/psisclient/samples/PDFValidation.java
Line number:    155
Stacktraces

java.lang.NullPointerException
    aoc.psisclient.samples.PDFValidation.getRevisionsDetail(PDFValidation.java:155)
    aoc.action.signature.PDFUpload.execute(PDFUpload.java:66)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    ...

Seems the NullPointerException points to the put method (Line number 155), but the problem was that de Map hasn't been initialized before. It compiled ok since the variable is out of the method that set the value.

How to get the mysql table columns data type?

Query to find out all the datatype of columns being used in any database

SELECT distinct DATA_TYPE FROM INFORMATION_SCHEMA.columns 
WHERE table_schema = '<db_name>' AND column_name like '%';

Is there a way to get a list of all current temporary tables in SQL Server?

Is this what you are after?

select * from tempdb..sysobjects
--for sql-server 2000 and later versions

select * from tempdb.sys.objects
--for sql-server 2005 and later versions

JS: Uncaught TypeError: object is not a function (onclick)

Please change only the name of the function; no other change is required

<script>
    function totalbandwidthresult() {
        alert("fdf");
        var fps = Number(document.calculator.fps.value);
        var bitrate = Number(document.calculator.bitrate.value);
        var numberofcameras = Number(document.calculator.numberofcameras.value);
        var encoding = document.calculator.encoding.value;
        if (encoding = "mjpeg") {
            storage = bitrate * fps;
        } else {
            storage = bitrate;
        }

        totalbandwidth = (numberofcameras * storage) / 1000;
        alert(totalbandwidth);
        document.calculator.totalbandwidthresult.value = totalbandwidth;
    }
</script>

<form name="calculator" class="formtable">
    <div class="formrow">
        <label for="rcname">RC Name</label>
        <input type="text" name="rcname">
    </div>
    <div class="formrow">
        <label for="fps">FPS</label>
        <input type="text" name="fps">
    </div>
    <div class="formrow">
        <label for="bitrate">Bitrate</label>
        <input type="text" name="bitrate">
    </div>
    <div class="formrow">
        <label for="numberofcameras">Number of Cameras</label>
        <input type="text" name="numberofcameras">
    </div>
    <div class="formrow">
        <label for="encoding">Encoding</label>
        <select name="encoding" id="encodingoptions">
            <option value="h264">H.264</option>
            <option value="mjpeg">MJPEG</option>
            <option value="mpeg4">MPEG4</option>
        </select>
    </div>Total Storage:
    <input type="text" name="totalstorage">Total Bandwidth:
    <input type="text" name="totalbandwidth">
    <input type="button" value="totalbandwidthresult" onclick="totalbandwidthresult();">
</form>

Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"

*In all instances the # refers to the cell number

You really don't need the datedif functions; for example:

I'm working on a spreadsheet that tracks benefit eligibility for employees.

I have their hire dates in the "A" column and in column B is =(TODAY()-A#)

And you just format the cell to display a general number instead of date.

It also works very easily the other way: I also converted that number into showing when the actual date is that they get their benefits instead of how many days are left, and that is simply

=(90-B#)+TODAY()

Just make sure you're formatting cells as general numbers or dates accordingly.

Hope this helps.

How to write trycatch in R

Here goes a straightforward example:

# Do something, or tell me why it failed
my_update_function <- function(x){
    tryCatch(
        # This is what I want to do...
        {
        y = x * 2
        return(y)
        },
        # ... but if an error occurs, tell me what happened: 
        error=function(error_message) {
            message("This is my custom message.")
            message("And below is the error message from R:")
            message(error_message)
            return(NA)
        }
    )
}

If you also want to capture a "warning", just add warning= similar to the error= part.

Get Value From Select Option in Angular 4

    //in html file
    <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">Country</label>
                        <select class="form-control" formControlName="country" (change)="onCountryChange($event.target.value)">
                            <option disabled selected value [ngValue]="null"> -- Select Country  -- </option>
                            <option *ngFor="let country of countries" [value]="country.id">{{country.name}}</option>
                            <div *ngIf="isEdit">
                                <option></option>
                            </div>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('country').invalid && studentForm.get('country').touched">
                <div *ngIf="studentForm.get('country').errors.required">*country is required</div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">State</label>
                        <select class="form-control" formControlName="state" (change)="onStateChange($event.target.value)">
                            <option disabled selected value [ngValue]="null"> -- Select State -- </option>
                            <option *ngFor="let state of states" [value]="state.id">{{state.state_name}}</option>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('state').invalid && studentForm.get('state').touched">
                <div *ngIf="studentForm.get('state').errors.required">*state is enter code hererequired</div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">City</label>
                        <select class="form-control" formControlName="city">
                            <option disabled selected value [ngValue]="null"> -- Select City -- </option>
                            <option *ngFor="let city of cities" [value]="city.id" >{{city.city_name}}</option>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('city').invalid && studentForm.get('city').touched">
                <div *ngIf="studentForm.get('city').errors.required">*city is required</div>
            </div>
    //then in component
    onCountryChange(countryId:number){
   this.studentServive.getSelectedState(countryId).subscribe(resData=>{
    this.states = resData;
   });
  }
  onStateChange(stateId:number){
    this.studentServive.getSelectedCity(stateId).subscribe(resData=>{
     this.cities = resData;
    });
   }`enter code here`

Center image in div horizontally

I hope this would be helpful:

.top_image img{
display: block;
margin: 0 auto;
}

How to connect to SQL Server database from JavaScript in the browser?

You shouldn´t use client javascript to access databases for several reasons (bad practice, security issues, etc) but if you really want to do this, here is an example:

var connection = new ActiveXObject("ADODB.Connection") ;

var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";

connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");

rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
   document.write(rs.fields(1));
   rs.movenext;
}

rs.close;
connection.close; 

A better way to connect to a sql server would be to use some server side language like PHP, Java, .NET, among others. Client javascript should be used only for the interfaces.

And there are rumors of an ancient legend about the existence of server javascript, but this is another story. ;)

Detect change to ngModel on a select tag (Angular 2)

I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"

in my .html

<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">

then in my component.ts

reSearch(newValue: string) {
    //this.searchText would equal the new value
    //handle my filtering with the new value
}

Jquery function BEFORE form submission

You can use some div or span instead of button and then on click call some function which submits form at he end.

<form id="my_form">
   <span onclick="submit()">submit</span>
</form>

<script>
   function submit()
   {   
       //do something
       $("#my_form").submit();
   }
</script>

Syntax error on print with Python 3

In Python 3, print became a function. This means that you need to include parenthesis now like mentioned below:

print("Hello World")

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

You could simply use

return

which does exactly the same as

return None

Your function will also return None if execution reaches the end of the function body without hitting a return statement. Returning nothing is the same as returning None in Python.

What's the difference between @Component, @Repository & @Service annotations in Spring?

Even if we interchange @Component or @Repository or @service

It will behave the same , but one aspect is that they wont be able to catch some specific exception related to DAO instead of Repository if we use component or @ service

How to overcome root domain CNAME restrictions?

The reason this question still often arises is because, as you mentioned, somewhere somehow someone presumed as important wrote that the RFC states domain names without subdomain in front of them are not valid. If you read the RFC carefully, however, you'll find that this is not exactly what it says. In fact, RFC 1912 states:

Don't go overboard with CNAMEs. Use them when renaming hosts, but plan to get rid of them (and inform your users).

Some DNS hosts provide a way to get CNAME-like functionality at the zone apex (the root domain level, for the naked domain name) using a custom record type. Such records include, for example:

  • ALIAS at DNSimple
  • ANAME at DNS Made Easy
  • ANAME at easyDNS
  • CNAME at CloudFlare

For each provider, the setup is similar: point the ALIAS or ANAME entry for your apex domain to example.domain.com, just as you would with a CNAME record. Depending on the DNS provider, an empty or @ Name value identifies the zone apex.

ALIAS or ANAME or @ example.domain.com.

If your DNS provider does not support such a record-type, and you are unable to switch to one that does, you will need to use subdomain redirection, which is not that hard, depending on the protocol or server software that needs to do it.

I strongly disagree with the statement that it's done only by "amateur admins" or such ideas. It's a simple "What does the name and its service need to do?" deal, and then to adapt your DNS config to serve those wishes; If your main services are web and e-mail, I don' t see any VALID reason why dropping the CNAMEs for-good would be problematic. After all, who would prefer @subdomain.domain.org over @domain.org ? Who needs "www" if you're already set with the protocol itself? It's illogical to assume that use of a root-domainname would be invalid.

Jquery Change Height based on Browser Size/Resize

If you are using jQuery 1.2 or newer, you can simply use these:

$(window).width();
$(document).width();
$(window).height();
$(document).height();

From there it is a simple matter to decide the height of your element.

Bootstrap 3 modal vertical position center

set modal center to screen

.modal {
  text-align: center;
  padding: 0!important;
}
.modal:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -4px;
}
.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}

Executing multiple SQL queries in one statement with PHP

This may be created sql injection point "SQL Injection Piggy-backed Queries". attackers able to append multiple malicious sql statements. so do not append user inputs directly to the queries.

Security considerations

The API functions mysqli_query() and mysqli_real_query() do not set a connection flag necessary for activating multi queries in the server. An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.

PHP Doc

MongoDB running but can't connect using shell

You may want to check your config to see if the bind_ip is set

bind_ip: 127.0.0.1

If it is then this permits only local logins. Comment this out and restart mongo, this may help.

Fastest way to check a string contain another substring in JavaScript?

You have three possibilites:

  1. Regular expression:

     (new RegExp('word')).test(str)
     // or
     /word/.test(str)
    
  2. indexOf:

     str.indexOf('word') !== -1
    
  3. includes:

     str.includes('word')
    

Regular expressions seem to be faster (at least in Chrome 10).

Performance test - short haystack
Performance test - long haystack


**Update 2011:**

It cannot be said with certainty which method is faster. The differences between the browsers is enormous. While in Chrome 10 indexOf seems to be faster, in Safari 5, indexOf is clearly slower than any other method.

You have to see and try for your self. It depends on your needs. For example a case-insensitive search is way faster with regular expressions.


Update 2018:

Just to save people from running the tests themselves, here are the current results for most common browsers, the percentages indicate performance increase over the next fastest result (which varies between browsers):

Chrome: indexOf (~98% faster) <-- wow
Firefox: cached RegExp (~18% faster)
IE11: cached RegExp(~10% faster)
Edge: indexOf (~18% faster)
Safari: cached RegExp(~0.4% faster)

Note that cached RegExp is: var r = new RegExp('simple'); var c = r.test(str); as opposed to: /simple/.test(str)

How to use WPF Background Worker

using System;  
using System.ComponentModel;   
using System.Threading;    
namespace BackGroundWorkerExample  
{   
    class Program  
    {  
        private static BackgroundWorker backgroundWorker;  

        static void Main(string[] args)  
        {  
            backgroundWorker = new BackgroundWorker  
            {  
                WorkerReportsProgress = true,  
                WorkerSupportsCancellation = true  
            };  

            backgroundWorker.DoWork += backgroundWorker_DoWork;  
            //For the display of operation progress to UI.    
            backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;  
            //After the completation of operation.    
            backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;  
            backgroundWorker.RunWorkerAsync("Press Enter in the next 5 seconds to Cancel operation:");  

            Console.ReadLine();  

            if (backgroundWorker.IsBusy)  
            { 
                backgroundWorker.CancelAsync();  
                Console.ReadLine();  
            }  
        }  

        static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)  
        {  
            for (int i = 0; i < 200; i++)  
            {  
                if (backgroundWorker.CancellationPending)  
                {  
                    e.Cancel = true;  
                    return;  
                }  

                backgroundWorker.ReportProgress(i);  
                Thread.Sleep(1000);  
                e.Result = 1000;  
            }  
        }  

        static void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)  
        {  
            Console.WriteLine("Completed" + e.ProgressPercentage + "%");  
        }  

        static void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)  
        {  

            if (e.Cancelled)  
            {  
                Console.WriteLine("Operation Cancelled");  
            }  
            else if (e.Error != null)  
            {  
                Console.WriteLine("Error in Process :" + e.Error);  
            }  
            else  
            {  
                Console.WriteLine("Operation Completed :" + e.Result);  
            }  
        }  
    }  
} 

Also, referr the below link you will understand the concepts of Background:

http://www.c-sharpcorner.com/UploadFile/1c8574/threads-in-wpf/

Preventing multiple clicks on button

I modified the solution by @Kalyani and so far it's been working beautifully!

$('selector').click(function(event) {
  if(!event.detail || event.detail == 1){ return true; }
  else { return false; }
});

Getting one value from a tuple

General

Single elements of a tuple a can be accessed -in an indexed array-like fashion-

via a[0], a[1], ... depending on the number of elements in the tuple.

Example

If your tuple is a=(3,"a")

  • a[0] yields 3,
  • a[1] yields "a"

Concrete answer to question

def tup():
  return (3, "hello")

tup() returns a 2-tuple.

In order to "solve"

i = 5 + tup()  # I want to add just the three

you select the 3 by

tup()[0|    #first element

so in total

i = 5 + tup()[0]

Alternatives

Go with namedtuple that allows you to access tuple elements by name (and by index). Details at https://docs.python.org/3/library/collections.html#collections.namedtuple

>>> import collections
>>> MyTuple=collections.namedtuple("MyTuple", "mynumber, mystring")
>>> m = MyTuple(3, "hello")
>>> m[0]
3
>>> m.mynumber
3
>>> m[1]
'hello'
>>> m.mystring
'hello'

How do I conditionally apply CSS styles in AngularJS?

span class="circle circle-{{selectcss(document.Extension)}}">

and code

$scope.selectcss = function (data) {
    if (data == '.pdf')
        return 'circle circle-pdf';
    else
        return 'circle circle-small';
};

css

.circle-pdf {
    width: 24px;
    height: 24px;
    font-size: 16px;
    font-weight: 700;
    padding-top: 3px;
    -webkit-border-radius: 12px;
    -moz-border-radius: 12px;
    border-radius: 12px;
    background-image: url(images/pdf_icon32.png);
}

Getting CheckBoxList Item values

Try to use this.

        for (int i = 0; i < chBoxListTables.Items.Count; i++)
        {
            if (chBoxListTables.Items[i].Selected)
            {
                string str = chBoxListTables.Items[i].Text;
                MessageBox.Show(str);

                var itemValue = chBoxListTables.Items[i].Value;
            }
        }

The "V" should be in CAPS in Value.

Here is another code example used in WinForm app and runs properly.

        var chBoxList= new CheckedListBox();
        chBoxList.Items.Add(new ListItem("One", "1"));
        chBoxList.Items.Add(new ListItem("Two", "2"));
        chBoxList.SetItemChecked(1, true);

        var checkedItems = chBoxList.CheckedItems;
        var chkText = ((ListItem)checkedItems[0]).Text;
        var chkValue = ((ListItem)checkedItems[0]).Value;
        MessageBox.Show(chkText);
        MessageBox.Show(chkValue);

How to use setArguments() and getArguments() methods in Fragments?

Instantiating the Fragment the correct way!

getArguments() setArguments() methods seem very useful when it comes to instantiating a Fragment using a static method.
ie Myfragment.createInstance(String msg)

How to do it?

Fragment code

public MyFragment extends Fragment {

    private String displayMsg;
    private TextView text;

    public static MyFragment createInstance(String displayMsg)
    {
        MyFragment fragment = new MyFragment();
        Bundle args = new Bundle();
        args.setString("KEY",displayMsg);
        fragment.setArguments(args);           //set
        return fragment;
    }

    @Override
    public void onCreate(Bundle bundle)
    {
        displayMsg = getArguments().getString("KEY"):    // get 
    }

    @Override
    public View onCreateView(LayoutInlater inflater, ViewGroup parent, Bundle bundle){
        View view = inflater.inflate(R.id.placeholder,parent,false);
        text = (TextView)view.findViewById(R.id.myTextView);
        text.setText(displayMsg)    // show msg
        returm view;
   }

}

Let's say you want to pass a String while creating an Instance. This is how you will do it.

MyFragment.createInstance("This String will be shown in textView");

Read More

1) Why Myfragment.getInstance(String msg) is preferred over new MyFragment(String msg)?
2) Sample code on Fragments

Python Selenium accessing HTML source

By using the page source you will get the whole HTML code.
So first decide the block of code or tag in which you require to retrieve the data or to click the element..

options = driver.find_elements_by_name_("XXX")
for option in options:
    if option.text == "XXXXXX":
        print(option.text)
        option.click()

You can find the elements by name, XPath, id, link and CSS path.

More than one file was found with OS independent path 'META-INF/LICENSE'

I'm having same problem and I tried this

Error: More than one file was found with OS independent path 'META-INF/library_release.kotlin_module'

Solution:

android {
    packagingOptions {
    exclude 'META-INF/library_release.kotlin_module'
    }
}

How to select an element inside "this" in jQuery?

$( this ).find( 'li.target' ).css("border", "3px double red");

or

$( this ).children( 'li.target' ).css("border", "3px double red");

Use children for immediate descendants, or find for deeper elements.

See whether an item appears more than once in a database column

try this:

select salesid,count (salesid) from AXDelNotesNoTracking group by salesid having count (salesid) >1

Convert java.util.date default format to Timestamp in Java

You can use the Calendar class to convert Date

public long getDifference()
{
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
    Date d = sdf.parse("Mon May 27 11:46:15 IST 2013");

    Calendar c = Calendar.getInstance();
    c.setTime(d);
    long time = c.getTimeInMillis();
    long curr = System.currentTimeMillis();
    long diff = curr - time;    //Time difference in milliseconds
    return diff/1000;
}

How to create a new text file using Python

Looks like you forgot the mode parameter when calling open, try w:

file = open("copy.txt", "w") 
file.write("Your text goes here") 
file.close() 

The default value is r and will fail if the file does not exist

'r' open for reading (default)
'w' open for writing, truncating the file first

Other interesting options are

'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists

See Doc for Python2.7 or Python3.6

-- EDIT --

As stated by chepner in the comment below, it is better practice to do it with a withstatement (it guarantees that the file will be closed)

with open("copy.txt", "w") as file:
    file.write("Your text goes here")

Graphviz's executables are not found (Python 3.4)

Just install

conda install graphviz

then install

conda install -c conda-forge pydotplus

Timeout function if it takes too long to finish

I rewrote David's answer using the with statement, it allows you do do this:

with timeout(seconds=3):
    time.sleep(4)

Which will raise a TimeoutError.

The code is still using signal and thus UNIX only:

import signal

class timeout:
    def __init__(self, seconds=1, error_message='Timeout'):
        self.seconds = seconds
        self.error_message = error_message
    def handle_timeout(self, signum, frame):
        raise TimeoutError(self.error_message)
    def __enter__(self):
        signal.signal(signal.SIGALRM, self.handle_timeout)
        signal.alarm(self.seconds)
    def __exit__(self, type, value, traceback):
        signal.alarm(0)

Oracle: How to filter by date and time in a where clause

Obviously '12/01/2012 13:16:32.000' doesn't match 'DD-MON-YYYY hh24:mi' format.

Update:

You need 'MM/DD/YYYY hh24:mi:ss.ff' format and to use TO_TIMESTAMP instead of TO_DATE cause dates don't hold millis in oracle.

Set transparent background using ImageMagick and commandline prompt

I had the same problem. In which i have to remove white background from jpg/png image format using ImageMagick.

What worked for me was:

1) Convert image format to png: convert input.jpg input.png

2) convert input.png -fuzz 2% -transparent white output.png

Dependency Injection vs Factory Pattern

I think these are orthogonal and can be used together. Let me show you an example I recently came across at work:

We were using the Spring framework in Java for DI. A singleton class (Parent) had to instantiate new objects of another class (Child), and those had complex collaborators:

@Component
class Parent {
    // ...
    @Autowired
    Parent(Dep1 dep1, Dep2 dep2, ..., DepN depN) {
        this.dep1 = dep1;
        this.dep2 = dep2;
    }

    void method(int p) {
        Child c = new Child(dep1, dep2, ..., depN, p);
        // ...
    }
}

In this example, Parent has to receive DepX instances only to pass them to the Child constructor. Problems with this:

  1. Parent has more knowledge of Child than it should
  2. Parent has more collaborators than it should
  3. Adding dependencies to Child involves changing Parent

This is when I realized a Factory would fit here perfectly:

  1. It hides all but the true parameters of the Child class, as seen by Parent
  2. It encapsulates the knowledge of creating a Child, which can be centralized in the DI configuration.

This is the simplified Parent class and the ChildFactory class:

@Component
class Parent {
    // ...
    @Autowired
    Parent(ChildFactory childFactory) {
        this.childFactory = childFactory;
    }

    void method(int p) {
        Child c = childFactory.newChild(p);
        // ...
    }
}

@Component
class ChildFactory {
    // ...
    @Autowired
    Parent(Dep1 dep1, Dep2 dep2, ..., DepN depN) {
        this.dep1 = dep1;
        this.dep2 = dep2;
        // ...
        this.depN = depN;
    }

    Child newChild(int p) {
        return new Child(dep1, dep2, ..., depN, p);
    }
}

Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

It works:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);

Javascript Click on Element by Class

If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).

var divs = document.querySelectorAll('.love-button.love-button--loved'); 

for (i = 0; i < divs.length; ++i) {
  divs[i].click();
};

With ES6 and Babel (cannot be run in the browser console directly)

[...document.querySelectorAll('.love-button.love-button--loved')]
   .forEach(div => { div.click(); })

Babel 6 regeneratorRuntime is not defined

I have async await working with webpack/babel build:

"devDependencies": {
    "babel-preset-stage-3": "^6.11.0"
}

.babelrc:

"presets": ["es2015", "stage-3"]

Read SQL Table into C# DataTable

Lots of ways.

Use ADO.Net and use fill on the data adapter to get a DataTable:

using (SqlDataAdapter dataAdapter
    = new SqlDataAdapter ("SELECT blah FROM blahblah ", sqlConn))
{
    // create the DataSet 
    DataSet dataSet = new DataSet(); 
    // fill the DataSet using our DataAdapter 
    dataAdapter.Fill (dataSet);
}

You can then get the data table out of the dataset.

Note in the upvoted answer dataset isn't used, (It appeared after my answer) It does

// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);

Which is preferable to mine.

I would strongly recommend looking at entity framework though ... using datatables and datasets isn't a great idea. There is no type safety on them which means debugging can only be done at run time. With strongly typed collections (that you can get from using LINQ2SQL or entity framework) your life will be a lot easier.

Edit: Perhaps I wasn't clear: Datatables = good, datasets = evil. If you are using ADO.Net then you can use both of these technologies (EF, linq2sql, dapper, nhibernate, orm of the month) as they generally sit on top of ado.net. The advantage you get is that you can update your model far easier as your schema changes provided you have the right level of abstraction by levering code generation.

The ado.net adapter uses providers that expose the type info of the database, for instance by default it uses a sql server provider, you can also plug in - for instance - devart postgress provider and still get access to the type info which will then allow you to as above use your orm of choice (almost painlessly - there are a few quirks) - i believe Microsoft also provide an oracle provider. The ENTIRE purpose of this is to abstract away from the database implementation where possible.

Count number of occurrences of a pattern in a file (even on same line)

Try this:

grep "string to search for" FileNameToSearch | cut -d ":" -f 4 | sort -n | uniq -c

Sample:

grep "SMTP connect from unknown" maillog | cut -d ":" -f 4 | sort -n | uniq -c
  6  SMTP connect from unknown [188.190.118.90]
 54  SMTP connect from unknown [62.193.131.114]
  3  SMTP connect from unknown [91.222.51.253]

increase the java heap size permanently?

This worked for me:

export _JAVA_OPTIONS="-Xmx1g"

It's important that you have no spaces because for me it did not work. I would suggest just copying and pasting. Then I ran:

java -XshowSettings:vm 

and it will tell you:

Picked up _JAVA_OPTIONS: -Xmx1g

MVC which submit button has been pressed

Name both your submit buttons the same

<input name="submit" type="submit" id="submit" value="Save" />
<input name="submit" type="submit" id="process" value="Process" />

Then in your controller get the value of submit. Only the button clicked will pass its value.

public ActionResult Index(string submit)
{
    Response.Write(submit);
    return View();
}

You can of course assess that value to perform different operations with a switch block.

public ActionResult Index(string submit)
{
    switch (submit)
    {
        case "Save":
            // Do something
            break;
        case "Process":
            // Do something
            break;
        default:
            throw new Exception();
            break;
    }

    return View();
}

How to use apply a custom drawable to RadioButton?

full solution here:

<RadioGroup
    android:id="@+id/radioGroup1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <RadioButton
        android:id="@+id/radio0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/oragne_toggle_btn"
        android:checked="true"
        android:text="RadioButton" />

    <RadioButton
        android:id="@+id/radio1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/oragne_toggle_btn"
        android:layout_marginTop="20dp"
        android:text="RadioButton" />

    <RadioButton
        android:id="@+id/radio2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/oragne_toggle_btn"
        android:layout_marginTop="20dp"
        android:text="RadioButton" />
</RadioGroup>

selector XML

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/orange_btn_selected" android:state_checked="true"/>
<item android:drawable="@drawable/orange_btn_unselected"    android:state_checked="false"/>

 </selector>

Format XML string to print friendly XML string

Check the following link: How to pretty-print XML (Unfortunately, the link now returns 404 :()

The method in the link takes an XML string as an argument and returns a well-formed (indented) XML string.

I just copied the sample code from the link to make this answer more comprehensive and convenient.

public static String PrettyPrint(String XML)
{
    String Result = "";

    MemoryStream MS = new MemoryStream();
    XmlTextWriter W = new XmlTextWriter(MS, Encoding.Unicode);
    XmlDocument D   = new XmlDocument();

    try
    {
        // Load the XmlDocument with the XML.
        D.LoadXml(XML);

        W.Formatting = Formatting.Indented;

        // Write the XML into a formatting XmlTextWriter
        D.WriteContentTo(W);
        W.Flush();
        MS.Flush();

        // Have to rewind the MemoryStream in order to read
        // its contents.
        MS.Position = 0;

        // Read MemoryStream contents into a StreamReader.
        StreamReader SR = new StreamReader(MS);

        // Extract the text from the StreamReader.
        String FormattedXML = SR.ReadToEnd();

        Result = FormattedXML;
    }
    catch (XmlException)
    {
    }

    MS.Close();
    W.Close();

    return Result;
}

Using Lato fonts in my css (@font-face)

Font Squirrel has a wonderful web font generator.

I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.

Getting text from td cells with jQuery

First of all, your selector is overkill. I suggest using a class or ID selector like my example below. Once you've corrected your selector, simply use jQuery's .each() to iterate through the collection:

ID Selector:

$('#mytable td').each(function() {
    var cellText = $(this).html();    
});

Class Selector:

$('.myTableClass td').each(function() {
    var cellText = $(this).html();    
});

Additional Information:

Take a look at jQuery's selector docs.

Add error bars to show standard deviation on a plot in R

In addition to @csgillespie's answer, segments is also vectorised to help with this sort of thing:

plot (x, y, ylim=c(0,6))
segments(x,y-sd,x,y+sd)
epsilon <- 0.02
segments(x-epsilon,y-sd,x+epsilon,y-sd)
segments(x-epsilon,y+sd,x+epsilon,y+sd)

enter image description here

Encode html entities in javascript

HTML Special Characters & its ESCAPE CODES

Reserved Characters must be escaped by HTML: We can use a character escape to represent any Unicode character [Ex: & - U+00026] in HTML, XHTML or XML using only ASCII characters. Numeric character references [Ex: ampersand(&) - &#38;] & Named character references [Ex: &amp;] are types of character escape used in markup.


Predefined Entities

    Original Character     XML entity replacement    XML numeric replacement  
                  <                                    &lt;                                           &#60;                    
                  >                                     &gt;                                         &#62;                    
                  "                                     &quot;                                      &#34;                    
                  &                                   &amp;                                       &#38;                    
                   '                                    &apos;                                      &#39;                    

To display HTML Tags as a normal form in web page we use <pre>, <code> tags or we can escape them. Escaping the string by replacing with any occurrence of the "&" character by the string "&amp;" and any occurrences of the ">" character by the string "&gt;". Ex: stackoverflow post

function escapeCharEntities() {
    var map = {
        "&": "&amp;",
        "<": "&lt;",
        ">": "&gt;",
        "\"": "&quot;",
        "'": "&apos;"
    };
    return map;
}

var mapkeys = '', mapvalues = '';
var html = {
    encodeRex : function () {
        return  new RegExp(mapkeys, 'g'); // "[&<>"']"
    }, 
    decodeRex : function () {
        return  new RegExp(mapvalues, 'g'); // "(&amp;|&lt;|&gt;|&quot;|&apos;)"
    },
    encodeMap : JSON.parse( JSON.stringify( escapeCharEntities () ) ), // json = {&: "&amp;", <: "&lt;", >: "&gt;", ": "&quot;", ': "&apos;"}
    decodeMap : JSON.parse( JSON.stringify( swapJsonKeyValues( escapeCharEntities () ) ) ),
    encode : function ( str ) {
        var encodeRexs = html.encodeRex();
        console.log('Encode Rex: ', encodeRexs); // /[&<>"']/gm
        return str.replace(encodeRexs, function(m) { console.log('Encode M: ', m); return html.encodeMap[m]; }); // m = < " > SpecialChars
    },
    decode : function ( str ) {
        var decodeRexs = html.decodeRex();
        console.log('Decode Rex: ', decodeRexs); // /(&amp;|&lt;|&gt;|&quot;|&apos;)/g
        return str.replace(decodeRexs, function(m) { console.log('Decode M: ', m); return html.decodeMap[m]; }); // m = &lt; &quot; &gt;
    }
};

function swapJsonKeyValues ( json ) {
    var count = Object.keys( json ).length;
    var obj = {};
    var keys = '[', val = '(', keysCount = 1;
    for(var key in json) {
        if ( json.hasOwnProperty( key ) ) {
            obj[ json[ key ] ] = key;
            keys += key;
            if( keysCount < count ) {
                val += json[ key ]+'|';
            } else {
                val += json[ key ];
            }
            keysCount++;
        }
    }
    keys += ']';    val  += ')';
    console.log( keys, ' == ', val);
    mapkeys = keys;
    mapvalues = val;
    return obj;
}

console.log('Encode: ', html.encode('<input type="password" name="password" value=""/>') ); 
console.log('Decode: ', html.decode(html.encode('<input type="password" name="password" value=""/>')) );

O/P:
Encode:  &lt;input type=&quot;password&quot; name=&quot;password&quot; value=&quot;&quot;/&gt;
Decode:  <input type="password" name="password" value=""/>

How to tackle daylight savings using TimeZone in Java

In java, DateFormatter by default uses DST,To avoid day Light saving (DST) you need to manually do a trick,
first you have to get the DST offset i.e. for how many millisecond DST applied, for ex somewhere DST is also for 45 minutes and for some places it is for 30 min
but in most cases DST is of 1 hour
you have to use Timezone object and check with the date whether it is falling under DST or not and then you have to manually add offset of DST into it. for eg:

 TimeZone tz = TimeZone.getTimeZone("EST");
 boolean isDST = tz.inDaylightTime(yourDateObj);
 if(isDST){
 int sec= tz.getDSTSavings()/1000;// for no. of seconds
 Calendar cal= Calendar.getInstance();
 cal.setTime(yourDateObj);
 cal.add(Calendar.Seconds,sec);
 System.out.println(cal.getTime());// your Date with DST neglected
  }

How do I find the size of a struct?

Contrary to what some of the other answers have said, on most systems, in the absence of a pragma or compiler option, the size of the structure will be at least 6 bytes and, on most 32-bit systems, 8 bytes. For 64-bit systems, the size could easily be 16 bytes. Alignment does come into play; always. The sizeof a single struct has to be such that an array of those sizes can be allocated and the individual members of the array are sufficiently aligned for the processor in question. Consequently, if the size of the struct was 5 as others have hypothesized, then an array of two such structures would be 10 bytes long, and the char pointer in the second array member would be aligned on an odd byte, which would (on most processors) cause a major bottleneck in the performance.

How to jQuery clone() and change id?

$('#cloneDiv').click(function(){


  // get the last DIV which ID starts with ^= "klon"
  var $div = $('div[id^="klon"]:last');

  // Read the Number from that DIV's ID (i.e: 3 from "klon3")
  // And increment that number by 1
  var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;

  // Clone it and assign the new ID (i.e: from num 4 to ID "klon4")
  var $klon = $div.clone().prop('id', 'klon'+num );

  // Finally insert $klon wherever you want
  $div.after( $klon.text('klon'+num) );

});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

How to fix "ImportError: No module named ..." error in Python?

If you have this problem when using an instaled version, when using setup.py, make sure your module is included inside packages

setup(name='Your program',
    version='0.7.0',
    description='Your desccription',
    packages=['foo', 'foo.bar'], # add `foo.bar` here

In C#, what's the difference between \n and \r\n?

They are just \r\n and \n are variants.

\r\n is used in windows

\n is used in mac and linux

Create new user in MySQL and give it full access to one database

In case the host part is omitted it defaults to the wildcard symbol %, allowing all hosts.

CREATE USER 'service-api';

GRANT ALL PRIVILEGES ON the_db.* TO 'service-api' IDENTIFIED BY 'the_password'

SELECT * FROM mysql.user;
SHOW GRANTS FOR 'service-api'

Set Culture in an ASP.Net MVC app

What is the best place is your question. The best place is inside the Controller.Initialize method. MSDN writes that it is called after the constructor and before the action method. In contrary of overriding OnActionExecuting, placing your code in the Initialize method allow you to benefit of having all custom data annotation and attribute on your classes and on your properties to be localized.

For example, my localization logic come from an class that is injected to my custom controller. I have access to this object since Initialize is called after the constructor. I can do the Thread's culture assignation and not having every error message displayed correctly.

 public BaseController(IRunningContext runningContext){/*...*/}

 protected override void Initialize(RequestContext requestContext)
 {
     base.Initialize(requestContext);
     var culture = runningContext.GetCulture();
     Thread.CurrentThread.CurrentUICulture = culture;
     Thread.CurrentThread.CurrentCulture = culture;
 }

Even if your logic is not inside a class like the example I provided, you have access to the RequestContext which allow you to have the URL and HttpContext and the RouteData which you can do basically any parsing possible.

How to copy std::string into std::vector<char>?

std::vector has a constructor that takes two iterators. You can use that:

std::string str = "hello";
std::vector<char> data(str.begin(), str.end());

If you already have a vector and want to add the characters at the end, you need a back inserter:

std::string str = "hello";
std::vector<char> data = /* ... */;
std::copy(str.begin(), str.end(), std::back_inserter(data));

How to add an element to a list?

Elements are added to list using append():

>>> data = {'list': [{'a':'1'}]}
>>> data['list'].append({'b':'2'})
>>> data
{'list': [{'a': '1'}, {'b': '2'}]}

If you want to add element to a specific place in a list (i.e. to the beginning), use insert() instead:

>>> data['list'].insert(0, {'b':'2'})
>>> data
{'list': [{'b': '2'}, {'a': '1'}]}

After doing that, you can assemble JSON again from dictionary you modified:

>>> json.dumps(data)
'{"list": [{"b": "2"}, {"a": "1"}]}'

SQL Server 2008: TOP 10 and distinct together

You could use a Common Table Expression to get the top 10 distinct ID's and then join those to the rest of your data:

;WITH TopTenIDs AS
( 
   SELECT DISTINCT TOP 10 id
   FROM dm.labs 
   ORDER BY ......
)
SELECT 
    tti.id, pl.nm, pl.val, pl.txt_val
FROM
    TopTenIDs tti
INNER JOIN
    dm.labs pl ON pl.id = tti.id
INNER JOIN 
    mas_data.patients p ON pl.id = p.id
WHERE
    pl.nm like '%LDL%'
    AND val IS NOT NULL

That should work. Mind you: if you have a "TOP x" clause, you typically also need an ORDER BY clause - if you want the TOP 10, you need to tell the system in what order that "TOP" is.

PS: why do you even join the "patients" table, if you never select any fields from it??

How do I open multiple instances of Visual Studio Code?

Select menu FileNew Window from the menu and then open the other folder in the new window.

How to style icon color, size, and shadow of Font Awesome Icons

If you are using Bootstrap at the same time, you can use:

<i class="fa fa-check-circle-o fa-5x text-success" ></i>

Otherwise:

<i class="fa fa-check-circle-o fa-5x" style="color:green"></i>

T-SQL: Export to new Excel file

Use PowerShell:

$Server = "TestServer"
$Database = "TestDatabase"
$Query = "select * from TestTable"
$FilePath = "C:\OutputFile.csv"

# This will overwrite the file if it already exists.
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath

In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.

Best way to run scheduled tasks

I'm not sure what kind of scheduled tasks you mean. If you mean stuff like "every hour, refresh foo.xml" type tasks, then use the Windows Scheduled Tasks system. (The "at" command, or via the controller.) Have it either run a console app or request a special page that kicks off the process.

Edit: I should add, this is an OK way to get your IIS app running at scheduled points too. So suppose you want to check your DB every 30 minutes and email reminders to users about some data, you can use scheduled tasks to request this page and hence get IIS processing things.

If your needs are more complex, you might consider creating a Windows Service and having it run a loop to do whatever processing you need. This also has the benefit of separating out the code for scaling or management purposes. On the downside, you need to deal with Windows services.

How to get past the login page with Wget?

Example to download with wget on server a big file link that can be obtained in your browser.

In example using Google Chrome.

Login where you need, and press download. Go to download and copy your link.

enter image description here

Then open DevTools on a page where you where login, go to Console and get your cookies, by entering document.cookie

enter image description here

Now, go to server and download your file: wget --header "Cookie: <YOUR_COOKIE_OUTPUT_FROM_CONSOLE>" <YOUR_DOWNLOAD_LINK>

enter image description here

Check if a given key already exists in a dictionary

The ways in which you can get the results are:

Which is better is dependent on 3 things:

  1. Does the dictionary 'normally has the key' or 'normally does not have the key'.
  2. Do you intend to use conditions like if...else...elseif...else?
  3. How big is dictionary?

Read More: http://paltman.com/try-except-performance-in-python-a-simple-test/

Use of try/block instead of 'in' or 'if':

try:
    my_dict_of_items[key_i_want_to_check]
except KeyError:
    # Do the operation you wanted to do for "key not present in dict".
else:
    # Do the operation you wanted to do with "key present in dict."

How do I set a path in Visual Studio?

None of the answers solved exactly my problem (the solution file I was running was trying to find xcopy to copy a dll after generation).

What solved it for me was going into menu "Project -> Properties"

Then in the window that opens choosing on the left pane: "Configuration Properties -> VC++ Directories

On the right pane under "General" choosing "Executable Directories "

And then adding:

$(SystemRoot)\system32;$(SystemRoot);$(SystemRoot)\System32\Wbem;$(SystemRoot)\System32\WindowsPowerShell\v1.0\;$(ExecutablePath)

Use dynamic variable names in JavaScript

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

In ES6 using let doesn't work:

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

However using var works

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

I hope this may be useful to some.

installing apache: no VCRUNTIME140.dll

Also, please make sure you installed the correct version of apache on your computer. For example, not install a x86 on a 64bit system. Vice versa.

Position a div container on the right side

if you don't want to use float

<div style="text-align:right; margin:0px auto 0px auto;">
<p> Hello </p>
</div>
  <div style="">
<p> Hello </p>
</div>

Android: Is it possible to display video thumbnails?

I really suggest you to use the Glide library. It's among the most efficient way to generate and display a video thumbnail for a local video file.

Just add this line to your gradle file :

compile 'com.github.bumptech.glide:glide:3.7.0'

And it will become as simple as :

String filePath = "/storage/emulated/0/Pictures/example_video.mp4";

Glide  
    .with( context )
    .load( Uri.fromFile( new File( filePath ) ) )
    .into( imageViewGifAsBitmap );

You can find more informations here : https://futurestud.io/blog/glide-displaying-gifs-and-videos

Cheers !

Why is it said that "HTTP is a stateless protocol"?

Modern HTTP is stateful. Old timey HTTP was stateless.

Before Netscape invented cookies and HTTPS in 1994 http could be considered stateless. As time progressed more and more stateful aspects were added for a myriad of reasons, including performance and security.

While HTTP 1 originally sought out to be stateless many HTTP/2 components are the very definition of stateful. HTTP/2 abandoned stateless goals.

No reasonable person can read the HTTP/2 RFC and think it is stateless. The errant "HTTP is stateless" old time dogma is false and far from the current reality of stateful HTTP.

Here's a limited, and not exhaustive list, of stateful HTTP/1 and HTTP/2 components:

  • Cookies, named "HTTP State Management Mechanism" by the RFC.
  • HTTPS, which stores keys thus state.
  • HTTP authentication requires state.
  • Web Storage.
  • HTTP caching is stateful.
  • The very purpose of the stream identifier is state. It's even in the name of the RFC section, "Stream States".
  • Header blocks, which establish stream identifiers, are stateful.
  • Frames which reference stream identifiers are stateful.
  • Header Compression, which the HTTP RFC explicitly says is stateful, is stateful.
  • Opportunistic encryption is stateful.

Section 5.1 of the HTTP/2 RFC is a great example of stateful mechanisms defined by the HTTP/2 standard.

Is it safe for web applications to consider HTTP/2 as a stateless protocol?

HTTP/2 is a stateful protocol, but that doesn't mean your HTTP/2 application can't be stateless. You can choose to not use certain stateful features for stateless HTTP/2 applications by using only a subset of HTTP/2 features.

Cookies and some other stateful mechanisms, or less obvious stateful mechanisms, are later HTTP additions. HTTP 1 is said to be stateless although in practice we use standardized stateful mechanisms, like cookies, TLS, and caching. Unlike HTTP/1, HTTP/2 defines stateful components in its standard from the very beginning. A particular HTTP/2 application can use a subset of HTTP/2 features to maintain statelessness, but the protocol itself anticipate state to be the norm, not the exception.

Existing applications, even HTTP 1 applications, needing state will break if trying to use them statelessly. It can be impossible to log into some HTTP/1.1 websites if cookies are disabled, thus breaking the application. It may not be safe to assume that a particular HTTP 1 application does not use state. This is no different for HTTP/2.

Say it with me one last time:

HTTP/2 is a stateful protocol.

Replace all particular values in a data frame

We can use data.table to get it quickly. First create df without factors,

df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)), stringsAsFactors=F)

Now you can use

setDT(df)
for (jj in 1:ncol(df)) set(df, i = which(df[[jj]]==""), j = jj, v = NA)

and you can convert it back to a data.frame

setDF(df)

If you only want to use data.frame and keep factors it's more difficult, you need to work with

levels(df$value)[levels(df$value)==""] <- NA

where value is the name of every column. You need to insert it in a loop.

Get human readable version of file size?

This solution might also appeal to you, depending on how your mind works:

from pathlib import Path    

def get_size(path = Path('.')):
    """ Gets file size, or total directory size """
    if path.is_file():
        size = path.stat().st_size
    elif path.is_dir():
        size = sum(file.stat().st_size for file in path.glob('*.*'))
    return size

def format_size(path, unit="MB"):
    """ Converts integers to common size units used in computing """
    bit_shift = {"B": 0,
            "kb": 7,
            "KB": 10,
            "mb": 17,
            "MB": 20,
            "gb": 27,
            "GB": 30,
            "TB": 40,}
    return "{:,.0f}".format(get_size(path) / float(1 << bit_shift[unit])) + " " + unit

# Tests and test results
>>> get_size("d:\\media\\bags of fun.avi")
'38 MB'
>>> get_size("d:\\media\\bags of fun.avi","KB")
'38,763 KB'
>>> get_size("d:\\media\\bags of fun.avi","kb")
'310,104 kb'

Phone number validation Android

You can use android's inbuilt Patterns:

public boolean validCellPhone(String number)
{
    return android.util.Patterns.PHONE.matcher(number).matches();
}

This pattern is intended for searching for things that look like they might be phone numbers in arbitrary text, not for validating whether something is in fact a phone number. It will miss many things that are legitimate phone numbers.

The pattern matches the following:

  • Optionally, a + sign followed immediately by one or more digits. Spaces, dots, or dashes may follow.
  • Optionally, sets of digits in parentheses, separated by spaces, dots, or dashes.
  • A string starting and ending with a digit, containing digits, spaces, dots, and/or dashes.

How do I create an abstract base class in JavaScript?

Another thing you might want to enforce is making sure your abstract class is not instantiated. You can do that by defining a function that acts as FLAG ones set as the Abstract class constructor. This will then try to construct the FLAG which will call its constructor containing exception to be thrown. Example below:

(function(){

    var FLAG_ABSTRACT = function(__class){

        throw "Error: Trying to instantiate an abstract class:"+__class
    }

    var Class = function (){

        Class.prototype.constructor = new FLAG_ABSTRACT("Class");       
    }

    //will throw exception
    var  foo = new Class();

})()

Detect all Firefox versions in JS

This script detects all versions of Firefox, for Desktop, from version 1 to 46.

It's the third time I've tried to answer this question on StackOverflow because I kept finding new ways to break my script. However, I think it's working now. It's a great exercise to learn about Firefox features and interesting to see how things have evolved. The script can be rewritten with different features, I chose ones I thought would be most useful, I would love for someone else to rewrite with other more useful features and post here, and compare results.

I placed the script in a try statement in case the user has any disabled settings in about.config. Otherwise I tested on every version of Firefox and it detects each one. I gave a brief description of what each feature is used for in the comments. I would like to do this for Webkit too but find the documentation not as good. Mozilla has easy to download previous versions and detailed releases.

_x000D_
_x000D_
// Element to display version_x000D_
var outputVersion = document.getElementById("displayFoxVersion");_x000D_
_x000D_
try {_x000D_
    // Match UserAgent string with Firefox Desktop_x000D_
    // Detect hybrid Gecko browsers and mobile_x000D_
    if (navigator.userAgent.match(/firefox/i) &&_x000D_
        !navigator.userAgent.match(/mobi|tablet|fennec|android|netscape|seamonkey|iceweasel|iceape|icecat|waterfox|gnuzilla|shadowfox|swiftfox/i)) {_x000D_
_x000D_
        // Create Element and Array to test availability  _x000D_
        var createdElement = document.createElement('div'),_x000D_
            createdArray = [],_x000D_
            firefoxVersion = "0";_x000D_
_x000D_
        // Firefox 1.0 released November 9, 2004 _x000D_
        // Check a current feature as being true, or NOT undefined _x000D_
        // AND check future features as EQUAL undefined_x000D_
        if (typeof window.alert !== "undefined" &&_x000D_
            typeof window.XPCNativeWrapper === "undefined" &&_x000D_
            typeof window.URL === "undefined") {_x000D_
            firefoxVersion = "1";_x000D_
        }_x000D_
_x000D_
        // Firefox 1.5 released October 15, 2003 _x000D_
        // XPCNativeWrapper used to create security wrapper_x000D_
        else if (typeof window.XPCNativeWrapper !== "undefined" &&_x000D_
            typeof window.globalStorage === "undefined" &&_x000D_
            typeof window.devicePixelRatio === "undefined" &&_x000D_
            typeof createdElement.style.animation === "undefined" &&_x000D_
            typeof document.querySelector === "undefined") {_x000D_
            firefoxVersion = "1.5";_x000D_
        }_x000D_
_x000D_
        // Firefox 2 released October 24, 2006_x000D_
        // globalStorage later deprecated in favor of localstorage_x000D_
        else if (typeof window.globalStorage !== "undefined" &&_x000D_
            typeof window.postMessage === "undefined") {_x000D_
            firefoxVersion = "2";_x000D_
        }_x000D_
_x000D_
        // Firefox 3 released June 17, 2008_x000D_
        // postMessage for cross window messaging_x000D_
        else if (typeof window.postMessage !== "undefined" &&_x000D_
            typeof document.querySelector === "undefined") {_x000D_
            firefoxVersion = "3";_x000D_
        }_x000D_
_x000D_
        // Firefox 3.5 released June 30, 2009_x000D_
        // querySelector returns list of the elements from document_x000D_
        else if (typeof document.querySelector !== "undefined" &&_x000D_
            typeof window.mozRequestAnimationFrame === "undefined" &&_x000D_
            typeof Reflect === "undefined") {_x000D_
            firefoxVersion = "3.5";_x000D_
        }_x000D_
_x000D_
        // Firefox 4 released March 22, 2011_x000D_
        // window.URL is Gecko, Webkit is window.webkitURL, manages object URLs_x000D_
        else if (typeof window.URL !== "undefined" &&_x000D_
            typeof createdElement.style.MozAnimation === "undefined") {_x000D_
            firefoxVersion = "4";_x000D_
        }_x000D_
_x000D_
        // After April 2011 releases every six weeks on Tuesday_x000D_
_x000D_
        // Firefox 5 released June 21, 2011_x000D_
        // style.MozAnimation for CSS animation, renamed to style.animation_x000D_
        else if (typeof createdElement.style.MozAnimation !== "undefined" &&_x000D_
            typeof WeakMap === "undefined") {_x000D_
            firefoxVersion = "5";_x000D_
        }_x000D_
_x000D_
        // Firefox 6 released August 16, 2011_x000D_
        // WeakMap collects key value pairs weakly referenced_x000D_
        else if (typeof WeakMap !== "undefined" &&_x000D_
            typeof createdElement.style.textOverflow === "undefined") {_x000D_
            firefoxVersion = "6";_x000D_
        }_x000D_
_x000D_
        // Firefox 7 released September 27, 2011_x000D_
        // textOverflow manages overflowed non displayed content_x000D_
        else if (typeof createdElement.style.textOverflow !== "undefined" &&_x000D_
            typeof createdElement.insertAdjacentHTML === "undefined") {_x000D_
            firefoxVersion = "7";_x000D_
        }_x000D_
_x000D_
        // Firefox 8 released November 8, 2011_x000D_
        // insertAdjacentHTML parses as HTML and inserts into specified position_x000D_
        // faster than direct innerHTML manipulation and_x000D_
        // appends without affecting other elements under the same parent_x000D_
        else if (typeof createdElement.insertAdjacentHTML !== "undefined" &&_x000D_
            typeof navigator.doNotTrack === "undefined") {_x000D_
            firefoxVersion = "8";_x000D_
        }_x000D_
_x000D_
        // Firefox 9 released December 20, 2011_x000D_
        // mozIndexedDB dropped ver 16, renamed window.indexedDB _x000D_
        // IndexDB improved functionality than localstorage_x000D_
        else if (typeof window.mozIndexedDB !== "undefined" &&_x000D_
            typeof document.mozFullScreenEnabled === "undefined") {_x000D_
            firefoxVersion = "9";_x000D_
        }_x000D_
_x000D_
        // Firefox 10 released January 31, 2012_x000D_
        // mozFullScreenEnabled reports if full-screen mode is available_x000D_
        else if (typeof document.mozFullScreenEnabled !== "undefined" &&_x000D_
            typeof window.mozCancelAnimationFrame === "undefined" &&_x000D_
            typeof Reflect === "undefined") {_x000D_
            firefoxVersion = "10";_x000D_
        }_x000D_
_x000D_
        // Firefox 11 released March 13, 2012_x000D_
        // mozCancelAnimationFrame prior to Firefox 23 prefixed with moz_x000D_
        // Cancels an animation frame request_x000D_
        else if (typeof window.mozCancelAnimationFrame !== "undefined" &&_x000D_
            typeof createdElement.style.MozTextAlignLast === "undefined") {_x000D_
            firefoxVersion = "11";_x000D_
        }_x000D_
_x000D_
        // Firefox 12 released April 24, 2012_x000D_
        // MozTextAlignLast how the last line is aligned_x000D_
        else if (typeof createdElement.style.MozTextAlignLast !== "undefined" &&_x000D_
            typeof createdElement.style.MozOpacity !== "undefined") {_x000D_
            firefoxVersion = "12";_x000D_
        }_x000D_
_x000D_
        // Firefox 13 released June 5, 2012_x000D_
        // MozOpacity dropped from this version_x000D_
        else if (typeof createdElement.style.MozOpacity === "undefined" &&_x000D_
            typeof window.globalStorage !== "undefined") {_x000D_
            firefoxVersion = "13";_x000D_
        }_x000D_
_x000D_
        // Firefox 14 released June 26, 2012_x000D_
        // globalStorage dropped from this version_x000D_
        else if (typeof window.globalStorage === "undefined" &&_x000D_
            typeof createdElement.style.borderImage === "undefined" &&_x000D_
            typeof document.querySelector !== "undefined") {_x000D_
            firefoxVersion = "14";_x000D_
        }_x000D_
_x000D_
        // Firefox 15 released August 28, 2012_x000D_
        // borderImage allows drawing an image on the borders of elements_x000D_
        else if (typeof createdElement.style.borderImage !== "undefined" &&_x000D_
            typeof createdElement.style.animation === "undefined") {_x000D_
            firefoxVersion = "15";_x000D_
        }_x000D_
_x000D_
        // Firefox 16 released October 9, 2012_x000D_
        // animation was MozAnimation_x000D_
        else if (typeof createdElement.style.animation !== "undefined" &&_x000D_
            typeof createdElement.style.iterator === "undefined" &&_x000D_
            typeof Math.hypot === "undefined") {_x000D_
            firefoxVersion = "16";_x000D_
        }_x000D_
_x000D_
        // Firefox 17 released November 20, 2012_x000D_
        // version 27 drops iterator and renames italic_x000D_
        // Used to iterate over enumerable properties of an object_x000D_
        else if (typeof createdElement.style.iterator !== "undefined" &&_x000D_
            typeof window.devicePixelRatio === "undefined") {_x000D_
            firefoxVersion = "17";_x000D_
        }_x000D_
_x000D_
        // Firefox 18 released January 8, 2013_x000D_
        // devicePixelRatio returns ratio of one vertical pixel between devices_x000D_
        else if (typeof window.devicePixelRatio !== "undefined" &&_x000D_
            typeof window.getInterface === "undefined" &&_x000D_
            typeof createdElement.style.mixBlendMode === "undefined") {_x000D_
            firefoxVersion = "18";_x000D_
        }_x000D_
_x000D_
        // Firefox 19 released February 19, 2013_x000D_
        // getInterface dropped and renamed in version 32_x000D_
        // Retrieves specified interface pointers_x000D_
        else if (typeof window.getInterface !== "undefined" &&_x000D_
            typeof Math.imul === "undefined") {_x000D_
            firefoxVersion = "19";_x000D_
        }_x000D_
_x000D_
        // Firefox 20 released April 2, 2013_x000D_
        // Math.imul provides fast 32 bit integer multiplication_x000D_
        else if (typeof Math.imul !== "undefined" &&_x000D_
            typeof window.crypto.getRandomValues === "undefined") {_x000D_
            firefoxVersion = "20";_x000D_
        }_x000D_
_x000D_
        // Firefox 21 released May 14, 2013_x000D_
        // getRandomValues lets you get cryptographically random values_x000D_
        else if (typeof window.crypto.getRandomValues !== "undefined" &&_x000D_
            typeof createdElement.style.flex === "undefined") {_x000D_
            firefoxVersion = "21";_x000D_
        }_x000D_
_x000D_
        // Firefox 22 released June 25, 2013_x000D_
        // flex can alter dimensions to fill available space_x000D_
        else if (typeof createdElement.style.flex !== "undefined" &&_x000D_
            typeof window.cancelAnimationFrame === "undefined") {_x000D_
            firefoxVersion = "22";_x000D_
        }_x000D_
_x000D_
        // Firefox 23 released August 6, 2013_x000D_
        // cancelAnimationFrame was mozCancelAnimationFrame_x000D_
        else if (typeof window.cancelAnimationFrame !== "undefined" &&_x000D_
            typeof document.loadBindingDocument !== "undefined" &&_x000D_
            typeof Math.trunc === "undefined") {_x000D_
            firefoxVersion = "23";_x000D_
        }_x000D_
_x000D_
        // Firefox 24 released September 17, 2013_x000D_
        // loadBindingDocument dropped_x000D_
        // loadBindingDocument reintroduced in 25 then dropped again in 26 _x000D_
        else if (typeof document.loadBindingDocument === "undefined" &&_x000D_
            typeof Math.trunc === "undefined") {_x000D_
            firefoxVersion = "24";_x000D_
        }_x000D_
_x000D_
        // Firefox 25 released October 29, 2013_x000D_
        // Math.trunc returns number removing fractional digits_x000D_
        else if (typeof Math.trunc !== "undefined" &&_x000D_
            typeof document.loadBindingDocument !== "undefined") {_x000D_
            firefoxVersion = "25";_x000D_
        }_x000D_
_x000D_
        // Firefox 26 released December 10, 2013_x000D_
        // loadBindingDocument dropped_x000D_
        else if (typeof Math.trunc !== "undefined" &&_x000D_
            typeof Math.hypot === "undefined") {_x000D_
            firefoxVersion = "26";_x000D_
        }_x000D_
_x000D_
        // Firefox 27 released February 4, 2014_x000D_
        // Math.hypot returns square root of the sum of squares_x000D_
        else if (typeof Math.hypot !== "undefined" &&_x000D_
            typeof createdArray.entries === "undefined") {_x000D_
            firefoxVersion = "27";_x000D_
        }_x000D_
_x000D_
        // Firefox 28 released March 18, 2014_x000D_
        // entries returns key value pairs for arrays_x000D_
        else if (typeof createdArray.entries !== "undefined" &&_x000D_
            typeof createdElement.style.boxSizing === "undefined") {_x000D_
            firefoxVersion = "28";_x000D_
        }_x000D_
_x000D_
        // Firefox 29 released April 29, 2014_x000D_
        // boxSizing alters CSS box model, calculates width and height of elements_x000D_
        else if (typeof createdElement.style.boxSizing != "undefined" &&_x000D_
            typeof createdElement.style.backgroundBlendMode === "undefined") {_x000D_
            firefoxVersion = "29";_x000D_
        }_x000D_
_x000D_
        // Firefox 30 released June 10, 2014_x000D_
        // backgroundBlendMode blends elements background images_x000D_
        else if (typeof createdElement.style.backgroundBlendMode !== "undefined" &&_x000D_
            typeof createdElement.style.paintOrder === "undefined") {_x000D_
            firefoxVersion = "30";_x000D_
        }_x000D_
_x000D_
        // Firefox 31 released July 22, 2014_x000D_
        // paintOrder specifies the order fill, stroke, markers of shape or element_x000D_
        else if (typeof createdElement.style.paintOrder !== "undefined" &&_x000D_
            typeof createdElement.style.mixBlendMode === "undefined") {_x000D_
            firefoxVersion = "31";_x000D_
        }_x000D_
_x000D_
        // Firefox 32 released September 2, 2014_x000D_
        // mixBlendMode how an element should blend _x000D_
        else if (typeof createdElement.style.mixBlendMode !== "undefined" &&_x000D_
            typeof Number.toInteger !== "undefined") {_x000D_
            firefoxVersion = "32";_x000D_
        }_x000D_
_x000D_
        // Firefox 33 released October 14, 2014_x000D_
        // numberToIntger dropped, used to convert values to integer_x000D_
        else if (typeof Number.toInteger === "undefined" &&_x000D_
            typeof createdElement.style.fontFeatureSettings === "undefined") {_x000D_
            firefoxVersion = "33";_x000D_
        }_x000D_
_x000D_
        // Firefox 34 released December 1, 2014_x000D_
        // fontFeatureSettings control over advanced typographic features_x000D_
        else if (typeof createdElement.style.fontFeatureSettings !== "undefined" &&_x000D_
            typeof navigator.mozIsLocallyAvailable !== "undefined") {_x000D_
            firefoxVersion = "34";_x000D_
        }_x000D_
_x000D_
        // Firefox 35 released January 13, 2015_x000D_
        // mozIsLocallyAvailable dropped_x000D_
        else if (typeof navigator.mozIsLocallyAvailable === "undefined" &&_x000D_
            typeof createdElement.style.MozWindowDragging === "undefined") {_x000D_
            firefoxVersion = "35";_x000D_
        }_x000D_
_x000D_
        // Firefox 36 released February 24, 2015_x000D_
        // quote returns a copy of the string_x000D_
        else if (typeof String.quote !== "undefined" &&_x000D_
            typeof createdElement.style.MozWindowDragging !== "undefined") {_x000D_
            firefoxVersion = "36";_x000D_
        }_x000D_
_x000D_
        // Firefox 37 released March 31, 2015_x000D_
        // quote quickly dropped_x000D_
        else if (typeof String.quote === "undefined" &&_x000D_
            typeof createdElement.style.rubyPosition === "undefined") {_x000D_
            firefoxVersion = "37";_x000D_
        }_x000D_
_x000D_
        // Firefox 38 released May 12, 2015_x000D_
        // rubyPosition defines position of a ruby element relative to its base element_x000D_
        else if (typeof createdElement.style.rubyPosition !== "undefined" &&_x000D_
            typeof window.Headers === "undefined") {_x000D_
            firefoxVersion = "38";_x000D_
        }_x000D_
_x000D_
        // Firefox 39 released July 2, 2015_x000D_
        // Headers allows us to create our own headers objects _x000D_
        else if (typeof window.Headers !== "undefined" &&_x000D_
            typeof Symbol.match === "undefined") {_x000D_
            firefoxVersion = "39";_x000D_
        }_x000D_
_x000D_
        // Firefox 40 released August 11, 2015_x000D_
        // match matches a regular expression against a string_x000D_
        else if (typeof Symbol.match !== "undefined" &&_x000D_
            typeof Symbol.species === "undefined") {_x000D_
            firefoxVersion = "40";_x000D_
        }_x000D_
_x000D_
        // Firefox 41 released September 22, 2015_x000D_
        // species allows subclasses to over ride the default constructor_x000D_
        else if (typeof Symbol.species !== "undefined" &&_x000D_
            typeof Reflect === "undefined") {_x000D_
            firefoxVersion = "41";_x000D_
        }_x000D_
_x000D_
        // Firefox 42 released November 3, 2015_x000D_
        // mozRequestAnimationFrame and mozFullScreenEnabled dropped_x000D_
        // Reflect offers methods for interceptable JavaScript operations_x000D_
        else if (typeof Reflect !== "undefined" &&_x000D_
            typeof window.screen.orientation === "undefined") {_x000D_
            firefoxVersion = "42";_x000D_
        }_x000D_
_x000D_
        // Firefox 43 released December 15, 2015_x000D_
        // orientation is mozOrientation in B2G and Android_x000D_
        else if (typeof window.screen.orientation !== "undefined" &&_x000D_
            typeof document.charset === "undefined") {_x000D_
            firefoxVersion = "43";_x000D_
        }_x000D_
_x000D_
        // Firefox 44 released January 26, 2016_x000D_
        // charset is for legacy, use document.characterSet_x000D_
        else if (typeof document.charset !== "undefined" &&_x000D_
            typeof window.onstorage === "undefined") {_x000D_
            firefoxVersion = "44";_x000D_
        }_x000D_
_x000D_
        // Firefox 45 released March 8, 2016_x000D_
        // onstorage contains an event handler that runs when the storage event fires_x000D_
        else if (typeof window.onstorage !== "undefined" &&_x000D_
            typeof window.onabsolutedeviceorientation === "undefined") {_x000D_
            firefoxVersion = "45";_x000D_
        }_x000D_
_x000D_
        // Firefox 46 - beta_x000D_
        // onabsolutedeviceorientation_x000D_
        else if (typeof window.onabsolutedeviceorientation !== "undefined") {_x000D_
            firefoxVersion = "46 or above";_x000D_
        }_x000D_
_x000D_
        // Else could not verify_x000D_
        else {_x000D_
            outputVersion.innerHTML = "Could not verify Mozilla Firefox";_x000D_
        }_x000D_
_x000D_
        // Display Firefox version_x000D_
        outputVersion.innerHTML = "Verified as Mozilla Firefox " + firefoxVersion;_x000D_
_x000D_
        // Else not detected_x000D_
    } else {_x000D_
        outputVersion.innerHTML = "Mozilla Firefox not detected";_x000D_
    }_x000D_
} catch (e) {_x000D_
    // Statement to handle exceptions_x000D_
    outputVersion.innerHTML = "An error occured. This could be because the default settings in Firefox have changed. Check about.config ";_x000D_
}
_x000D_
<div id="displayFoxVersion"></div>
_x000D_
_x000D_
_x000D_

Converting HTML element to string in JavaScript / JQuery

(document.body.outerHTML).constructor will return String. (take off .constructor and that's your string)

That aughta do it :)

Getting the parameters of a running JVM

I am adding this new answer because as per JDK8 documentation jcmd is suggested approach now.

It is suggested to use the latest utility, jcmd instead of the previous jstack, jinfo, and jmap utilities for enhanced diagnostics and reduced performance overhead.

Below are commands to get your properties/flags you want.

jcmd pid VM.system_properties
jcmd pid VM.flags

We need pid, for this use jcmd -l, like below

username@users-Air:~/javacode$ jcmd -l 
11441 Test 
6294 Test 
29197 jdk.jcmd/sun.tools.jcmd.JCmd -l 

Now time to use these pids to get properties/flags you want

Command: jcmd 11441 VM.system_properties

11441:
#Tue Oct 17 12:44:50 IST 2017
gopherProxySet=false
awt.toolkit=sun.lwawt.macosx.LWCToolkit
file.encoding.pkg=sun.io
java.specification.version=9
sun.cpu.isalist=
sun.jnu.encoding=UTF-8
java.class.path=.
java.vm.vendor=Oracle Corporation
sun.arch.data.model=64
java.vendor.url=http\://java.oracle.com/
user.timezone=Asia/Kolkata
java.vm.specification.version=9
os.name=Mac OS X
sun.java.launcher=SUN_STANDARD
user.country=US
sun.boot.library.path=/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/lib
sun.java.command=Test
http.nonProxyHosts=local|*.local|169.254/16|*.169.254/16
jdk.debug=release
sun.cpu.endian=little
user.home=/Users/XXXX
user.language=en
java.specification.vendor=Oracle Corporation
java.home=/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
file.separator=/
java.vm.compressedOopsMode=Zero based
line.separator=\n
java.specification.name=Java Platform API Specification
java.vm.specification.vendor=Oracle Corporation
java.awt.graphicsenv=sun.awt.CGraphicsEnvironment
sun.management.compiler=HotSpot 64-Bit Tiered Compilers
ftp.nonProxyHosts=local|*.local|169.254/16|*.169.254/16
java.runtime.version=9+181
user.name=XXXX
path.separator=\:
os.version=10.12.6
java.runtime.name=Java(TM) SE Runtime Environment
file.encoding=UTF-8
java.vm.name=Java HotSpot(TM) 64-Bit Server VM
java.vendor.url.bug=http\://bugreport.java.com/bugreport/
java.io.tmpdir=/var/folders/dm/gd6lc90d0hg220lzw_m7krr00000gn/T/
java.version=9
user.dir=/Users/XXXX/javacode
os.arch=x86_64
java.vm.specification.name=Java Virtual Machine Specification
java.awt.printerjob=sun.lwawt.macosx.CPrinterJob
sun.os.patch.level=unknown
MyParam=2
java.library.path=/Users/XXXX/Library/Java/Extensions\:/Library/Java/Extensions\:/Network/Library/Java/Extensions\:/System/Library/Java/Extensions\:/usr/lib/java\:.
java.vm.info=mixed mode
java.vendor=Oracle Corporation
java.vm.version=9+181
sun.io.unicode.encoding=UnicodeBig
java.class.version=53.0
socksNonProxyHosts=local|*.local|169.254/16|*.169.254/16

Command : jcmd 11441 VM.flags output:

11441:
-XX:CICompilerCount=3 -XX:ConcGCThreads=1 -XX:G1ConcRefinementThreads=4 -XX:G1HeapRegionSize=1048576 -XX:InitialHeapSize=67108864 -XX:MarkStackSize=4194304 -XX:MaxHeapSize=1073741824 -XX:MaxNewSize=643825664 -XX:MinHeapDeltaBytes=1048576 -XX:NonNMethodCodeHeapSize=5830092 -XX:NonProfiledCodeHeapSize=122914074 -XX:ProfiledCodeHeapSize=122914074 -XX:ReservedCodeCacheSize=251658240 -XX:+SegmentedCodeCache -XX:-UseAOT -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseFastUnorderedTimeStamps -XX:+UseG1GC 

For more instructions of usages of jcmd, see my blog post

Question mark and colon in statement. What does it mean?

It's a ternary operator, or the short form for if..else.

condition ? value if true : value if false

See Microsoft Docs | ?: operator (C# reference).

sorting dictionary python 3

A modern and fast solution, for Python 3.7. May also work in some interpreters of Python 3.6.

TLDR

To sort a dictionary by keys use:

sorted_dict = {k: disordered[k] for k in sorted(disordered)}

Almost three times faster than the accepted answer; probably more when you include imports.

Comment on the accepted answer

The example in the accepted answer instead of iterating over the keys only - with key parameter of sorted() or the default behaviour of dict iteration - iterates over tuples (key, value), which suprisingly turns out to be much slower than comparing the keys only and accessing dictionary elements in a list comprehension.

How to sort by key in Python 3.7

The big change in Python 3.7 is that the dictionaries are now ordered by default.

  • You can generate sorted dict using dict comprehensions.
  • Using OrderedDict might still be preferable for the compatibility sake.
  • Do not use sorted(d.items()) without key.

See:

disordered = {10: 'b', 3: 'a', 5: 'c'}

# sort keys, then get values from original - fast
sorted_dict = {k: disordered[k] for k in sorted(disordered)}

# key = itemgetter - slower
from operator import itemgetter
key = itemgetter(0)
sorted_dict = {k: v for k, v in sorted(disordered.items(), key=key)}

# key = lambda - the slowest
key = lambda item: item[0]
sorted_dict = {k: v for k in sorted(disordered.items(), key=key)} 

Timing results:

Best for {k: d[k] for k in sorted(d)}: 7.507327548999456
Best for {k: v for k, v in sorted(d.items(), key=key_getter)}: 12.031082626002899
Best for {k: v for k, v in sorted(d.items(), key=key_lambda)}: 14.22885995300021

Best for dict(sorted(d.items(), key=key_getter)): 11.209122000000207
Best for dict(sorted(d.items(), key=key_lambda)): 13.289728325995384
Best for dict(sorted(d.items())): 14.231471302999125

Best for OrderedDict(sorted(d.items(), key=key_getter)): 16.609151654003654
Best for OrderedDict(sorted(d.items(), key=key_lambda)): 18.52622927199991
Best for OrderedDict(sorted(d.items())): 19.436101284998585

Testing code:

from timeit import repeat

setup_code = """
from operator import itemgetter
from collections import OrderedDict
import random
random.seed(0)
d = {i: chr(i) for i in [random.randint(0, 120) for repeat in range(120)]}
key_getter = itemgetter(0)
key_lambda = lambda item: item[0]
"""

cases = [
    # fast
    '{k: d[k] for k in sorted(d)}',
    '{k: v for k, v in sorted(d.items(), key=key_getter)}',
    '{k: v for k, v in sorted(d.items(), key=key_lambda)}',
    # slower
    'dict(sorted(d.items(), key=key_getter))',
    'dict(sorted(d.items(), key=key_lambda))',
    'dict(sorted(d.items()))',
    # the slowest 
    'OrderedDict(sorted(d.items(), key=key_getter))',
    'OrderedDict(sorted(d.items(), key=key_lambda))',
    'OrderedDict(sorted(d.items()))',
]

for code in cases:
    times = repeat(code, setup=setup_code, repeat=3)
    print(f"Best for {code}: {min(times)}")

Brackets.io: Is there a way to auto indent / format <html>

I've been playing around with the preferences and added the following to my brackets.json file (access in Menu Bar: Debug: "Open Preferences File").

"closeTags": { "dontCloseTags": ["br", "hr", "img", "input", "link", "meta", "area", "base", "col", "command", "embed", "keygen", "param", "source", "track", "wbr"], "indentTags": ["ul", "ol", "div", "section", "table", "tr"], }

  • dontCloseTags are tags such as <br> which shouldn't be closed.
  • indentTags are tags that you want to automatically create a new indented line - add more as needed!
  • (any tags that aren't in above arrays will self-close on the same line)

What is char ** in C?

It is a pointer to a pointer, so yes, in a way it's a 2D character array. In the same way that a char* could indicate an array of chars, a char** could indicate that it points to and array of char*s.

How To Make Circle Custom Progress Bar in Android

Try this piece of code to create circular progress bar(pie chart). pass it integer value to draw how many percent of filling area. :)

private void circularImageBar(ImageView iv2, int i) {

    Bitmap b = Bitmap.createBitmap(300, 300,Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(b); 
    Paint paint = new Paint();

        paint.setColor(Color.parseColor("#c4c4c4"));
        paint.setStrokeWidth(10);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        canvas.drawCircle(150, 150, 140, paint);
        paint.setColor(Color.parseColor("#FFDB4C"));
        paint.setStrokeWidth(10);   
        paint.setStyle(Paint.Style.FILL);
        final RectF oval = new RectF();
        paint.setStyle(Paint.Style.STROKE);
        oval.set(10,10,290,290);
        canvas.drawArc(oval, 270, ((i*360)/100), false, paint);
        paint.setStrokeWidth(0);    
        paint.setTextAlign(Align.CENTER);
        paint.setColor(Color.parseColor("#8E8E93")); 
        paint.setTextSize(140);
        canvas.drawText(""+i, 150, 150+(paint.getTextSize()/3), paint); 
        iv2.setImageBitmap(b);
}

Xcode/Simulator: How to run older iOS version?

If you have iAds in your binary you will not be able to run it on anything before iOS 4.0 and it will be rejected if you try and submit a binary like this.

You can still run the simulator from 3.2 onwards after upgrading.

In the iPhone Simulator try selecting Hardware -> Version -> 3.2

Sass nth-child nesting

I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child parameters will only make it more complicated. As for the background color I'd just set that to a variable.

Here goes what I came up with before I realized trying to be too clever might be a bad thing.

#romtest {
 $bg: #e5e5e5;
 .detailed {
    th {
      &:nth-child(-2n+6) {
        background-color: $bg;
      }
    }
    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        background-color: $bg;
      }
      &.last {
        &:nth-child(-2n+4){
          background-color: $bg;
        }
      }
    }
  }
}

and here is a quick demo: http://codepen.io/anon/pen/BEImD

----EDIT----

Here's another approach to avoid retyping background-color:

#romtest {
  %highlight {
    background-color: #e5e5e5; 
  }
  .detailed {
    th {
      &:nth-child(-2n+6) {
        @extend %highlight;
      }
    }

    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        @extend %highlight;
      }
      &.last {
        &:nth-child(-2n+4){
          @extend %highlight;
        }
      }
    }
  }
}

Youtube - downloading a playlist - youtube-dl

Download YouTube playlist videos in separate directory indexed by video order in a playlist

$ youtube-dl -o '%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s'  https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re

Download all playlists of YouTube channel/user keeping each playlist in separate directory:

$ youtube-dl -o '%(uploader)s/%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s' https://www.youtube.com/user/TheLinuxFoundation/playlists

Video Selection:

youtube-dl is a command-line program to download videos from YouTube.com and a few more sites. It requires the Python interpreter, version 2.6, 2.7, or 3.2+, and it is not platform specific. It should work on your Unix box, on Windows or on macOS. It is released to the public domain, which means you can modify it, redistribute it or use it however you like.

$ youtube-dl [OPTIONS] URL [URL...]
--playlist-start NUMBER          Playlist video to start at (default is 1)

--playlist-end NUMBER            Playlist video to end at (default is last)

--playlist-items ITEM_SPEC       Playlist video items to download. Specify
                                 indices of the videos in the playlist
                                 separated by commas like: "--playlist-items
                                 1,2,5,8" if you want to download videos
                                 indexed 1, 2, 5, 8 in the playlist. You can
                                 specify range: "--playlist-items
                                 1-3,7,10-13", it will download the videos
                                 at index 1, 2, 3, 7, 10, 11, 12 and 13.

How to git ignore subfolders / subdirectories?

Seems this page still shows up on the top of Google search after so many years...

Modern versions of Git support nesting .gitignore files within a single repo. Just place a .gitignore file in the subdirectory that you want ignored. Use a single asterisk to match everything in that directory:

echo "*" > /path/to/bin/Debug/.gitignore
echo "*" > /path/to/bin/Release/.gitignore

If you've made previous commits, remember to remove previously tracked files:

git rm -rf /path/to/bin/Debug
git rm -rf /path/to/bin/Release

You can confirm it by doing git status to show you all the files removed from tracking.

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

If you already have nodejs installed (check with which nodejs) and don't want to install another package, you can, as root:

update-alternatives --install /usr/bin/node node /usr/bin/nodejs 99

How to convert strings into integers in Python?

You can do something like this:

T1 = (('13', '17', '18', '21', '32'),  
     ('07', '11', '13', '14', '28'),  
     ('01', '05', '06', '08', '15', '16'))  
new_list = list(list(int(a) for a in b if a.isdigit()) for b in T1)  
print(new_list)  

"Items collection must be empty before using ItemsSource."

Me too on a different scenario.

<ComboBox Cursor="Hand" DataContext="{Binding}"  
              FontSize="16" Height="27" ItemsSource="{Binding}" 
              Name="cbxDamnCombo" SelectedIndex="0" SelectedValuePath="MemberId">

        <DataTemplate>
            <TextBlock DataContext="{Binding}">
                <TextBlock.Text>
                  <MultiBinding StringFormat="{}{0} / {1}">
                    <Binding Path="MemberName"/>
                    <Binding Path="Phone"/>
                  </MultiBinding>
                </TextBlock.Text>
            </TextBlock>
        </DataTemplate>

</ComboBox>

Now when you complete with the missing tag Control.ItemTemplate, everything gets to normal:

<ComboBox Cursor="Hand" DataContext="{Binding}"  
              FontSize="16" Height="27" ItemsSource="{Binding}" 
              Name="cbxDamnCombo" SelectedIndex="0" SelectedValuePath="MemberId">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock DataContext="{Binding}">
                <TextBlock.Text>
                  <MultiBinding StringFormat="{}{0} / {1}">
                    <Binding Path="MemberName"/>
                    <Binding Path="Phone"/>
                  </MultiBinding>
                </TextBlock.Text>
            </TextBlock>
        </DataTemplate>
    <ComboBox.ItemTemplate>
</ComboBox>

React Native version mismatch

In my case (NOT using expo & Android build)

package.json

"dependencies": {
    "react": "16.3.1",
    "react-native": "0.55.2"
}

And app.json

{
  "sdkVersion": "27"
}

resolved the issue

stopPropagation vs. stopImmediatePropagation

event.stopPropagation() allows other handlers on the same element to be executed, while event.stopImmediatePropagation() prevents every event from running. For example, see below jQuery code block.

$("p").click(function(event)
{ event.stopImmediatePropagation();
});
$("p").click(function(event)
{ // This function won't be executed 
$(this).css("color", "#fff7e3");
});

If event.stopPropagation was used in previous example, then the next click event on p element which changes the css will fire, but in case event.stopImmediatePropagation(), the next p click event will not fire.

how to inherit Constructor from super class to sub class

Default constructors -- public constructors with out arguments (either declared or implied) -- are inherited by default. You can try the following code for an example of this:

public class CtorTest {
    public static void main(String[] args) {
        final Sub sub = new Sub();
        System.err.println("Finished.");
    }

    private static class Base {
        public Base() {
            System.err.println("In Base ctor");
        }
    }

    private static class Sub extends Base {
        public Sub() {
            System.err.println("In Sub ctor");
        }
    }
}

If you want to explicitly call a constructor from a super class, you need to do something like this:

public class Ctor2Test {
    public static void main(String[] args) {
        final Sub sub = new Sub();
        System.err.println("Finished.");
    }

    private static class Base {
        public Base() {
            System.err.println("In Base ctor");
        }

        public Base(final String toPrint) {
            System.err.println("In Base ctor.  To Print: " + toPrint);
        }
    }

    private static class Sub extends Base {
        public Sub() {
            super("Hello World!");
            System.err.println("In Sub ctor");
        }
    }
}

The only caveat is that the super() call must come as the first line of your constructor, else the compiler will get mad at you.

Google Maps API v3: InfoWindow not sizing correctly

I know that lots of other people have found solutions that worked for their particular case, but since none of them worked for my particular case, I thought this might be helpful to someone else.

Some details:

I'm using google maps API v3 on a project where inline CSS is something we really, really want to avoid. My infowindows were working for everything except for IE11, where the width was not calculated correctly. This resulted in div overflows, which triggered scrollbars.

I had to do three things:

  1. Remove all display: inline-block style rules from anything inside of the infowindow content (I replaced with display: block) - I got the idea to try this from a thread (which I can't find anymore) where someone was having the same problem with IE6.

  2. Pass the content as a DOM node instead of as a string. I am using jQuery, so I could do this by replacing: infowindow.setContent(infoWindowDiv.html()); with infowindow.setContent($(infoWindowDiv.html())[0]); This turned out to be easiest for me, but there are lots of other ways to get the same result.

  3. Use the "setMaxWidth" hack - set the MaxWidth option in the constructor - setting the option later doesn't work. If you don't really want a max width, just set it to a very large number.

I don't know why these worked, and I'm not sure if a subset of them would work. I know that none of them work for all of my use cases individually, and that 2 + 3 doesn't work. I didn't have time to test 1 + 2 or 1 + 3.