Thanks to @tgrrr for a simple solution, especially when 3rd party library is not wanted (such as React-Bootstrap). However, this solution has a problem: modal container is embedded inside react component, which leads to modal-under-background issue when outside react component (or its parent element) has position style as fixed/relative/absolute. I met this problem and came up to a new solution:
"use strict";
var React = require('react');
var ReactDOM = require('react-dom');
var SampleModal = React.createClass({
render: function() {
return (
<div className="modal fade" tabindex="-1" role="dialog">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 className="modal-title">Title</h4>
</div>
<div className="modal-body">
<p>Modal content</p>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" className="btn btn-primary">OK</button>
</div>
</div>
</div>
</div>
);
}
});
var sampleModalId = 'sample-modal-container';
var SampleApp = React.createClass({
handleShowSampleModal: function() {
var modal = React.cloneElement(<SampleModal></SampleModal>);
var modalContainer = document.createElement('div');
modalContainer.id = sampleModalId;
document.body.appendChild(modalContainer);
ReactDOM.render(modal, modalContainer, function() {
var modalObj = $('#'+sampleModalId+'>.modal');
modalObj.modal('show');
modalObj.on('hidden.bs.modal', this.handleHideSampleModal);
}.bind(this));
},
handleHideSampleModal: function() {
$('#'+sampleModalId).remove();
},
render: function(){
return (
<div>
<a href="javascript:;" onClick={this.handleShowSampleModal}>show modal</a>
</div>
)
}
});
module.exports = SampleApp;
The main idea is:
<?php if($condition) : ?>
<a href="http://yahoo.com">This will only display if $condition is true</a>
<?php endif; ?>
By request, here's elseif and else (which you can also find in the docs)
<?php if($condition) : ?>
<a href="http://yahoo.com">This will only display if $condition is true</a>
<?php elseif($anotherCondition) : ?>
more html
<?php else : ?>
even more html
<?php endif; ?>
It's that simple.
The HTML will only be displayed if the condition is satisfied.
Per the docs, the exception types you may need to catch are:
GuzzleHttp\Exception\ClientException
for 400-level errorsGuzzleHttp\Exception\ServerException
for 500-level errorsGuzzleHttp\Exception\BadResponseException
for both (it's their superclass)Code to handle such errors thus now looks something like this:
$client = new GuzzleHttp\Client;
try {
$client->get('http://google.com/nosuchpage');
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
}
I the quick start tutorial I went through the steps up until npm start
. Then i got this error. Then I deleted the node_modules
folder under angular-quickstart
and ran npm install
again. Now it works.
You should reinstall Python:
brew reinstall python
To get brew see the brew homepage.
You can rename/remove master on remote, but this will be an issue if lots of people have based their work on the remote master branch and have pulled that branch in their local repo.
That might not be the case here since everyone seems to be working on branch 'seotweaks
'.
In that case you can:
git remote --show may not work.
(Make a git remote show
to check how your remote is declared within your local repo. I will assume 'origin
')
(Regarding GitHub, house9 comments: "I had to do one additional step, click the 'Admin
' button on GitHub and set the 'Default Branch
' to something other than 'master
', then put it back afterwards")
git branch -m master master-old # rename master on local
git push origin :master # delete master on remote
git push origin master-old # create master-old on remote
git checkout -b master seotweaks # create a new local master on top of seotweaks
git push origin master # create master on remote
But again:
reset --hard
their local master to the remote/master branch they will fetch, and forget about their current master.For completeness, if you wanted to use replaceFirst, try this:
public static String cap1stChar(String userIdea)
{
String betterIdea = userIdea;
if (userIdea.length() > 0)
{
String first = userIdea.substring(0,1);
betterIdea = userIdea.replaceFirst(first, first.toUpperCase());
}
return betterIdea;
}//end cap1stChar
so, if you want to update parent component,
class ParentComponent extends React.Component {
constructor(props){
super(props);
this.state = {
page:0
}
}
handler(val){
console.log(val) // 1
}
render(){
return (
<ChildComponent onChange={this.handler} />
)
}
}
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
page:1
};
}
someMethod = (page) => {
this.setState({ page: page });
this.props.onChange(page)
}
render() {
return (
<Button
onClick={() => this.someMethod()}
> Click
</Button>
)
}
}
Here onChange is an attribute with "handler" method bound to it's instance. we passed the method handler to the Child class component, to receive via onChange property in its props argument.
The attribute onChange will be set in a props object like this:
props ={
onChange : this.handler
}
and passed to the child component
So the Child component can access the value of name in the props object like this props.onChange
Its done through the use of render props.
Now the Child component has a button “Click” with an onclick event set to call the handler method passed to it via onChnge in its props argument object. So now this.props.onChange in Child holds the output method in the Parent class Reference and credits: Bits and Pieces
Apple Docs:
- (id)initWithFrame:(CGRect)frame
collectionViewLayout:(UICollectionViewLayout *)layoutParameters
Use this method when initializing a collection view object programmatically. If you specify nil for the layout parameter, you must assign a layout object to the collectionViewLayout property before displaying the collection view onscreen. If you do not, the collection view will be unable to present any items onscreen.
This method is the designated initializer.
This method is used to initialize the UICollectionView
.
here you provide frame and a UICollectionViewLayout
object.
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
At the end, add UICollectionView
as a subview
to your view.
Now collection view is added pro grammatically. You can go on learning.
Happy learning!! Hope it helps you.
For the mathematically inclined: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
The recommended approach is to use correction factors (multiply by a suitable power of 10 so that the arithmetic happens between integers). For example, in the case of 0.1 * 0.2
, the correction factor is 10
, and you are performing the calculation:
> var x = 0.1
> var y = 0.2
> var cf = 10
> x * y
0.020000000000000004
> (x * cf) * (y * cf) / (cf * cf)
0.02
A (very quick) solution looks something like:
var _cf = (function() {
function _shift(x) {
var parts = x.toString().split('.');
return (parts.length < 2) ? 1 : Math.pow(10, parts[1].length);
}
return function() {
return Array.prototype.reduce.call(arguments, function (prev, next) { return prev === undefined || next === undefined ? undefined : Math.max(prev, _shift (next)); }, -Infinity);
};
})();
Math.a = function () {
var f = _cf.apply(null, arguments); if(f === undefined) return undefined;
function cb(x, y, i, o) { return x + f * y; }
return Array.prototype.reduce.call(arguments, cb, 0) / f;
};
Math.s = function (l,r) { var f = _cf(l,r); return (l * f - r * f) / f; };
Math.m = function () {
var f = _cf.apply(null, arguments);
function cb(x, y, i, o) { return (x*f) * (y*f) / (f * f); }
return Array.prototype.reduce.call(arguments, cb, 1);
};
Math.d = function (l,r) { var f = _cf(l,r); return (l * f) / (r * f); };
In this case:
> Math.m(0.1, 0.2)
0.02
I definitely recommend using a tested library like SinfulJS
Just throw everything you read into a MemoryStream
and get the byte array in the end. As noted, you should be reading from the underlying stream to get the raw bytes.
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
var buffer = new byte[512];
var bytesRead = default(int);
while ((bytesRead = reader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
memstream.Write(buffer, 0, bytesRead);
bytes = memstream.ToArray();
}
Or if you don't want to manage the buffers:
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
reader.BaseStream.CopyTo(memstream);
bytes = memstream.ToArray();
}
You need to use isset() to check whether value is set.
angular.module('myapp', ['myapp.filters', 'myapp.services', 'myapp.directives']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/page/:name*', {
templateUrl: function(urlattr){
return '/pages/' + urlattr.name + '.html';
},
controller: 'CMSController'
});
}
]);
From the docs (1.3.0):
"If templateUrl is a function, it will be called with the following parameters:
{Array.} - route parameters extracted from the current $location.path() by applying the current route"
Also
when(path, route) : Method
- path can contain named groups starting with a colon and ending with a star: e.g.:name*. All characters are eagerly stored in $routeParams under the given name when the route matches.
The example Java data structure in the original question does not match the description of the JSON structure in the comment.
The JSON is described as
"an array of {object with an array of {object}}".
In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is
"an array of {TypeDTO object with an array of {ItemDTO object}}".
But the Java data structure provided in the question is not this. Instead it's
"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".
A two-dimensional array != a single-dimensional array.
This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false},
{"id":4,"name":"name4","valid":true}
]
},
{
"id":5,
"name":"name5",
"items":
[
{"id":6,"name":"name6","valid":true},
{"id":7,"name":"name7","valid":false}
]
},
{
"id":8,
"name":"name8",
"items":
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false},
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items;
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false}
],
[
{"id":4,"name":"name4","valid":true}
]
]
},
{
"id":5,
"name":"name5",
"items":
[
[
{"id":6,"name":"name6","valid":true}
],
[
{"id":7,"name":"name7","valid":false}
]
]
},
{
"id":8,
"name":"name8",
"items":
[
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false}
],
[
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items[];
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
Regarding the remaining two questions:
is Gson extremely fast?
Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.
That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.
Or am I better to stick with what I've got working already?
I wouldn't. I would most always rather have one simple line of code like
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.
Maybe something like this:
connected = False
while not connected:
try:
try_connect()
connected = True
except ...:
pass
Add this code ..It helped me
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
classpath:/org/springframework/context/config/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
classpath:/org/springframework/aop/config/spring-aop-3.0.xsd
">
</beans>
This link explains where you're going wrong:
Place the definition of your constructors, destructors methods and whatnot in your header file, and that will correct the problem.
This offers another solution:
How can I avoid linker errors with my template functions?
However this requires you to anticipate how your template will be used and, as a general solution, is counter-intuitive. It does solve the corner case though where you develop a template to be used by some internal mechanism, and you want to police the manner in which it is used.
:.,$d
This will delete all content from current line to end of the file. This is very useful when you're dealing with test vector generation or stripping.
There are two steps you need to take.
First, you need to put the PDF in an iframe.
<iframe id="pdf" name="pdf" src="document.pdf"></iframe>
To print the iframe you can look at the answers here:
Javascript Print iframe contents only
If you want to print the iframe automatically after the PDF has loaded, you can add an onload handler to the <iframe>
:
<iframe onload="isLoaded()" id="pdf" name="pdf" src="document.pdf"></iframe>
the loader can look like this:
function isLoaded()
{
var pdfFrame = window.frames["pdf"];
pdfFrame.focus();
pdfFrame.print();
}
This will display the browser's print dialog, and then print just the PDF document itself. (I personally use the onload handler to enable a "print" button so the user can decide to print the document, or not).
I'm using this code pretty much verbatim in Safari and Chrome, but am yet to try it on IE or Firefox.
Many tricks work, but the Ajax request split the file name at 19 characters? Look at the output of the ajax request to see that:
The file name is okay to go into the href attribute, but the $(this).attr("href")
use
the text of the <a href='full/file/name' >
Split file name </a>
So the $(data).find("a:contains(.jpg)")
is not able to detect the extension.
I hope this is useful
I am always used DateDiff(day,date1,date2) to compare two date.
Checkout following example. Just copy that and run in Ms sql server. Also, try with change date by 31 dec to 30 dec and check result
BEGIN
declare @firstDate datetime
declare @secondDate datetime
declare @chkDay int
set @firstDate ='2010-12-31 15:13:48.593'
set @secondDate ='2010-12-31 00:00:00.000'
set @chkDay=Datediff(day,@firstDate ,@secondDate )
if @chkDay=0
Begin
Print 'Date is Same'
end
else
Begin
Print 'Date is not Same'
end
End
Just for someone looking for a solution more similar to R:
df[(df.Product == p_id) & (df.Time> start_time) & (df.Time < end_time)][['Time','Product']]
No need for data.loc
or query
, but I do think it is a bit long.
public class Array {
static int a[] = new int[101];
int counter = 0;
public int add(int num) {
if (num <= 100) {
Array.a[this.counter] = num;
System.out.println(a[this.counter]);
this.counter++;
return add(num + 1);
}
return 0;
}
public static void main(String[] args) {
Array c = new Array();
c.add(1);
}
}
It is .shape
:
ndarray.shape
Tuple of array dimensions.
Thus:
>>> a.shape
(2, 2)
Try this:
$(document).ready(function(){
var yourArray = [];
$("span.HOEnZb").find("div").each(function(){
if(($.trim($(this).text()).length>0)){
yourArray.push($(this).text());
}
});
});
I was not even concentrating, here is how to do it
$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = '$DOCDIR\MatchedLog'
if(!(Test-Path -Path $TARGETDIR )){
New-Item -ItemType directory -Path $TARGETDIR
}
SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'dbName';
This is mine:
USE databasename;
SHOW TABLES;
SELECT FOUND_ROWS();
If you want to find the word you can use
var word = words.Where(item => item.IsKey).First();
This gives you the first item for which IsKey is true (if there might be non you might want to use .FirstOrDefault()
To get both the item and the index you can use
KeyValuePair<WordType, int> word = words.Select((item, index) => new KeyValuePair<WordType, int>(item, index)).Where(item => item.Key.IsKey).First();
Using index
:
>>> string = "Username: How are you today?"
>>> string[:string.index(":")]
'Username'
The index will give you the position of :
in string, then you can slice it.
If you want to use regex:
>>> import re
>>> re.match("(.*?):",string).group()
'Username'
match
matches from the start of the string.
you can also use itertools.takewhile
>>> import itertools
>>> "".join(itertools.takewhile(lambda x: x!=":", string))
'Username'
This is a small tweak on the other answers. If you have nested divs you can include more exciting content such as H1s in your popup.
CSS
div.appear {
width: 250px;
border: #000 2px solid;
background:#F8F8F8;
position: relative;
top: 5px;
left:15px;
display:none;
padding: 0 20px 20px 20px;
z-index: 1000000;
}
div.hover {
cursor:pointer;
width: 5px;
}
div.hover:hover div.appear {
display:block;
}
HTML
<div class="hover">
<img src="questionmark.png"/>
<div class="appear">
<h1>My popup</h1>Hitherto and whenceforth.
</div>
</div>
The problem with these solutions is that everything after this in the page gets shifted when the popup is displayed, ie, the rest of the page jumps downwards to 'make space'. The only way I could fix this was by making position:absolute and removing the top and left CSS tags.
I ran into this exact problem too. In my case, adding parenthesis around any internal functions (to get them to evaluate first) seemed to do the trick:
Changed
=SUM(A1, SUBSTITUTE(A2,"x","3",1), A3)
to
=SUM(A1, (SUBSTITUTE(A2,"x","3",1)), A3)
I close them, but they always come back
When you say "they always come back" do you mean "next time you restart Visual Studio" or "immediately"?
One quirk of Visual Studio (at least VS2005) is that settings aren't saved until you exit. That means that if VS crashes at all while you are using it, any layout changes you made will be lost. The way around this is to always gracefully exit when you have set up everything like you want it to be.
Not sure if this will help your particular situation though.
UPDATE: I had some time on my hands, so ... I went ahead and fleshed out this idea. See below for the code.
Here's a bit of a crazy answer:
You could do what you're looking for -- essentially treat a two-dimensional array as a table with rows -- by writing a static method (perhaps an extension method) that takes a T[,]
and returns an IEnumerable<T[]>
. This would require copying each "row" of the underlying table into a new array, though.
A perhaps better (though more involved) approach would be to actually write a class that implements IList<T>
as a wrapper around a single "row" of a two-dimensional array (you would probably set IsReadOnly
to true and just implement the getter for the this[int]
property and probably Count
and GetEnumerator
; everything else could throw a NotSupportedException
). Then your static/extension method could return an IEnumerable<IList<T>>
and provide deferred execution.
That way you could write code pretty much like what you have:
foreach (IList<string> row in table.GetRows()) // or something
{
Console.WriteLine(row[0] + " " + row[1]);
}
Just a thought.
Implementation suggestion:
public static class ArrayTableHelper {
public static IEnumerable<IList<T>> GetRows<T>(this T[,] table) {
for (int i = 0; i < table.GetLength(0); ++i)
yield return new ArrayTableRow<T>(table, i);
}
private class ArrayTableRow<T> : IList<T> {
private readonly T[,] _table;
private readonly int _count;
private readonly int _rowIndex;
public ArrayTableRow(T[,] table, int rowIndex) {
if (table == null)
throw new ArgumentNullException("table");
if (rowIndex < 0 || rowIndex >= table.GetLength(0))
throw new ArgumentOutOfRangeException("rowIndex");
_table = table;
_count = _table.GetLength(1);
_rowIndex = rowIndex;
}
// I didn't implement the setter below,
// but you easily COULD (and then set IsReadOnly to false?)
public T this[int index] {
get { return _table[_rowIndex, index]; }
set { throw new NotImplementedException(); }
}
public int Count {
get { return _count; }
}
bool ICollection<T>.IsReadOnly {
get { return true; }
}
public IEnumerator<T> GetEnumerator() {
for (int i = 0; i < _count; ++i)
yield return this[i];
}
// omitted remaining IList<T> members for brevity;
// you actually could implement IndexOf, Contains, etc.
// quite easily, though
}
}
...now I think I should give StackOverflow a break for the rest of the day ;)
Here's how to use a Jet OLEDB or Ace OLEDB Access DB:
using System.Data;
using System.Data.OleDb;
string myConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\myPath\myFile.mdb;" +
"Persist Security Info=True;" +
"Jet OLEDB:Database Password=myPassword;";
try
{
// Open OleDb Connection
OleDbConnection myConnection = new OleDbConnection();
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
// Execute Queries
OleDbCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "SELECT * FROM `myTable`";
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); // close conn after complete
// Load the result into a DataTable
DataTable myDataTable = new DataTable();
myDataTable.Load(reader);
}
catch (Exception ex)
{
Console.WriteLine("OLEDB Connection FAILED: " + ex.Message);
}
I've mixed and matched from different schemes I've seen and based on the tooling I'm using.
So my completed branch name would be:
name/feature/issue-tracker-number/short-description
which would translate to:
mike/blogs/RSSI-12/logo-fix
The parts are separated by forward slashes because those get interpreted as folders in SourceTree for easy organization. We use Jira for our issue tracking so including the number makes it easier to look up in the system. Including that number also makes it searchable when trying to find that issue inside Github when trying to submit a pull request.
One more way -
select * from <table> where id=(select max(id) from <table>)
Also you can check on this link -
Some basic differences can be written in short:
MVC:
Traditional MVC is where there is a
MVP:
Similar to traditional MVC but Controller is replaced by Presenter. But the Presenter, unlike Controller is responsible for changing the view as well. The view usually does not call the presenter.
MVVM
The difference here is the presence of View Model. It is kind of an implementation of Observer Design Pattern, where changes in the model are represented in the view as well, by the VM. Eg: If a slider is changed, not only the model is updated but the data which may be a text, that is displayed in the view is updated as well. So there is a two-way data binding.
If you have a two-dimensional array in Python (not numpy), you can extract all the columns like so,
data = [
['a', 1, 2],
['b', 3, 4],
['c', 5, 6]
]
columns = list(zip(*data))
print("column[0] = {}".format(columns[0]))
print("column[1] = {}".format(columns[1]))
print("column[2] = {}".format(columns[2]))
Executing this code will yield,
>>> print("column[0] = {}".format(columns[0]))
column[0] = ('a', 'b', 'c')
>>> print("column[1] = {}".format(columns[1]))
column[1] = (1, 3, 5)
>>> print("column[2] = {}".format(columns[2]))
column[2] = (2, 4, 6)
Of course, you can extract a single column by index (e.g. columns[0]
)
You can use the iterator that is returned by the begin() method of the map template:
std::map<K,V> myMap;
std::pair<K,V> firstEntry = *myMap.begin()
But remember that the std::map container stores its content in an ordered way. So the first entry is not always the first entry that has been added.
These are the correct version that you can add in your build.gradle according to the API needs.
API 24:
implementation 'com.android.support:appcompat-v7:24.2.1'
implementation 'com.android.support:recyclerview-v7:24.2.1'
API 25:
implementation 'com.android.support:appcompat-v7:25.4.0'
implementation 'com.android.support:recyclerview-v7:25.4.0'
API 26:
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:recyclerview-v7:26.1.0'
API 27:
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'
This image presents both orientation(Landscape/Portrait)
To get MaxX and MaxY, read on.
For Android device screen coordinates, below concept will work.
Display mdisp = getWindowManager().getDefaultDisplay();
Point mdispSize = new Point();
mdisp.getSize(mdispSize);
int maxX = mdispSize.x;
int maxY = mdispSize.y;
EDIT:- ** **for devices supporting android api level older than 13. Can use below code.
Display mdisp = getWindowManager().getDefaultDisplay();
int maxX= mdisp.getWidth();
int maxY= mdisp.getHeight();
(x,y) :-
1) (0,0) is top left corner.
2) (maxX,0) is top right corner
3) (0,maxY) is bottom left corner
4) (maxX,maxY) is bottom right corner
here maxX and maxY are screen maximum height and width in pixels, which we have retrieved in above given code.
Sorry not sure what was going on this worked in the end:
<VirtualHost *>
ServerName example.com
DocumentRoot /var/www/html/mjp
Alias /ncn "/var/www/html/ncn"
<Directory "/var/www/html/ncn">
Options None
AllowOverride None
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
It's usually just easier to skip the mouse altogether--or it would be if Sublime didn't mess up multiselect when word wrapping. Here's the official documentation on using the keyboard and mouse for multiple selection. Since it's a bit spread out, I'll summarize it:
Where shortcuts are different in Sublime Text 3, I've made a note. For v3, I always test using the latest dev build; if you're using the beta build, your experience may be different.
If you lose your selection when switching tabs or windows (particularly on Linux), try using Ctrl + U to restore it.
Building blocks:
Combine as you see fit. For example:
Building blocks:
Combine as you see fit. For example:
On Yosemite and El Capitan, ^?? and ^?? are system keyboard shortcuts by default. If you want them to work in Sublime Text, you will need to change them:
System Preferences
.Shortcuts
tab.Mission Control
in the left listbox.Mission Control
and Application windows
(or disable them). I use ^?? and ^??. They defaults are ^? and ^?; adding ^ to those shortcuts triggers the same actions, but slows the animations.In case you're not familiar with Mac's keyboard symbols:
I got this error when attempting to build with Xcode 10. It appears to be a bug in the Swift compiler. Building with Whole Module Optimization
on, resolves the issue: https://forums.swift.org/t/illegal-instruction-4-when-trying-to-compile-project/16118
This is not an ideal solution, I will continue to use Xcode 9.4.1 until this issue is resolved.
If you want it casted to a specific type you can use this method. Most non primitive types won't by default support direct casting so you will have to handle those accordingly.
public T GetValue<T>(string registryKeyPath, string value, T defaultValue = default(T))
{
T retVal = default(T);
retVal = (T)Registry.GetValue(registryKeyPath, value, defaultValue);
return retVal;
}
'L' means wchar_t
, which, as opposed to a normal character, requires 16-bits of storage rather than 8-bits. Here's an example:
"A" = 41
"ABC" = 41 42 43
L"A" = 00 41
L"ABC" = 00 41 00 42 00 43
A wchar_t
is twice big as a simple char. In daily use you don't need to use wchar_t, but if you are using windows.h you are going to need it.
JPG and JPEG stand both for an image format proposed and supported by the Joint Photographic Experts Group. The two terms have the same meaning and are interchangeable.
To read on, check out Difference between JPG and JPEG.
The reason for the different file extensions dates back to the early versions of Windows. The original file extension for the Joint Photographic Expert Group File Format was ‘.jpeg’; however in Windows all files required a three letter file extension. So, the file extension was shortened to ‘.jpg’. However, Macintosh was not limited to three letter file extensions, so Mac users used ‘.jpeg’. Eventually, with upgrades Windows also began to accept ‘.jpeg’. However, many users were already used to ‘.jpg’, so both the three letter file extension and the four letter extension began to be commonly used, and still is.
Today, the most commonly accepted and used form is the ‘.jpg’, as many users were Windows users. Imaging applications, such as Adobe Photoshop, save all JPEG files with a ".jpg" extension on both Mac and Windows, in an attempt to avoid confusion. The Joint Photographic Expert Group File Format can also be saved with the upper-case ‘.JPEG’ and ‘.JPG’ file extensions, which are less common, but also accepted.
While the final version of HttpContent and the entire System.Net.Http namespace will come with .NET 4.5, you can use a .NET 4 version by adding the Microsoft.Net.Http package from NuGet
In this situation I would try:
$(document).on('click','.addproduct', function(){
//your code here
});
then, if you need to perform something in the other elements with the same class on click on one ot them you can loop through the elements:
$(document).on('click','.addproduct', function(){
$('.addproduct').each( function(){
//your code here
}
);
}
);
Go to mirror.olnevhost.net/pub/apache/maven/binaries/ and check what is the latest tar.gz file
Supposing it is e.g. apache-maven-3.2.1-bin.tar.gz, from the command line; you should be able to simply do:
wget http://mirror.olnevhost.net/pub/apache/maven/binaries/apache-maven-3.2.1-bin.tar.gz
And then proceed to install it.
UPDATE: Adding complete instructions (copied from the comment below)
run the following to extract the tar:
tar xvf apache-maven-3.2.1-bin.tar.gz
Next add the env varibles such as
export M2_HOME=/usr/local/apache-maven/apache-maven-3.2.1
export M2=$M2_HOME/bin
export PATH=$M2:$PATH
Verify
mvn -version
CentOS is Linux, so as in just about all other Unix/Linux systems, you have the find
command. To search for files within the current directory:
find -name "filename"
You can also have wildcards inside the quotes, and not just a strict filename. You can also explicitly specify a directory to start searching from as the first argument to find:
find / -name "filename"
will look for "filename" or all the files that match the regex expression in between the quotes, starting from the root directory. You can also use single quotes instead of double quotes, but in most cases you don't need either one, so the above commands will work without any quotes as well. Also, for example, if you're searching for java files and you know they are somewhere in your /home/username, do:
find /home/username -name *.java
There are many more options to the find command and you should do a:
man find
to learn more about it.
One more thing: if you start searching from / and are not root or are not sudo running the command, you might get warnings that you don't have permission to read certain directories. To ignore/remove those, do:
find / -name 'filename' 2>/dev/null
That just redirects the stderr to /dev/null.
When you need a programatically way of doing it, you can set it during startup:
System.getProperties().put( "server.port", 80 );
SpringApplication.run(App.class, args);
This might help for things like environment dependent port. Have a nice day
If you use %pylab inline
you can (on a new line) insert the following command:
%pylab inline
pylab.rcParams['figure.figsize'] = (10, 6)
This will set all figures in your document (unless otherwise specified) to be of the size (10, 6)
, where the first entry is the width and the second is the height.
See this SO post for more details. https://stackoverflow.com/a/17231361/1419668
You can use this code:
var vid = document.getElementById("video1");
function slowPlaySpeed() {
vid.playbackRate = 0.5;
}
function normalPlaySpeed() {
vid.playbackRate = 1;
}
function fastPlaySpeed() {
vid.playbackRate = 2;
}
The one way is by using webservice, simply write a webservice method in PHP or any other language . And From your android app by using http client request and response , you can hit the web service method which will return whatever you want.
For PHP You can create a webservice like this. Assuming below we have a php file in the server. And the route of the file is yourdomain.com/api.php
if(isset($_GET['api_call'])){
switch($_GET['api_call']){
case 'userlogin':
//perform your userlogin task here
break;
}
}
Now you can use Volley or Retrofit to send a network request to the above PHP Script and then, actually the php script will handle the database operation.
In this case the PHP script is called a RESTful API.
You can learn all the operation at MySQL from this tutorial. Android MySQL Tutorial to Perform CRUD.
This typically occurs when there is unintended output from the script before you start the session. With your current code, you could try to use output buffering to solve it.
try adding a call to the ob_start();
function at the very top of your script and ob_end_flush();
at the very end of the document.
View Page
@using (Html.BeginForm("ActionmethodName", "ControllerName", FormMethod.Post, new { id = "formid" }))
{
<input type="file" name="file" />
<input type="submit" value="Upload" class="save" id="btnid" />
}
script file
$(document).on("click", "#btnid", function (event) {
event.preventDefault();
var fileOptions = {
success: res,
dataType: "json"
}
$("#formid").ajaxSubmit(fileOptions);
});
In Controller
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
}
javap
to read the bytecodeThe javap
command takes class-names without the .class
extension. Try
javap -c ClassName
javap
will however not give you the implementations of the methods in java-syntax. It will at most give it to you in JVM bytecode format.
To actually decompile (i.e., do the reverse of javac
) you will have to use proper decompiler. See for instance the following related question:
Best way to do is :
[self performSelector:@selector(YourFunctionName)
withObject:(can be Self or Object from other Classes)
afterDelay:(Time Of Delay)];
you can also pass nil as withObject parameter.
example :
[self performSelector:@selector(subscribe) withObject:self afterDelay:3.0 ];
I actually use a makefile to build any dependencies needed before invoking devenv to build a particular project as in the following:
debug: coratools_debug
devenv coralib.vcproj /build debug
coratools_debug: nothing
cd ../coratools
nmake debug
cd $(MAKEDIR)
You can also use the msbuild tool to do the same thing:
debug: coratools_debug
msbuild coralib.vcxproj /p:Configuration=debug
coratools_debug: nothing
cd ../coratools
nmake debug
cd $(MAKEDIR)
In my opinion, this is much easier than trying to figure out the overly complicated visual studio project management scheme.
Basically you use props to send information to and from Child and Parent.
Adding to all the wonderful answers, let me give a simple example that explains passing values from child to parent component in React
App.js
class App extends React.Component {
constructor(){
super();
this.handleFilterUpdate = this.handleFilterUpdate.bind(this);
this.state={name:'igi'}
}
handleFilterUpdate(filterValue) {
this.setState({
name: filterValue
});
}
render() {
return (
<div>
<Header change={this.handleFilterUpdate} name={this.state.name} />
<p>{this.state.name}</p>
</div>
);
}
}
Header.js
class Header extends React.Component {
constructor(){
super();
this.state={
names: 'jessy'
}
}
Change(event) {
// this.props.change(this.state.names);
this.props.change('jessy');
}
render() {
return (
<button onClick={this.Change.bind(this)}>click</button>
);
}
}
Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
Thats it , now you can pass values from your client to the server.
Take a look at the Change function in the Header.js
Change(event) {
// this.props.change(this.state.names);
this.props.change('jessy');
}
This is how you push values into the props from client to the server
This is called the "shape" in NumPy, and can be requested via the .shape
attribute:
>>> a = zeros((2, 5))
>>> a.shape
(2, 5)
If you prefer a function, you could also use numpy.shape(a)
.
Maybe
if (inventory.contains("bread") && !inventory.contains("water"))
Or
if (inventory.contains("bread")) {
if (!inventory.contains("water")) {
// do something here
}
}
You can use this:
Collections.sort(list, org.joda.time.DateTimeComparator.getInstance());
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
Run this in your browser console of choice.
if(jQuery().pluginName){console.log('bonjour');}
If the plugin exists it will print out "bonjour" as a response in your console.
Examples:
class Dog
{
public:
barkAt( const std::string& pOtherDog ); // const reference
barkAt( std::string pOtherDog ); // value
};
const &
is generally best. You don't incur the construction and destruction penalty. If the reference isn't const your interface is suggesting that it will change the passed in data.
How does [HttpContext.Current.User] know which usernames exist or do not exist?
Let's look at an example of one way this works. Suppose you are using Forms Authentication and the "OnAuthenticate" event fires. This event occurs "when the application authenticates the current request" (Reference Source).
Up until this point, the application has no idea who you are.
Since you are using Forms Authentication, it first checks by parsing the authentication cookie (usually .ASPAUTH) via a call to ExtractTicketFromCookie
. This calls FormsAuthentication.Decrypt
(This method is public; you can call this yourself!). Next, it calls Context.SetPrincipalNoDemand
, turning the cookie into a user and stuffing it into Context.User
(Reference Source).
In Spring 4 Web MVC. You can use @SessionAttribute
in the method with @SessionAttributes
in Controller level
@Controller
@SessionAttributes("SessionKey")
public class OrderController extends BaseController {
GetMapping("/showOrder")
public String showPage(@SessionAttribute("SessionKey") SearchCriteria searchCriteria) {
// method body
}
Last version of jupyter notebook accepts copy/paste of image natively
I found another strange reason and i thought maybe another developer confused as me. I did run install.bat that created to install my service in developer Command Prompt of VS2010 but my service generated in VS2012. it was going to this error and drives me to crazy but i try VS2012 Developer Command Prompt tools and everything gone to be OK. I don't no why but my problem was solved. so you can test it and if anyone know reason of that please share with us. Thanks.
OR
rm -rf `find /path/to/base/dir/* -type d -mtime +10`
Updated, faster version of it:
find /path/to/base/dir/* -mtime +10 -print0 | xargs -0 rm -f
Setup JAVA_OPTS as a system variable with the following content:
JAVA_OPTS="-Xms256m -Xmx512m"
After that in a command prompt run the following commands:
SET JAVA_OPTS="-Xms256m -Xmx512m"
This can be explained as follows:
These values should be changed according to application requirements.
EDIT:
You can also try adding it through the Environment Properties menu which can be found at:
EDIT 2:
JAVA_OPTS is a system variable that stores various settings/configurations for your local Java Virtual Machine. By having JAVA_OPTS set as a system variable all applications running on top of the JVM will take their settings from this parameter.
To setup a system variable you have to complete the steps listed above from 1 to 4.
I know rather old question but....came across looking other thing so I give my shot:
[each*2 for each in [1,2,3,4,5] if each % 10 == 0])
Switch is not same as if-else-if.
Switch is used when there is one expression that gets evaluated to a value and that value can be one of predefined set of values. If you need to perform multiple boolean / comparions operations run-time then if-else-if needs to be used.
If those elements have a common class name, one may also use this:
$('#your_div .your_classname').serialize()
This way you can avoid selection of buttons, which will be selected using the jQuery selector :input
. Though this can also be avoided by using $('#your_div :input:not(:button)').serialize();
It should be like this :
<string name="game_settings_dragNDropMove_checkBox">Move by Drag&Drop</string>
try like this
= IIF( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ) ) = -1, "", FormatNumber( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ), "CellReading_Reading"),3)) )
For mixed position and index, use .ix
. BUT you need to make sure that your index is not of integer, otherwise it will cause confusions.
df.ix[0, 'COL_NAME'] = x
Alternatively, try
df.iloc[0, df.columns.get_loc('COL_NAME')] = x
Example:
import pandas as pd
import numpy as np
# your data
# ========================
np.random.seed(0)
df = pd.DataFrame(np.random.randn(10, 2), columns=['col1', 'col2'], index=np.random.randint(1,100,10)).sort_index()
print(df)
col1 col2
10 1.7641 0.4002
24 0.1440 1.4543
29 0.3131 -0.8541
32 0.9501 -0.1514
33 1.8676 -0.9773
36 0.7610 0.1217
56 1.4941 -0.2052
58 0.9787 2.2409
75 -0.1032 0.4106
76 0.4439 0.3337
# .iloc with get_loc
# ===================================
df.iloc[0, df.columns.get_loc('col2')] = 100
df
col1 col2
10 1.7641 100.0000
24 0.1440 1.4543
29 0.3131 -0.8541
32 0.9501 -0.1514
33 1.8676 -0.9773
36 0.7610 0.1217
56 1.4941 -0.2052
58 0.9787 2.2409
75 -0.1032 0.4106
76 0.4439 0.3337
One thing that the above solutions don't take into account is if you have an array of inputs but only one value was supplied.
For instance, if the back end expects an array of People, but in this particular case, you are just dealing with a single person. Then doing:
<input type="hidden" name="People" value="Joe" />
Then with the previous solutions, it would just map to something like:
{
"People" : "Joe"
}
But it should really map to
{
"People" : [ "Joe" ]
}
To fix that, the input should look like:
<input type="hidden" name="People[]" value="Joe" />
And you would use the following function (based off of other solutions, but extended a bit)
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (this.name.substr(-2) == "[]"){
this.name = this.name.substr(0, this.name.length - 2);
o[this.name] = [];
}
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Originally it was used as an anchor to jump to an element with the same name/id.
However, nowadays it's usually used with AJAX-based pages since changing the hash can be detected using JavaScript and allows you to use the back/forward button without actually triggering a full page reload.
If the array is not large, you could just loop and check the string against each substring individually using indexOf()
. Alternatively you could construct a regular expression with substrings as alternatives, which may or may not be more efficient.
Already good answer there. Just add a benchmark result for StringBuffer and StringBuild performance difference use new instance in loop or use setLength(0) in loop.
The summary is: In a large loop
Very simple benchmark (I just manually changed the code and do different test ):
public class StringBuilderSpeed {
public static final char ch[] = new char[]{'a','b','c','d','e','f','g','h','i'};
public static void main(String a[]){
int loopTime = 99999999;
long startTime = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
for(int i = 0 ; i < loopTime; i++){
for(char c : ch){
sb.append(c);
}
sb.setLength(0);
}
long endTime = System.currentTimeMillis();
System.out.println("Time cost: " + (endTime - startTime));
}
}
New StringBuilder instance in loop: Time cost: 3693, 3862, 3624, 3742
StringBuilder setLength: Time cost: 3465, 3421, 3557, 3408
New StringBuffer instance in loop: Time cost: 8327, 8324, 8284
StringBuffer setLength Time cost: 22878, 23017, 22894
Again StringBuilder setLength to ensure not my labtop got some issue to use such long for StringBuffer setLength :-) Time cost: 3448
Actually, both INSTALLPATH/TARGETDIR
are correct. It depends on how MSI processes this.
I create a MSG using wixToolSet
. In WXS file, there is "Directory" Node, which root dir maybe like the following:
<Directory Id="**TARGETDIR**" Name="SourceDir">;
As you can see: Id
is which you should use.
I imagine this forum posting, which I quote fully below, should answer the question.
Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):
BEGIN ATOMIC
DECLARE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
END
or (in any environment):
WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM tablename, t
WHERE column1 = example
or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):
CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
follow the python2.7 document, you have to use calendar.timegm() instead of time.mktime()
>>> d = datetime.date(2011,01,01)
>>> datetime.datetime.utcfromtimestamp(calendar.timegm(d.timetuple()))
datetime.datetime(2011, 1, 1, 0, 0)
I just want to point out that the FindBoost macro might be looking for an earlier version, for instance, 1.58.0 when you might have 1.60.0 installed. I suggest popping open the FindBoost macro from whatever it is you are attempting to build, and checking if that's the case. You can simply edit it to include your particular version. (This was my problem.)
Loop through the file.
f = open("masters.txt")
lines = f.readlines()
for line in lines:
print line
Try obj2fd => https://www.npmjs.com/package/obj2fd
import obj2fd from 'obj2fd'
let data = {a:1, b:2, c:{ca:1}};
let dataWithFormData = obj2fd(data);
//result => [a=>1, b=>2, c=>[ca=>1]]
$variable[0] != "_"
In PHP you can get particular character of a string with array index notation. $variable[0]
is the first character of a string (if $variable is a string).
Adding processData: false
to the $.ajax
options will fix this issue.
You don't have the namespace the Login class is in as a reference.
Add the following to the form that uses the Login
class:
using FootballLeagueSystem;
When you want to use a class in another namespace, you have to tell the compiler where to find it. In this case, Login
is inside the FootballLeagueSystem
namespace, or : FootballLeagueSystem.Login
is the fully qualified namespace.
As a commenter pointed out, you declare the Login class inside the FootballLeagueSystem
namespace, but you're using it in the FootballLeague
namespace.
You can instruct tesseract to use only digits, and if that is not accurate enough then best chance of getting better results is to go trough training process: http://www.resolveradiologic.com/blog/2013/01/15/training-tesseract/
Technically redirect should be used either if we need to transfer control to different domain or to achieve separation of task.
For example in the payment application we do the PaymentProcess first and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PaymentProcess will not be repeated. But if we use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.
For other scenarios, forward is efficient to use since as it is faster than sendRedirect
If you just want to remove "username1" you can use a simple replace.
name.replace("username1,", "")
or you could use split like you mentioned.
var name = "username1, username2 and username3 like this post.".split(",")[1];
$("h1").text(name);
jsfiddle example
You can set Default attribute in Model also>
protected $attributes = [
'status' => self::STATUS_UNCONFIRMED,
'role_id' => self::ROLE_PUBLISHER,
];
You can find the details in these links
1.) How to set a default attribute value for a Laravel / Eloquent model?
You can also Use Accessors & Mutators for this You can find the details in the Laravel documentation 1.) https://laravel.com/docs/4.2/eloquent#accessors-and-mutators
2.) https://scotch.io/tutorials/automatically-format-laravel-database-fields-with-accessors-and-mutators
['class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost:3306;dbname=testdb',
'username' => 'user',
'password' => 'password',
'charset' => 'utf8',]
It's simple:
Just provide the port number along with the host name
and set default sock path to your mysql.sock
file path in php.ini
which the server is running on.
Here's a function that'll do it:
def totuple(a):
try:
return tuple(totuple(i) for i in a)
except TypeError:
return a
And an example:
>>> array = numpy.array(((2,2),(2,-2)))
>>> totuple(array)
((2, 2), (2, -2))
you can also just add it to the command option eg.
command: bash -c "sleep 5; start.sh"
https://github.com/docker/compose/issues/374#issuecomment-156546513
to wait on a port you can also use something like this
command: bash -c "while ! curl -s rabbitmq:5672 > /dev/null; do echo waiting for xxx; sleep 3; done; start.sh"
to increment the waiting time you can hack a bit more:
command: bash -c "for i in {1..100} ; do if ! curl -s rabbitmq:5672 > /dev/null ; then echo waiting on rabbitmq for $i seconds; sleep $i; fi; done; start.sh"
Since there isn't one simple answer that always gives the correct age, here's what I came up with.
SELECT DATEDIFF(YY, DateOfBirth, GETDATE()) -
CASE WHEN RIGHT(CONVERT(VARCHAR(6), GETDATE(), 12), 4) >=
RIGHT(CONVERT(VARCHAR(6), DateOfBirth, 12), 4)
THEN 0 ELSE 1 END AS AGE
This gets the year difference between the birth date and the current date. Then it subtracts a year if the birthdate hasn't passed yet.
Accurate all the time - regardless of leap years or how close to the birthdate.
Best of all - no function.
Why one want to use it ?
To reduce the memory of the structure
Why one should not use it ?
I think the question is not 100% answered. I was searching for issue with missing typeof(), which is compile time directive.
Following links will shine light on the situation:
https://gcc.gnu.org/onlinedocs/gcc-5.3.0/gcc/Typeof.html
https://gcc.gnu.org/onlinedocs/gcc-5.3.0/gcc/Alternate-Keywords.html#Alternate-Keywords
as of conculsion try to use __typeof__()
instead. Also gcc ... -Dtypeof=__typeof__ ...
can help.
If your numbers are a, b and c then:
int a = 1;
int b = 2;
int c = 3;
int d = a > b ? a : b;
return c > d ? c : d;
This could turn into one of those "how many different ways can we do this" type questions!
If you need a custom string sort, you can create a function that returns a number based on the order you specify.
For example, I had pictures that I wanted to sort based on being front side or clasp. So I did the following:
Private Function sortpictures(s As String) As Integer
If Regex.IsMatch(s, "FRONT") Then
Return 0
ElseIf Regex.IsMatch(s, "SIDE") Then
Return 1
ElseIf Regex.IsMatch(s, "CLASP") Then
Return 2
Else
Return 3
End If
End Function
Then I call the sort function like this:
list.Sort(Function(elA As String, elB As String)
Return sortpictures(elA).CompareTo(sortpictures(elB))
End Function)
I've only ever seen CopyFile
fail with a "permission denied" error in one of these 3 scenarios:
Based on @pilau s answer - but with an improvement that even the accepted answer does not have.
<div class="angular-with-newlines" ng-repeat="item in items">
{{item.description}}
</div>
/* in the css file or in a style block */
.angular-with-newlines {
white-space: pre-line;
}
This will use newlines and whitespace as given, but also break content at the content boundaries. More information about the white-space property can be found here:
https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
If you want to break on newlines, but also not collapse multiple spaces or white space preceeding the text (to render code or something), you can use:
white-space: pre-wrap;
Nice comparison of the different rendering modes: http://meyerweb.com/eric/css/tests/white-space.html
I ran into this problem some days ago, for a pure NodeJS answer I would suggest using Stream to merge the chunks together.
var http = require('http'),
Stream = require('stream').Transform,
fs = require('fs');
var url = 'http://www.google.com/images/srpr/logo11w.png';
http.request(url, function(response) {
var data = new Stream();
response.on('data', function(chunk) {
data.push(chunk);
});
response.on('end', function() {
fs.writeFileSync('image.png', data.read());
});
}).end();
The newest Node versions won't work well with binary strings, so merging chunks with strings is not a good idea when working with binary data.
*Just be careful when using 'data.read()', it will empty the stream for the next 'read()' operation. If you want to use it more than once, store it somewhere.
Alen Saqe's latest JSFiddle didn't toggle for me on Firefox, so I thought I would provide a simple html/javascript workaround that will function nicely within forms (regarding submission) until the day that the datalist tag is accepted by all browsers/devices. For more details and see it in action, go to: http://jsfiddle.net/6nq7w/4/ Note: Do not allow any spaces between toggling siblings!
<!DOCTYPE html>
<html>
<script>
function toggleField(hideObj,showObj){
hideObj.disabled=true;
hideObj.style.display='none';
showObj.disabled=false;
showObj.style.display='inline';
showObj.focus();
}
</script>
<body>
<form name="BrowserSurvey" action="#">
Browser: <select name="browser"
onchange="if(this.options[this.selectedIndex].value=='customOption'){
toggleField(this,this.nextSibling);
this.selectedIndex='0';
}">
<option></option>
<option value="customOption">[type a custom value]</option>
<option>Chrome</option>
<option>Firefox</option>
<option>Internet Explorer</option>
<option>Opera</option>
<option>Safari</option>
</select><input name="browser" style="display:none;" disabled="disabled"
onblur="if(this.value==''){toggleField(this,this.previousSibling);}">
<input type="submit" value="Submit">
</form>
</body>
</html>
Cross browser compatible JS solution:
var e = document.getElementById('elem');_x000D_
var spin = false;_x000D_
_x000D_
var spinner = function(){_x000D_
e.classList.toggle('running', spin);_x000D_
if (spin) setTimeout(spinner, 2000);_x000D_
}_x000D_
_x000D_
e.onmouseover = function(){_x000D_
spin = true;_x000D_
spinner();_x000D_
};_x000D_
_x000D_
e.onmouseout = function(){_x000D_
spin = false;_x000D_
};
_x000D_
body { _x000D_
height:300px; _x000D_
}_x000D_
#elem {_x000D_
position:absolute;_x000D_
top:20%;_x000D_
left:20%;_x000D_
width:0; _x000D_
height:0;_x000D_
border-style: solid;_x000D_
border-width: 75px;_x000D_
border-color: red blue green orange;_x000D_
border-radius: 75px;_x000D_
}_x000D_
_x000D_
#elem.running {_x000D_
animation: spin 2s linear 0s infinite;_x000D_
}_x000D_
_x000D_
@keyframes spin { _x000D_
100% { transform: rotate(360deg); } _x000D_
}
_x000D_
<div id="elem"></div>
_x000D_
#longest palindrome_x000D_
s='HYTBCABADEFGHABCDEDCBAGHTFYW123456789987654321ZWETYGDE'_x000D_
out1=[]_x000D_
def substring(x):_x000D_
for i in range(len(x)):_x000D_
a=x[i:]_x000D_
b=x[:-i]_x000D_
out1.append(a)_x000D_
out1.append(b)_x000D_
_x000D_
return out1_x000D_
_x000D_
for i in range(len(s)):_x000D_
substring(s[i:]) _x000D_
final=set([item for item in out1 if len(item)>2])_x000D_
final_x000D_
palind={item:len(item) for item in final if item==item[::-1]}_x000D_
print(palind)_x000D_
sorted(palind.items(),reverse=True, key=lambda x: x[1])[0]
_x000D_
{'DED': 3, '123456789987654321': 18, '67899876': 8, 'ABCDEDCBA': 9, '456789987654': 12, '34567899876543': 14, 'BCDEDCB': 7, 'ABA': 3, '5678998765': 10, '2345678998765432': 16, 'CDEDC': 5, '789987': 6, '8998': 4} ('123456789987654321', 18)
Yes you only need $()
when you're using jQuery. If you want jQuery's help to do DOM things just keep this in mind.
$(this)[0] === this
Basically every time you get a set of elements back jQuery turns it into a jQuery object. If you know you only have one result, it's going to be in the first element.
$("#myDiv")[0] === document.getElementById("myDiv");
And so on...
You can use the .input-group
class like this:
<div class="input-group">
<input type="text" class="form-control"/>
<span class="input-group-addon">
<i class="fa fa-search"></i>
</span>
</div>
You can use the .input-append
class like this:
<div class="input-append">
<input class="span2" type="text">
<button type="submit" class="btn">
<i class="icon-search"></i>
</button>
</div>
Both will look like this:
If you'd like the icon inside the input box, like this:
Then see my answer to Add a Bootstrap Glyphicon to Input Box
The best answer here is too long. I cannot comment so I added my answer.
Absolute positioning positions an element relative to its nearest positioned ancestor. So put position: relative
on the container, then for child elements, top
and left
will be relative to the top-left of the container so long as the child elements have position: absolute
. More information is available in the CSS 2.1 specification.
res = ActiveRecord::Base.connection_pool.with_connection { |con| con.exec_query( "SELECT 1;" ) }
The above code is an example for
Nope, ThreadAbortException
is thrown by a simple Response.Redirect
If you only need the first row from each group we can do with drop_duplicates
, Notice the function default method keep='first'
.
df.drop_duplicates('id')
Out[1027]:
id value
0 1 first
3 2 first
5 3 first
9 4 second
11 5 first
12 6 first
15 7 fourth
After thinking this through carefully, I think this is the best way. It lets you step off in the middle easily without using break
, which I think is important, and it requires minimal computation, so I think it's the fastest. It also doesn't require that li
be a list or tuple. It could be any iterator.
from itertools import cycle
li = [0, 1, 2, 3]
running = True
licycle = cycle(li)
# Prime the pump
nextelem = next(licycle)
while running:
thiselem, nextelem = nextelem, next(licycle)
I'm leaving the other solutions here for posterity.
All of that fancy iterator stuff has its place, but not here. Use the % operator.
li = [0, 1, 2, 3]
running = True
while running:
for idx, elem in enumerate(li):
thiselem = elem
nextelem = li[(idx + 1) % len(li)]
Now, if you intend to infinitely cycle through a list, then just do this:
li = [0, 1, 2, 3]
running = True
idx = 0
while running:
thiselem = li[idx]
idx = (idx + 1) % len(li)
nextelem = li[idx]
I think that's easier to understand than the other solution involving tee
, and probably faster too. If you're sure the list won't change size, you can squirrel away a copy of len(li)
and use that.
This also lets you easily step off the ferris wheel in the middle instead of having to wait for the bucket to come down to the bottom again. The other solutions (including yours) require you check running
in the middle of the for
loop and then break
.
Along with the great answers in this post I am going to propose Divide and Conquer approach, I am not writing this answer to abolish the other great answers but to fulfill them with another approach which was working efficiently for me. It has two steps of splitting
and merging
the pandas dataframe:
PROS of Divide and Conquer:
iterrows()
and itertuples()
in my case were having the same performance over entire dataframeindex
, you will be able to exponentially quicken the iteration. The higher index
, the quicker your iteration process.CONS of Divide and Conquer:
=================== Divide and Conquer Approach =================
Step 1: Splitting/Slicing
In this step, we are going to divide the iteration over the entire dataframe. Think that you are going to read a csv file into pandas df then iterate over it. In may case I have 5,000,000 records and I am going to split it into 100,000 records.
NOTE: I need to reiterate as other runtime analysis explained in the other solutions in this page, "number of records" has exponential proportion of "runtime" on search on the df. Based on the benchmark on my data here are the results:
Number of records | Iteration per second
========================================
100,000 | 500 it/s
500,000 | 200 it/s
1,000,000 | 50 it/s
5,000,000 | 20 it/s
Step 2: Merging
This is going to be an easy step, just merge all the written csv files into one dataframe and write it into a bigger csv file.
Here is the sample code:
# Step 1 (Splitting/Slicing)
import pandas as pd
df_all = pd.read_csv('C:/KtV.csv')
df_index = 100000
df_len = len(df)
for i in range(df_len // df_index + 1):
lower_bound = i * df_index
higher_bound = min(lower_bound + df_index, df_len)
# splitting/slicing df (make sure to copy() otherwise it will be a view
df = df_all[lower_bound:higher_bound].copy()
'''
write your iteration over the sliced df here
using iterrows() or intertuples() or ...
'''
# writing into csv files
df.to_csv('C:/KtV_prep_'+str(i)+'.csv')
# Step 2 (Merging)
filename='C:/KtV_prep_'
df = (pd.read_csv(f) for f in [filename+str(i)+'.csv' for i in range(ktv_len // ktv_index + 1)])
df_prep_all = pd.concat(df)
df_prep_all.to_csv('C:/KtV_prep_all.csv')
Reference:
I'd like to share this little hack:
A click on the Eclipse's icon indicated a problem with the JRE. So, I put this command in the destination field of the icon's properties:
C:\...\eclipse.exe -vm c:\'Program Files'\Java\jdk1.7.0_51\jre\bin\javaw
Thinking that the "'" would solve the problem with the space in the path. That did not function. Then, I tried this command:
C:\...\eclipse.exe -vm c:\Progra~1\Java\jdk1.7.0_51\jre\bin\javaw
with success
You can also use this very simplified form:
@Html.ActionLink("Come back to Home", "Index", "Home")
Where :
Come back to Home
is the text that will appear on the page
Index
is the view name
Home
is the controller name
You CAN add on click to dynamically created elements. Example below. Using a When to make sure its done. In my example, i'm grabbing a div with the class expand, adding a "click to see more" span, then using that span to hide/show the original div.
$.when($(".expand").before("<span class='clickActivate'>Click to see more</span>")).then(function(){
$(".clickActivate").click(function(){
$(this).next().toggle();
})
});
The distance estimate provided by iOS is based on the ratio of the beacon signal strength (rssi) over the calibrated transmitter power (txPower). The txPower is the known measured signal strength in rssi at 1 meter away. Each beacon must be calibrated with this txPower value to allow accurate distance estimates.
While the distance estimates are useful, they are not perfect, and require that you control for other variables. Be sure you read up on the complexities and limitations before misusing this.
When we were building the Android iBeacon library, we had to come up with our own independent algorithm because the iOS CoreLocation source code is not available. We measured a bunch of rssi measurements at known distances, then did a best fit curve to match our data points. The algorithm we came up with is shown below as Java code.
Note that the term "accuracy" here is iOS speak for distance in meters. This formula isn't perfect, but it roughly approximates what iOS does.
protected static double calculateAccuracy(int txPower, double rssi) {
if (rssi == 0) {
return -1.0; // if we cannot determine accuracy, return -1.
}
double ratio = rssi*1.0/txPower;
if (ratio < 1.0) {
return Math.pow(ratio,10);
}
else {
double accuracy = (0.89976)*Math.pow(ratio,7.7095) + 0.111;
return accuracy;
}
}
Note: The values 0.89976, 7.7095 and 0.111 are the three constants calculated when solving for a best fit curve to our measured data points. YMMV
Without moment.js:
var time_to_show = 1509968436; // unix timestamp in seconds_x000D_
_x000D_
var t = new Date(time_to_show * 1000);_x000D_
var formatted = ('0' + t.getHours()).slice(-2) + ':' + ('0' + t.getMinutes()).slice(-2);_x000D_
_x000D_
document.write(formatted);
_x000D_
A common mistake during development of an android app running on a Virtual Device on your dev machine is to forget that the virtual device is not the same host as your dev machine. So if your server is running on your dev machine you cannot use a "http://localhost/..." url as that will look for the server endpoint on the virtual device not your dev machine.
You shouldn't be doing tuple dereferencing on values that can change like your line below.
script, user_name = argv
The line above will fail if you pass less than one argument or more than one argument. A better way of doing this is to do something like this:
for arg in argv[1:]:
print arg
Of cause you will do something other than print the args. Maybe put a series of 'if' statement in the 'for' loop that set variables depending on the arguments passed. An even better way is to use the getopt or optparse packages.
If you are at a certain branch mybranch
, just go ahead and git checkout commit_hash
. Then you can return to your branch by git checkout mybranch
. I had the same game bisecting a bug today :) Also, you should know about git bisect.
If you already know what type it can cast to, use a C-style cast:
var o = (string) iKnowThisIsAString;
Note that only with a C-style cast can you perform explicit type coercion.
If you don't know whether it's the desired type and you're going to use it if it is, use as keyword:
var s = o as string;
if (s != null) return s.Replace("_","-");
//or for early return:
if (s==null) return;
Note that as will not call any type conversion operators. It will only be non-null if the object is not null and natively of the specified type.
Use ToString() to get a human-readable string representation of any object, even if it can't cast to string.
you should see this tutorial: https://scotch.io/@micwanyoike/how-to-add-fonts-to-a-react-project
import WebFont from 'webfontloader';
WebFont.load({
google: {
families: ['Titillium Web:300,400,700', 'sans-serif']
}
});
I just tried this method and I can say that it works very well ;)
Use display: none
instead. Besides, this is probably what you need, because this also truncates the page by removing the space the table occupies, whereas visibility: hidden
leaves the white space left by the table.
From the CSS specification on Calculating widths and margins for Block-level, non-replaced elements in normal flow:
If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.
Grep is useful if you want to quickly search for lines that match in a file. It can also return some other simple information like matching line numbers, match count, and file name lists.
Awk is an entire programming language built around reading CSV-style files, processing the records, and optionally printing out a result data set. It can do many things but it is not the easiest tool to use for simple tasks.
Sed is useful when you want to make changes to a file based on regular expressions. It allows you to easily match parts of lines, make modifications, and print out results. It's less expressive than awk but that lends it to somewhat easier use for simple tasks. It has many more complicated operators you can use (I think it's even turing complete), but in general you won't use those features.
To answer the Susitha's question: use setNeedsStatusBarAppearanceUpdate. This will make a call to prefersStatusBarHidden to refresh with your desired status bar state. Try this:
@property (nonatomic, getter=isHideStatusBar) BOOL hideStatusBar; // Give this a default value early
- (BOOL)prefersStatusBarHidden {
return self.isHideStatusBar;
}
- (void)someMethod {
// triggered by an event or user action
[self setHideStatusBar:YES];
[self setNeedsStatusBarAppearanceUpdate];
}
If you want to see the status bar again, set your property hideStatusBar (or whatever you call it) to NO. Call preferStatusBarHidden indirectly by making another call to
[self setNeedsStatusBarAppearanceUpdate]
The solution
angular.element(document.getElementById('ID')).scope().get()
stopped working for me in angular 1.5.2. Sombody mention in a comment that this doesn't work in 1.4.9 also.
I fixed it by storing the scope in a global variable:
var scopeHolder;
angular.module('fooApp').controller('appCtrl', function ($scope) {
$scope = function bar(){
console.log("foo");
};
scopeHolder = $scope;
})
call from custom code:
scopeHolder.bar()
if you wants to restrict the scope to only this method. To minimize the exposure of whole scope. use following technique.
var scopeHolder;
angular.module('fooApp').controller('appCtrl', function ($scope) {
$scope.bar = function(){
console.log("foo");
};
scopeHolder = $scope.bar;
})
call from custom code:
scopeHolder()
I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.
It's a trade off !
pros of each one :
To remove the license key:
In my case on a Windows 7 machine I could find this license key in C:\Users\you\.IntelliJIdea13\config\idea13.key
Here is an appendTo version using the html dropdown you mentioned. It inserts another row on "change".
$('#dropdown').on( 'change', function(e) {
$('#table').append('<tr><td>COL1</td><td>COL2</td></tr>');
});
With an example for you to play with. Best of luck!
I actually like MY JavaScript files to be validated, but I definitely don't want to validate and deal with trivial warnings with third party libraries.
That's why I think that turning off validation all together is too drastic. Fortunately with Eclipse, you can selectively remove some JavaScript sources from validation.
Excluded
pattern.Exclusion patterns
box.Browse
button to mention the JavaScript source by name.The information about JavaScript source inclusion/exclusion is saved into .settings/.jsdtscope
file. Do not forget to add it to your SCM.
Here is how configuration looks with jQuery files removed from validation:
Obviously it's a problem with your internet connection. Check, if you can reach http://repo.spring.io with your browser. If yes, check if you need to configure a proxy server. If no, you should contact your internet provider.
Here is the documentation, how you configure a proxy server for Maven: https://maven.apache.org/guides/mini/guide-proxies.html
Have you tried to overlay one gradient with a nearly-transparent opacity for the highlight on top of another image with an opaque opacity for the green gradient?
You need to use to_timestamp()
to convert your string to a proper timestamp
value:
to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
If your column is of type DATE
(which also supports seconds), you need to use to_date()
to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
To get this into a where
condition use the following:
select *
from TableA
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')
You never need to use to_timestamp()
on a column that is of type timestamp
.
@ECHO OFF
ECHO Welcome to my calculator!
ECHO What is the number you want to insert to find the sum?
SET /P Num1=
ECHO What is the second number?
SET /P Num2=
SET /A Ans=%Num1%+%Num2%
ECHO The sum is: %Ans%
PAUSE>NUL
It working 100% in safari..i tried
@media screen and (-webkit-min-device-pixel-ratio:0)
{
::i-block-chrome, Class Name {your styles}
}
Ubuntu 13.04
installed using software centre :
The location for mine is:
/etc/postgresql/9.1/main/postgresql.conf
If Color
is something that is specific to just Car
s then that is the way you would limit its scope. If you are going to have another Color
enum that other classes use then you might as well make it global (or at least outside Car
).
It makes no difference. If there is a global one then the local one is still used anyway as it is closer to the current scope. Note that if you define those function outside of the class definition then you'll need to explicitly specify Car::Color
in the function's interface.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1252"/>
<title>DIN A4 Page</title>
<style type="text/css">
@page { size: 21cm 29.7cm; margin: 2cm }
p { line-height: 120%; text-align: justify; background: transparent }
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat.
</p>
</body>
</html>
You have to override your ;
delimiter with something like $$
to avoid this kind of error.
After your function definition, you can set the delimiter back to ;
.
This should work:
DELIMITER $$
CREATE FUNCTION F_Dist3D (x1 decimal, y1 decimal)
RETURNS decimal
DETERMINISTIC
BEGIN
DECLARE dist decimal;
SET dist = SQRT(x1 - y1);
RETURN dist;
END$$
DELIMITER ;
Your code works for me. Here is my test case:
mysql> CREATE TABLE carmake (country ENUM('Canada', 'United States'));
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW CREATE TABLE carmake;
+---------+-------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+-------------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
`country` enum('Canada','United States') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+-------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia');
Query OK, 0 rows affected (0.53 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SHOW CREATE TABLE carmake;
+---------+--------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+--------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
`country` enum('Sweden','Malaysia') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+--------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
What error are you seeing?
FWIW this would also work:
ALTER TABLE carmake MODIFY COLUMN country ENUM('Sweden','Malaysia');
I would actually recommend a country table rather than enum column. You may have hundreds of countries which would make for a rather large and awkward enum.
EDIT: Now that I can see your error message:
ERROR 1265 (01000): Data truncated for column 'country' at row 1.
I suspect you have some values in your country column that do not appear in your ENUM
. What is the output of the following command?
SELECT DISTINCT country FROM carmake;
ANOTHER EDIT: What is the output of the following command?
SHOW VARIABLES LIKE 'sql_mode';
Is it STRICT_TRANS_TABLES
or STRICT_ALL_TABLES
? That could lead to an error, rather than the usual warning MySQL would give you in this situation.
YET ANOTHER EDIT: Ok, I now see that you definitely have values in the table that are not in the new ENUM
. The new ENUM
definition only allows 'Sweden'
and 'Malaysia'
. The table has 'USA'
, 'India'
and several others.
LAST EDIT (MAYBE): I think you're trying to do this:
ALTER TABLE carmake CHANGE country country ENUM('Italy', 'Germany', 'England', 'USA', 'France', 'South Korea', 'Australia', 'Spain', 'Czech Republic', 'Sweden', 'Malaysia') DEFAULT NULL;
The fundamental issue with your code is that you mix two APIs. Unfortunately online resources are not great at pointing this out, but there are two semaphore APIs on UNIX-like systems:
Looking at the code above you used semget() from the System V API and tried to post through sem_post() which comes from the POSIX API. It is not possible to mix them.
To decide which semaphore API you want you don't have so many great resources. The simple best is the "Unix Network Programming" by Stevens. The section that you probably interested in is in Vol #2.
These two APIs are surprisingly different. Both support the textbook style semaphores but there are a few good and bad points in the System V API worth mentioning:
You should have space characters at the start of fields ONLY where the space characters are part of the data. Excel will not strip off leading spaces. You will get unwanted spaces in your headings and data fields. Worse, the "
that should be "protecting" that line-break in the third column will be ignored because it is not at the start of the field.
If you have non-ASCII characters (encoded in UTF-8) in the file, you should have a UTF-8 BOM (3 bytes, hex EF BB BF
) at the start of the file. Otherwise Excel will interpret the data according to your locale's default encoding (e.g. cp1252) instead of utf-8, and your non-ASCII characters will be trashed.
Following comments apply to Excel 2003, 2007 and 2013; not tested on Excel 2000
If you open the file by double-clicking on its name in Windows Explorer, everything works OK.
If you open it from within Excel, the results vary:
Options include:
If it's any help to anyone, give permission to "IIS_IUSRS" group.
Note that if you can't find "IIS_IUSRS", try prepending it with your server's name, like "MySexyServer\IIS_IUSRS".
Or use this:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:scrollbars="vertical"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- Add your UI elements inside the inner most linear layout -->
</LinearLayout>
</ScrollView>
A lot of the times the implementation will exist in the same namespace as the interface. So, I came up with this:
public class InterfaceConverter : JsonConverter
{
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.ReadFrom(reader);
var typeVariable = this.GetTypeVariable(token);
if (TypeExtensions.TryParse(typeVariable, out var implimentation))
{ }
else if (!typeof(IEnumerable).IsAssignableFrom(objectType))
{
implimentation = this.GetImplimentedType(objectType);
}
else
{
var genericArgumentTypes = objectType.GetGenericArguments();
var innerType = genericArgumentTypes.FirstOrDefault();
if (innerType == null)
{
implimentation = typeof(IEnumerable);
}
else
{
Type genericType = null;
if (token.HasAny())
{
var firstItem = token[0];
var genericTypeVariable = this.GetTypeVariable(firstItem);
TypeExtensions.TryParse(genericTypeVariable, out genericType);
}
genericType = genericType ?? this.GetImplimentedType(innerType);
implimentation = typeof(IEnumerable<>);
implimentation = implimentation.MakeGenericType(genericType);
}
}
return JsonConvert.DeserializeObject(token.ToString(), implimentation);
}
public override bool CanConvert(Type objectType)
{
return !typeof(IEnumerable).IsAssignableFrom(objectType) && objectType.IsInterface || typeof(IEnumerable).IsAssignableFrom(objectType) && objectType.GetGenericArguments().Any(t => t.IsInterface);
}
protected Type GetImplimentedType(Type interfaceType)
{
if (!interfaceType.IsInterface)
{
return interfaceType;
}
var implimentationQualifiedName = interfaceType.AssemblyQualifiedName?.Replace(interfaceType.Name, interfaceType.Name.Substring(1));
return implimentationQualifiedName == null ? interfaceType : Type.GetType(implimentationQualifiedName) ?? interfaceType;
}
protected string GetTypeVariable(JToken token)
{
if (!token.HasAny())
{
return null;
}
return token.Type != JTokenType.Object ? null : token.Value<string>("$type");
}
}
Therefore, you can include this globally like so:
public static JsonSerializerSettings StandardSerializerSettings => new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new InterfaceConverter()
}
};
I've used MongoDB extensively (for the past 6 months), building a hierarchical data management system, and I can vouch for both the ease of setup (install it, run it, use it!) and the speed. As long as you think about indexes carefully, it can absolutely scream along, speed-wise.
I gather that Cassandra, due to its use with large-scale projects like Twitter, has better scaling functionality, although the MongoDB team is working on parity there. I should point out that I've not used Cassandra beyond the trial-run stage, so I can't speak for the detail.
The real swinger for me, when we were assessing NoSQL databases, was the querying - Cassandra is basically just a giant key/value store, and querying is a bit fiddly (at least compared to MongoDB), so for performance you'd have to duplicate quite a lot of data as a sort of manual index. MongoDB, on the other hand, uses a "query by example" model.
For example, say you've got a Collection (MongoDB parlance for the equivalent to a RDMS table) containing Users. MongoDB stores records as Documents, which are basically binary JSON objects. e.g:
{
FirstName: "John",
LastName: "Smith",
Email: "[email protected]",
Groups: ["Admin", "User", "SuperUser"]
}
If you wanted to find all of the users called Smith who have Admin rights, you'd just create a new document (at the admin console using Javascript, or in production using the language of your choice):
{
LastName: "Smith",
Groups: "Admin"
}
...and then run the query. That's it. There are added operators for comparisons, RegEx filtering etc, but it's all pretty simple, and the Wiki-based documentation is pretty good.
Besides the redundant )
this expression will always be true
because currentStatus
will always match one of these two conditions:
currentStatus !== 'open' || currentStatus !== 'reopen'
perhaps you mean one of
!(currentStatus === 'open' || currentStatus === 'reopen')
(currentStatus !== 'open' && currentStatus !== 'reopen')
Yet another approach - just set a flag on an element signaling which type of event should be handled:
function setRangeValueChangeHandler(rangeElement, handler) {
rangeElement.oninput = (event) => {
handler(event);
// Save flag that we are using onInput in current browser
event.target.onInputHasBeenCalled = true;
};
rangeElement.onchange = (event) => {
// Call only if we are not using onInput in current browser
if (!event.target.onInputHasBeenCalled) {
handler(event);
}
};
}
I had a similar issue. I added write permissions to the .bak file itself, and my folder that I was writing the backup to for the NETWORK SERVICE user. To add permissions just right-click what file/directory you want to alter, select the security tab, and add the appropriate users/permissions there.
svn:// doesn't talk http, therefor there's nothing a http proxy could do.
Any reason why http doesn't work? Have you considered https? If you really need it, you probably have to have port 3690 opened in your firewall.
You can easily use ng-show such as :
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div ng-show="isExists(item)">available</div>
<div ng-show="!isExists(item)">oh no, you don't have it</div>
</div>
For more complex tests, you can use ng-switch statements :
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div ng-switch on="isExists(item)">
<span ng-switch-when="true">Available</span>
<span ng-switch-default>oh no, you don't have it</span>
</div>
</div>
If you type:
?sample
If will launch a help menu to explain what the parameters of the sample function mean.
I am not an expert, but here is some code I have:
data <- data.frame(matrix(rnorm(400), nrow=100))
splitdata <- split(data[1:nrow(data),],sample(rep(1:4,as.integer(nrow(data)/4))))
test <- splitdata[[1]]
train <- rbind(splitdata[[1]],splitdata[[2]],splitdata[[3]])
This will give you 75% train and 25% test.
If you try to run
sudo -H pip3 install --upgrade pip3
you will get the following error:
WARNING: You are using pip version 19.2.3, however version 21.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
but if you upgrade using the suggested command:
pip install --upgrade pip
then, the legacy pip will be upgraded, so what I did is the following:
which pip3
and I located my pip3 installation (just in case the following command wouldn't upgrade the legacy pip. Then i changed to that directory and upgraded pip3 using the following commands: (your directory could be different)
cd /Library/Frameworks/Python.framework/Versions/3.8/bin
sudo -H pip3 install --upgrade pip
after this:
pip --version
will still show the legacy version, while
pip3 --version
will show pip 21.0.1
First download the exe file of the IEDriverServer (64 bit and 32 bit). Don't need to install, only download this file with your browser( 64 or 32 bit) and simply give the path of the exe file in the given code.
http://www.seleniumhq.org/download/
use this code
package myProject;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class Browserlaunch {
public static void main(String[] args) {
System.setProperty("webdriver.ie.driver", "C:/Drivers/IEDriverServer.exe");
InternetExplorerDriver IEDriver=new InternetExplorerDriver();
IEDriver.get("http://localhost:8888");
}
}
The keyCode
is deprecated you can use key
property in the KeyboardEvent
<textarea (keydown)=onKeydownEvent($event)></textarea>
Typescript:
onKeydownEvent($event: KeyboardEvent){
// you can use the following for checkig enter key pressed or not
if ($event.key === 'Enter') {
console.log($event.key); // Enter
}
if ($event.key === 'Enter' && event.shiftKey) {
//This is 'Shift+Enter'
}
}
Awesome tutorial: 3 Different Ways to Display Progress in an ASP.NET AJAX Application
Sign up for an account on as many major email providers as possible (gmail/yahoo/hotmail/aol/etc). If you make changes to your emails, either major rewording, changes to the code that sends the emails, changes to your email servers, etc, make sure to send test messages to all your accounts and verify that they are not being marked as spam.
Use the below code. This should work.
$comments = EmailArchive::find()->where(['email_id' => $id])->all();
You could use FindBin, Cwd, File::Basename, or a combination of them. They're all in the base distribution of Perl IIRC.
I used Cwd in the past:
Cwd:
use Cwd qw(abs_path);
my $path = abs_path($0);
print "$path\n";
1) Locate server.xml in {Tomcat installation folder}\ conf \ 2) Find following similar statement
<!-- Define a non-SSL HTTP/1.1 Connector on port 8180 -->
<Connector port="8080" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" />
For example
<Connector port="8181" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
Edit and save the server.xml file. Restart Tomcat. Done
Further reference: http://www.mkyong.com/tomcat/how-to-change-tomcat-default-port/
Yes you can solve this error by changing the port number of glassfish because the WAMP SERVER or ORACLE database software uses a port number 8080, so there is a conflict of port number.
1)open a path like C:\GlassFish_Server\glassfish\domains\domain1\config\domain.xml.
2)find out the 8080 port number with the help of ctrl+F. You will get the following code...
<network-listener protocol="http-listener-1" port="8080" name="http-listener-1" thread-pool="http-thread-pool" transport="tcp">
3) Change that port number from 8080 to 9090 or 1234 or whatever you like..
4) Save it. Open a Netbeans IDE goto the glassfish server .
5) Right click on the server -> select refresh option.
6) to check the port no. which is given by u just right click on the server-> property.
7) Start the Glassfish server . Yehhh the error is gone...
SynchronousQueue
( Taken from another question )SynchronousQueue
is more of a handoff, whereas the LinkedBlockingQueue
just allows a single element. The difference being that the put()
call to a SynchronousQueue
will not return until there is a corresponding take()
call, but with a LinkedBlockingQueue
of size 1, the put()
call (to an empty queue) will return immediately. It's essentially the BlockingQueue
implementation for when you don't really want a queue (you don't want to maintain any pending data).
LinkedBlockingQueue
(LinkedList
Implementation but Not Exactly JDK Implementation of LinkedList
It uses static inner class Node to maintain Links between elements )Constructor for LinkedBlockingQueue
public LinkedBlockingQueue(int capacity)
{
if (capacity < = 0) throw new IllegalArgumentException();
this.capacity = capacity;
last = head = new Node< E >(null); // Maintains a underlying linkedlist. ( Use when size is not known )
}
Node class Used to Maintain Links
static class Node<E> {
E item;
Node<E> next;
Node(E x) { item = x; }
}
3 . ArrayBlockingQueue ( Array Implementation )
Constructor for ArrayBlockingQueue
public ArrayBlockingQueue(int capacity, boolean fair)
{
if (capacity < = 0)
throw new IllegalArgumentException();
this.items = new Object[capacity]; // Maintains a underlying array
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
IMHO Biggest Difference between ArrayBlockingQueue
and LinkedBlockingQueue
is clear from constructor one has underlying data structure Array and other linkedList.
ArrayBlockingQueue
uses single-lock double condition algorithm and LinkedBlockingQueue
is variant of the "two lock queue" algorithm and it has 2 locks 2 conditions ( takeLock , putLock)
I finally was able to run datepicker directive in angular js , here are pointers
include following JS in order
I added the following
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"> </script>
in html code
<body ng-app="myApp" ng-controller="myController">
// some other html code
<input type="text" ng-model="date" mydatepicker />
<br/>
{{ date }}
//some other html code
</body>
in the js , make sure you code for the directive first and after that add the code for controller , else it will cause issues.
date picker directive :
var app = angular.module('myApp',[]);
app.directive('mydatepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
element.datepicker({
dateFormat: 'DD, d MM, yy',
onSelect: function (date) {
scope.date = date;
scope.$apply();
}
});
}
};
});
directive code referred from above answers.
After this directive , write the controller
app.controller('myController',function($scope){
//controller code
};
TRY THIS INSTEAD in angular js
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
along with jquery.js and jquery-ui.js
we can implement angular js datepicker as
<input type="date" ng-model="date" name="DOB">
This gives the built in datepicker and date is set in ng-model and can be used for further processing and validation.
Found this after lot of successful headbanging with previous approach. :)
As of HTML5 browsers one can use inputElement.form
- the value of the attribute must be an id of a <form>
element in the same document.
More info on MDN.
Here is how you can read the entire file contents, and if done successfully, start a webserver which displays the JPG image in response to every request:
var http = require('http')
var fs = require('fs')
fs.readFile('image.jpg', function(err, data) {
if (err) throw err // Fail if the file can't be read.
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'image/jpeg'})
res.end(data) // Send the file data to the browser.
}).listen(8124)
console.log('Server running at http://localhost:8124/')
})
Note that the server is launched by the "readFile" callback function and the response header has Content-Type: image/jpeg
.
[Edit] You could even embed the image in an HTML page directly by using an <img>
with a data URI source. For example:
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<html><body><img src="data:image/jpeg;base64,')
res.write(Buffer.from(data).toString('base64'));
res.end('"/></body></html>');
Found a solution:
mysql> UPDATE table SET last_update=now(), last_monitor=last_update WHERE id=1;
I found this in MySQL Docs and after a few tests it works:
the following statement sets col2 to the current (updated) col1 value, not the original col1 value. The result is that col1 and col2 have the same value. This behavior differs from standard SQL.
UPDATE t1 SET col1 = col1 + 1, col2 = col1;
break
or goto
while ( true ) {
if ( conditional ) {
break;
}
if ( other conditional ) {
goto EndWhile;
}
}
EndWhile:
the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.
Consider the following.
This creates and recreates a function f
that closes on i
, but different ones!:
i=100;_x000D_
_x000D_
f=function(i){return function(){return ++i}}(0);_x000D_
alert([f,f(),f(),f(),f(),f(),f(),f(),f(),f(),f()].join('\n\n'));_x000D_
_x000D_
f=function(i){return new Function('return ++i')}(0); /* function declarations ~= expressions! */_x000D_
alert([f,f(),f(),f(),f(),f(),f(),f(),f(),f(),f()].join('\n\n'));
_x000D_
while the following closes on "a" function "itself"
( themselves! the snippet after this uses a single referent f
)
for(var i = 0; i < 10; i++) {_x000D_
setTimeout( new Function('console.log('+i+')'), 1000 );_x000D_
}
_x000D_
or to be more explicit:
for(var i = 0; i < 10; i++) {_x000D_
console.log( f = new Function( 'console.log('+i+')' ) );_x000D_
setTimeout( f, 1000 );_x000D_
}
_x000D_
NB. the last definition of f
is function(){ console.log(9) }
before 0
is printed.
Caveat! The closure concept can be a coercive distraction from the essence of elementary programming:
for(var i = 0; i < 10; i++) { setTimeout( 'console.log('+i+')', 1000 ); }
_x000D_
x-refs.:
How do JavaScript closures work?
Javascript Closures Explanation
Does a (JS) Closure Require a Function Inside a Function
How to understand closures in Javascript?
Javascript local and global variable confusion
For an incoming request like /v1/location/1234
, as you can imagine it would be difficult for Web API to automatically figure out if the value of the segment corresponding to '1234' is related to appid
and not to deviceid
.
I think you should change your route template to be like
[Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]
and then parse the deiveOrAppid
to figure out the type of id.
Also you need to make the segments in the route template itself optional otherwise the segments are considered as required. Note the ?
character in this case.
For example:
[Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]
The combo you need is
white-space: nowrap
on the parent and
display: inline-block; // or inline
on the children
Try this:
sed -i 's/subdomainA/subdomainB/g' `grep -ril 'subdomainA' *`
The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be:
Object.size = function(obj) {
var size = 0,
key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
// Get the size of an object
const myObj = {}
var size = Object.size(myObj);
_x000D_
There's a sort of convention in JavaScript that you don't add things to Object.prototype, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.
Here's an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, you can use Object.keys()
so the above code just becomes:
var size = Object.keys(myObj).length;
This doesn't have to modify any existing prototype since Object.keys()
is now built-in.
Edit: Objects can have symbolic properties that can not be returned via Object.key method. So the answer would be incomplete without mentioning them.
Symbol type was added to the language to create unique identifiers for object properties. The main benefit of the Symbol type is the prevention of overwrites.
Object.keys
or Object.getOwnPropertyNames
does not work for symbolic properties. To return them you need to use Object.getOwnPropertySymbols
.
var person = {
[Symbol('name')]: 'John Doe',
[Symbol('age')]: 33,
"occupation": "Programmer"
};
const propOwn = Object.getOwnPropertyNames(person);
console.log(propOwn.length); // 1
let propSymb = Object.getOwnPropertySymbols(person);
console.log(propSymb.length); // 2
_x000D_
If older browser support is a must, so you can't go with multiple backgrounds or gradients, you're probably going to want to do something like this on a spare div
element:
#background {
position: fixed;
top: 0;
left: 0;
width: 50%;
height: 100%;
background-color: pink;
}
Example: http://jsfiddle.net/PLfLW/1704/
The solution uses an extra fixed div that fills half the screen. Since it's fixed, it will remain in position even when your users scroll. You may have to fiddle with some z-indexes later, to make sure your other elements are above the background div, but it shouldn't be too complex.
If you have issues, just make sure the rest of your content has a z-index higher than the background element and you should be good to go.
If newer browsers are your only concern, there are a couple other methods you can use:
Linear Gradient:
This is definitely the easiest solution. You can use a linear-gradient in the background property of the body for a variety of effects.
body {
height: 100%;
background: linear-gradient(90deg, #FFC0CB 50%, #00FFFF 50%);
}
This causes a hard cutoff at 50% for each color, so there isn't a "gradient" as the name implies. Try experimenting with the "50%" piece of the style to see the different effects you can achieve.
Example: http://jsfiddle.net/v14m59pq/2/
Multiple Backgrounds with background-size:
You can apply a background color to the html
element, and then apply a background-image to the body
element and use the background-size
property to set it to 50% of the page width. This results in a similar effect, though would really only be used over gradients if you happen to be using an image or two.
html {
height: 100%;
background-color: cyan;
}
body {
height: 100%;
background-image: url('http://i.imgur.com/9HMnxKs.png');
background-repeat: repeat-y;
background-size: 50% auto;
}
Example: http://jsfiddle.net/6vhshyxg/2/
EXTRA NOTE: Notice that both the html
and body
elements are set to height: 100%
in the latter examples. This is to make sure that even if your content is smaller than the page, the background will be at least the height of the user's viewport. Without the explicit height, the background effect will only go down as far as your page content. It's also just a good practice in general.
Got this issue on returning to an Eclipse project on a VM after leaving it untouched for maybe a couple of weeks.
I started to apply the accepted answer, but when I got to the step of renaming the folder and had exited Eclipse, I saw there was an instance of Eclipse still running. I realized Windows had for some reason started a second instance of Eclipse when I hit the taskbar button. The second instance had been unable to access the workspace while the first instance was using it.
Once I undid my folder rename, and closed and restarted the original instance of Eclipse, I was able to use File->Switch Workspace to get my normal workspace back.
The problem is that you forgot to import os. Add this line of code:
import os
And everything should be fine. Hope this helps!
With Bootstrap >4.1 it's just a case of using the flexbox utility classes. Just have a flexbox container inside your column, and then give all the elements within it the "flex-fill" class. As with inline forms you'll need to set the margins/padding on the elements yourself.
.prop-label {_x000D_
margin: .25rem 0 !important;_x000D_
}_x000D_
_x000D_
.prop-field {_x000D_
margin-left: 1rem;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row">_x000D_
<div class="col-12">_x000D_
<div class="d-flex">_x000D_
<label class="flex-fill prop-label">Label:</label>_x000D_
<input type="text" class="flex-fill form-control prop-field">_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
As Johannes pointed out,
for c in "string":
#do something with c
You can iterate pretty much anything in python using the for loop
construct,
for example, open("file.txt")
returns a file object (and opens the file), iterating over it iterates over lines in that file
with open(filename) as f:
for line in f:
# do something with line
If that seems like magic, well it kinda is, but the idea behind it is really simple.
There's a simple iterator protocol that can be applied to any kind of object to make the for
loop work on it.
Simply implement an iterator that defines a next()
method, and implement an __iter__
method on a class to make it iterable. (the __iter__
of course, should return an iterator object, that is, an object that defines next()
)
To refresh the whole page, but it works normally:
Response.Redirect(url,bool)
From the man page:
-i When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command. It does not read the $PYTHONSTARTUP file. This can be useful to inspect global variables or a stack trace when a script raises an exception.
So this should do what you want:
python -i file.py
For a new document: Settings -> Preferences -> New Document/Default Directory
-> New Document -> Format -> Windows/Mac/Unix
And for an already-open document: Edit -> EOL Conversion
I recently ran into this error on Windows 10. It turned out that windows was looking for .dll files necessary for my project and couldn't find them because it looks for them in the system path, PATH, rather than the CLASSPATH or -Djava.library.path
//xn=list of parent nodes......
foreach (XmlNode xn in xnList)
{
foreach (XmlNode child in xn.ChildNodes)
{
if (child.Name.Equals("name"))
{
name = child.InnerText;
}
if (child.Name.Equals("age"))
{
age = child.InnerText;
}
}
}
=counta(range)
counta
: "Returns a count of the number of values in a dataset"
Note: CountA
considers ""
to be a value. Only cells that are blank (press delete in a cell to blank it) are not counted.
Google support: https://support.google.com/docs/answer/3093991
countblank
: "Returns the number of empty cells in a given range"
Note: CountBlank
considers both blank cells (press delete to blank a cell) and cells that have a formula that returns ""
to be empty cells.
Google Support: https://support.google.com/docs/answer/3093403
If you have a range that includes formulae that result in ""
, then you can modify your formula from
=counta(range)
to:
=Counta(range) - Countblank(range)
EDIT: the function is countblank
, not countblanks
, the latter will give an error.
inspired by @newacct's answer, a code that can be compiled in any platform:
String osName = System.getProperty( "os.name" ).toLowerCase();
String className = null;
String methodName = "getUsername";
if( osName.contains( "windows" ) ){
className = "com.sun.security.auth.module.NTSystem";
methodName = "getName";
}
else if( osName.contains( "linux" ) ){
className = "com.sun.security.auth.module.UnixSystem";
}
else if( osName.contains( "solaris" ) || osName.contains( "sunos" ) ){
className = "com.sun.security.auth.module.SolarisSystem";
}
if( className != null ){
Class<?> c = Class.forName( className );
Method method = c.getDeclaredMethod( methodName );
Object o = c.newInstance();
System.out.println( method.invoke( o ) );
}
I stumbled upon the same problem: a page with many independent animations, each one with its own parameters, which must be repeated forever.
Merging this clue with this other clue I found an easy solution: after the end of all your animations the wrapping div
is restored, forcing the animations to restart.
All you have to do is to add these few lines of Javascript, so easy they don't even need any external library, in the <head>
section of your page:
<script>
setInterval(function(){
var container = document.getElementById('content');
var tmp = container.innerHTML;
container.innerHTML= tmp;
}, 35000 // length of the whole show in milliseconds
);
</script>
BTW, the closing </head>
in your code is misplaced: it must be before the starting <body>
.