I had a similar problem which I solved by changing the Port Settings in the port driver (located in Ports in device manager) to fit the device I was using.
For me it was that wrong Bits per second value was set.
The no-op command in shell is :
(colon).
if [ "$a" -ge 10 ]
then
:
elif [ "$a" -le 5 ]
then
echo "1"
else
echo "2"
fi
From the bash manual:
:
(a colon)
Do nothing beyond expanding arguments and performing redirections. The return status is zero.
I had to go through this process myself and chose a different way that I think is better in the long run.
I installed homebrew
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
then:
brew doctor
The last step gives you some warnings and errors that you have to resolve. One of those will be to download and install the Mac OS X command-line tools.
then:
brew install python3
This gave me python3
and pip3
in my path.
pieter$ which pip3 python3
/usr/local/bin/pip3
/usr/local/bin/python3
I struggled a bit with the answers on this question and didn't have much luck with the answers in a similar SO post either. So this is what worked for me - bearing in mind that in my case, the submodule was maintained by a different team, so the conflict came from different submodule versions in master and my local branch of the project I was working on:
git status
- make a note of the submodule folder with conflictsReset the submodule to the version that was last committed in the current branch:
git reset HEAD path/to/submodule
At this point, you have a conflict-free version of your submodule which you can now update to the latest version in the submodule's repository:
cd path/to/submodule git submodule foreach git pull origin SUBMODULE-BRANCH-NAME
And now you can commit
that and get back to work.
Left bit shifting to multiply by any power of two. Right bit shifting to divide by any power of two.
x = x << 5; // Left shift
y = y >> 5; // Right shift
In C/C++ it can be written as,
#include <math.h>
x = x * pow(2, 5);
y = y / pow(2, 5);
isset() is used to check if the variable is set with the value or not and Empty() is used to check if a given variable is empty or not.
isset() returns true when the variable is not null whereas Empty() returns true if the variable is an empty string.
Lambda expression can be passed as a argument.To pass a lambda expression as an argument the type of the parameter (which receives the lambda expression as an argument) must be of functional interface type.
If there is a functional interface -
interface IMyFunc {
boolean test(int num);
}
And there is a filter method which adds the int in the list only if it is greater than 5. Note here that filter method has funtional interface IMyFunc as one of the parameter. In that case lambda expression can be passed as an argument for the method parameter.
public class LambdaDemo {
public static List<Integer> filter(IMyFunc testNum, List<Integer> listItems) {
List<Integer> result = new ArrayList<Integer>();
for(Integer item: listItems) {
if(testNum.test(item)) {
result.add(item);
}
}
return result;
}
public static void main(String[] args) {
List<Integer> myList = new ArrayList<Integer>();
myList.add(1);
myList.add(4);
myList.add(6);
myList.add(7);
// calling filter method with a lambda expression
// as one of the param
Collection<Integer> values = filter(n -> n > 5, myList);
System.out.println("Filtered values " + values);
}
}
Add "bDestroy": true in your dataTable Like:-
$('#example').dataTable({
....
stateSave: true,
"bDestroy": true
});
It Will Work.
import copy
a = ["a", "b", "c", "d", "e"]
b = copy.copy(a)
for item in a:
print item
b.remove(item)
a = copy.copy(b)
Works: to avoid changing the list you are iterating on, you make a copy of a
, iterate over it and remove the items from b
. Then you copy b
(the altered copy) back to a
.
gb = df.groupby(['A'])
gb_groups = grouped_df.groups
If you are looking for selective groupby objects then, do: gb_groups.keys(), and input desired key into the following key_list..
gb_groups.keys()
key_list = [key1, key2, key3 and so on...]
for key, values in gb_groups.iteritems():
if key in key_list:
print df.ix[values], "\n"
Just throwing this out there...Can't you just do:
Collections.sort(myarrayList);
It's been awhile though...
IF vertical align won't work use padding.
padding-top: 10px;
it will shift the text to the bottom or
padding-bottom: 10px;
to shift the text in the text box to top
adjust the padding size till it suit the size you want. Thats the hack
It's pretty simple, take a look at the code below:
The form:
<form action="result.php" method="post">
Answer 1 <input type="radio" name="ans" value="ans1" /><br />
Answer 2 <input type="radio" name="ans" value="ans2" /><br />
Answer 3 <input type="radio" name="ans" value="ans3" /><br />
Answer 4 <input type="radio" name="ans" value="ans4" /><br />
<input type="submit" value="submit" />
</form>
PHP code:
<?php
$answer = $_POST['ans'];
if ($answer == "ans1") {
echo 'Correct';
}
else {
echo 'Incorrect';
}
?>
This can happen if disableContentCompression()
is set on a pooling manager assigned to your HttpClient, and the target server is trying to use gzip compression.
mmap
is great if you have multiple processes accessing data in a read only fashion from the same file, which is common in the kind of server systems I write. mmap
allows all those processes to share the same physical memory pages, saving a lot of memory.
mmap
also allows the operating system to optimize paging operations. For example, consider two programs; program A
which reads in a 1MB
file into a buffer creating with malloc
, and program B which mmaps
the 1MB file into memory. If the operating system has to swap part of A
's memory out, it must write the contents of the buffer to swap before it can reuse the memory. In B
's case any unmodified mmap
'd pages can be reused immediately because the OS knows how to restore them from the existing file they were mmap
'd from. (The OS can detect which pages are unmodified by initially marking writable mmap
'd pages as read only and catching seg faults, similar to Copy on Write strategy).
mmap
is also useful for inter process communication. You can mmap
a file as read / write in the processes that need to communicate and then use synchronization primitives in the mmap'd
region (this is what the MAP_HASSEMAPHORE
flag is for).
One place mmap
can be awkward is if you need to work with very large files on a 32 bit machine. This is because mmap
has to find a contiguous block of addresses in your process's address space that is large enough to fit the entire range of the file being mapped. This can become a problem if your address space becomes fragmented, where you might have 2 GB of address space free, but no individual range of it can fit a 1 GB file mapping. In this case you may have to map the file in smaller chunks than you would like to make it fit.
Another potential awkwardness with mmap
as a replacement for read / write is that you have to start your mapping on offsets of the page size. If you just want to get some data at offset X
you will need to fixup that offset so it's compatible with mmap
.
And finally, read / write are the only way you can work with some types of files. mmap
can't be used on things like pipes and ttys.
From your original code it looks like what you want is to check if the list was empty:
var getResult= keyValueList.SingleOrDefault();
if (keyValueList.Count == 0)
{
/* default */
}
else
{
}
Try adding the style
element to the head
rather than the body
.
This was tested in IE (7-9), Firefox, Opera and Chrome:
var css = 'h1 { background: red; }',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
head.appendChild(style);
style.type = 'text/css';
if (style.styleSheet){
// This is required for IE8 and below.
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
A good way to force your CSS to reload is to:
<link href='styles.css?version=1' rel='stylesheet'></link>
And then just increment the version number as you change your CSS. The browser will then obey. I believe StackOverflow uses this technique.
Using Twitter Bootstrap classes may be the best choice :
pull-left
makes an element floating leftclearfix
allows the element to contain floating elements (if not already set via another class)<div class="paragraphs">
<div class="row">
<div class="span4">
<div class="clearfix content-heading">
<img class="pull-left" src="../site/img/success32.png"/>
<h3>Experience   </h3>
</div>
<p>Donec id elit non mi porta gravida at eget metus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.</p>
</div>
</div>
</div>
Using join
:
join -t $'\t' -o 1.2,1.1 file.txt file.txt
Notes:
-t $'\t'
In GNU join
the more intuitive -t '\t'
without the $
fails, (coreutils v8.28 and earlier?); it's probably a bug that a workaround like $
should be necessary. See: unix join separator char.
join
needs two filenames, even though there's just one file being worked on. Using the same name twice tricks join
into performing the desired action.
For systems with low resources join
offers a smaller footprint than some of the tools used in other answers:
wc -c $(realpath `which cut join sed awk perl`) | head -n -1
43224 /usr/bin/cut
47320 /usr/bin/join
109840 /bin/sed
658072 /usr/bin/gawk
2093624 /usr/bin/perl
Adding to a_horse_with_no_name's answer you might find the following of interest...
it does not make any difference whether you declare a column as VARCHAR(100) or VACHAR(500).
-- try to create a table with max varchar length
drop table if exists foo;
create table foo(name varchar(65535) not null)engine=innodb;
MySQL Database Error: Row size too large.
-- try to create a table with max varchar length - 2 bytes for the length
drop table if exists foo;
create table foo(name varchar(65533) not null)engine=innodb;
Executed Successfully
-- try to create a table with max varchar length with nullable field
drop table if exists foo;
create table foo(name varchar(65533))engine=innodb;
MySQL Database Error: Row size too large.
-- try to create a table with max varchar length with nullable field
drop table if exists foo;
create table foo(name varchar(65532))engine=innodb;
Executed Successfully
Dont forget the length byte(s) and the nullable byte so:
name varchar(100) not null
will be 1 byte (length) + up to 100 chars (latin1)
name varchar(500) not null
will be 2 bytes (length) + up to 500 chars (latin1)
name varchar(65533) not null
will be 2 bytes (length) + up to 65533 chars (latin1)
name varchar(65532)
will be 2 bytes (length) + up to 65532 chars (latin1) + 1 null byte
Hope this helps :)
You can check out this post on SuperUser.
Word starts page numbering over for each new section by default.
I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.
My method:
Format Page Numbers
Continue from Previous Section
radio button under Page numbering
I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.
Just add the missing prototype constructor to all SVG nodes:
SVGElement.prototype.hasClass = function (className) {
return new RegExp('(\\s|^)' + className + '(\\s|$)').test(this.getAttribute('class'));
};
SVGElement.prototype.addClass = function (className) {
if (!this.hasClass(className)) {
this.setAttribute('class', this.getAttribute('class') + ' ' + className);
}
};
SVGElement.prototype.removeClass = function (className) {
var removedClass = this.getAttribute('class').replace(new RegExp('(\\s|^)' + className + '(\\s|$)', 'g'), '$2');
if (this.hasClass(className)) {
this.setAttribute('class', removedClass);
}
};
You can then use it this way without requiring jQuery:
this.addClass('clicked');
this.removeClass('clicked');
All credit goes to Todd Moto.
I am facing the same issue, I am able to hide android keyboard even focus is in textbox by just adding one css property
<input type="text" style="pointer-events:none" />
and it works fine...
Basically it should be
<textarea>something here with no spaces in the begining</textarea>
If there are some predefined spaces lets say due to code formatting like below
<textarea>.......
....some_variable
</textarea>
The spaces shown by dots keeps on adding on each submit.
This is INTERNET error
So, Create a SQUID Proxy Server
1. install android studio
2. setup proxy settings in android studio
3. uninstall android studio and keep user settings
4. install android studio again
5. after finish first setup, then android must detect proxy settings automatically and setup SDK
6. after finish sdk configs, then create your first project
7. confirm proxy settings dialog for first time
XPath 1.0, which is what MS implements, does not have the idea of a default namespace. So try this:
XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable());
xnm.AddNamespace("x", "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/x:Report/x:ReportInfo/x:Name", xnm) == null);
FYI: it looks like you might have an infinite loop in your example...
if cnt > 0 and len(aStr) > 1:
while cnt > 0:
aStr = aStr[1:]+aStr[0]
cnt += 1
cnt
is greater than 0cnt
is greater than 0cnt
by 1The net result is that cnt
will always be greater than 0 and the loop will never exit.
Copy the file into your src folder. Go to the Project Explorer in Eclipse, Right-click on your project, and click on "Refresh". The file should appear on the Project Explorer pane as well.
1) local simplest methods
<?php
echo readfile("http://example.com/"); //needs "Allow_url_include" enabled
//OR
echo include("http://example.com/"); //needs "Allow_url_include" enabled
//OR
echo file_get_contents("http://example.com/");
//OR
echo stream_get_contents(fopen('http://example.com/', "rb")); //you may use "r" instead of "rb" //needs "Allow_url_fopen" enabled
?>
2) Better Way is CURL:
echo get_remote_data('http://example.com'); // GET request
echo get_remote_data('http://example.com', "var2=something&var3=blabla" ); // POST request
It automatically handles FOLLOWLOCATION problem + Remote urls:
src="./imageblabla.png"
turned into:src="http://example.com/path/imageblabla.png"
Code : https://github.com/tazotodua/useful-php-scripts/blob/master/get-remote-url-content-data.php
In this line:
for name, email, lastname in unpaidMembers.items():
unpaidMembers.items()
must have only two values per iteration.
Here is a small example to illustrate the problem:
This will work:
for alpha, beta, delta in [("first", "second", "third")]:
print("alpha:", alpha, "beta:", beta, "delta:", delta)
This will fail, and is what your code does:
for alpha, beta, delta in [("first", "second")]:
print("alpha:", alpha, "beta:", beta, "delta:", delta)
In this last example, what value in the list is assigned to delta
? Nothing, There aren't enough values, and that is the problem.
Yes, add it to the php.ini, restart apache and it should work.
You can test it on the fly if you want to with ini_set("max_input_vars",100)
There are two storage areas involved: the stack and the heap.The stack is where the current state of a method call is kept (ie local variables and references), and the heap is where objects are stored. recursion and memory
I gues there are too many keys in the counter
dict that will consume too much memory of the heap region, so the Python runtime will raise a OutOfMemory exception.
To save it, don't create a giant object, e.g. the counter.
1.StackOverflow
a program that create too many local variables.
Python 2.7.9 (default, Mar 1 2015, 12:57:24)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('stack_overflow.py','w')
>>> f.write('def foo():\n')
>>> for x in xrange(10000000):
... f.write('\tx%d = %d\n' % (x, x))
...
>>> f.write('foo()')
>>> f.close()
>>> execfile('stack_overflow.py')
Killed
2.OutOfMemory
a program that creats a giant dict
includes too many keys.
>>> f = open('out_of_memory.py','w')
>>> f.write('def foo():\n')
>>> f.write('\tcounter = {}\n')
>>> for x in xrange(10000000):
... f.write('counter[%d] = %d\n' % (x, x))
...
>>> f.write('foo()\n')
>>> f.close()
>>> execfile('out_of_memory.py')
Killed
Another alternative is to use the heatmap function in seaborn to plot the covariance. This example uses the Auto data set from the ISLR package in R (the same as in the example you showed).
import pandas.rpy.common as com
import seaborn as sns
%matplotlib inline
# load the R package ISLR
infert = com.importr("ISLR")
# load the Auto dataset
auto_df = com.load_data('Auto')
# calculate the correlation matrix
corr = auto_df.corr()
# plot the heatmap
sns.heatmap(corr,
xticklabels=corr.columns,
yticklabels=corr.columns)
If you wanted to be even more fancy, you can use Pandas Style, for example:
cmap = cmap=sns.diverging_palette(5, 250, as_cmap=True)
def magnify():
return [dict(selector="th",
props=[("font-size", "7pt")]),
dict(selector="td",
props=[('padding', "0em 0em")]),
dict(selector="th:hover",
props=[("font-size", "12pt")]),
dict(selector="tr:hover td:hover",
props=[('max-width', '200px'),
('font-size', '12pt')])
]
corr.style.background_gradient(cmap, axis=1)\
.set_properties(**{'max-width': '80px', 'font-size': '10pt'})\
.set_caption("Hover to magify")\
.set_precision(2)\
.set_table_styles(magnify())
Something like:
File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
The easiest way to send (simulate) KeyStrokes to any window is to use the SendKeys.Send method of .NET Framework.
Checkout this very intuitive MSDN article http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx
Particularly for your case, if your browser window is in focus, sending F5 would just involve the following line of code:
SendKeys.Send("{F5}");
Matlab and Scilab languages offer a simpler and more elegant syntax than Python for the question you're asking, so I think the best you can do is to mimic Matlab/Scilab by using the Numpy package in Python. By doing this the solution to your problem is very concise and elegant:
from numpy import *
property_a = array([545., 656., 5.4, 33.])
property_b = array([ 1.2, 1.3, 2.3, 0.3])
good_objects = [True, False, False, True]
good_indices = [0, 3]
property_asel = property_a[good_objects]
property_bsel = property_b[good_indices]
Numpy tries to mimic Matlab/Scilab but it comes at a cost: you need to declare every list with the keyword "array", something which will overload your script (this problem doesn't exist with Matlab/Scilab). Note that this solution is restricted to arrays of number, which is the case in your example.
Use the mapfile
command:
mapfile -t myArray < file.txt
The error is using for
-- the idiomatic way to loop over lines of a file is:
while IFS= read -r line; do echo ">>$line<<"; done < file.txt
See BashFAQ/005 for more details.
Simple.... use tapku library.... you can google that word and use it... its open source... enjoy..... no need of bugging with those codes....
From the official angular documentation
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
As you can see first parameter for error callback is data an status is second.
For example, your remote host is example.com and remote login name is user1:
scp [email protected]:/path/to/file /path/to/store/file
You can't update it. What you can do is uninstall the cordova plugin and add it again.
cordova plugin rm https://github.com/apache/cordova-plugin-camera --save
cordova plugin add https://github.com/apache/cordova-plugin-camera --save
public ArrayList divineCast(String object) {
try
{
Integer result = Integer.parseInt(object);
ArrayList<Integer> generic = new ArrayList<Integer>();
generic.add(result);
return generic;
}
catch(Exception e)
{
//not a Integer
}
try
{
Float result = Float.parseFloat(object);
ArrayList<Float> generic = new ArrayList<Float>();
generic.add(result);
return generic;
}
catch(Exception e)
{
//not a Float
}
try
{
Double result = Double.parseDouble(object);
ArrayList<Double> generic = new ArrayList<Double>();
generic.add(result);
return generic;
}
catch(Exception e)
{
//not a double
}
try
{
Boolean result = Boolean.parseBoolean(object);
ArrayList<Boolean> generic = new ArrayList<Boolean>();
generic.add(result);
return generic;
}
catch(Exception e)
{
//not a Boolean
}
try
{
String result = String.valueOf(object);
ArrayList<String> generic = new ArrayList<String>();
generic.add(result);
return generic;
}
catch(Exception e)
{
//not a String
}
return null;
}
Then you can call then function as so
String test1 = "0.90854938";
String test2 = "true";
System.out.println(divineCast(test1).get(0));
System.out.println(divineCast(test1).get(0).getClass());
System.out.println(divineCast(test2).get(0));
System.out.println(divineCast(test2).get(0).getClass());
Java doesn't force you to declare the type of ArrayList you are returning in the function declaration, so you can return an ArrayList of any type.
I got the error when building an R package (using roxygen2)
The cause in my case was that I had saved data/mydata.RData
with saveRDS()
rather than save()
. E.g. save(iris, file="data/iris.RData")
This fixed the issue for me. I found this info here
Also note that with save()
/ load()
the object is loaded in with the same name it is initially saved with (i.e you can't rename it until it's already loaded into the R environment under the name it had when you initially saved it).
I would use a two file setup like this:
index.php
<?php
session_start();
define('DS', TRUE); // used to protect includes
define('USERNAME', $_SESSION['username']);
define('SELF', $_SERVER['PHP_SELF'] );
if (!USERNAME or isset($_GET['logout']))
include('login.php');
// everything below will show after correct login
?>
login.php
<?php defined('DS') OR die('No direct access allowed.');
$users = array(
"user" => "userpass"
);
if(isset($_GET['logout'])) {
$_SESSION['username'] = '';
header('Location: ' . $_SERVER['PHP_SELF']);
}
if(isset($_POST['username'])) {
if($users[$_POST['username']] !== NULL && $users[$_POST['username']] == $_POST['password']) {
$_SESSION['username'] = $_POST['username'];
header('Location: ' . $_SERVER['PHP_SELF']);
}else {
//invalid login
echo "<p>error logging in</p>";
}
}
echo '<form method="post" action="'.SELF.'">
<h2>Login</h2>
<p><label for="username">Username</label> <input type="text" id="username" name="username" value="" /></p>
<p><label for="password">Password</label> <input type="password" id="password" name="password" value="" /></p>
<p><input type="submit" name="submit" value="Login" class="button"/></p>
</form>';
exit;
?>
The following adds elements to a list in a loop.
l<-c()
i=1
while(i<100) {
b<-i
l<-c(l,b)
i=i+1
}
I will throw one more solution into the mix. I downloaded a sample app and it was crimping only on this taglib. Turns out it didn't care for the single quotes around the attributes.
<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
Once I changed those and made sure jstl.jar was in the web app, i was good to go.
If you use performSelectorInBackground:withObject:
to spawn a new thread, then the performed selector is responsible for setting up the new thread's autorelease pool, run loop and other configuration details – see "Using NSObject to Spawn a Thread" in Apple's Threading Programming Guide.
You'd probably be better off using Grand Central Dispatch, though:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self getResultSetFromDB:docids];
});
GCD is a newer technology, and is more efficient in terms of memory overhead and lines of code.
Updated with a hat tip to Chris Nolet, who suggested a change that makes the above code simpler and keeps up with Apple's latest GCD code examples.
There is a library for this BarCode PHP. You just need to include a few files:
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
You can generate many types of barcodes, namely 1D or 2D. Add the required library:
require_once('class/BCGcode39.barcode.php');
Generate the colours:
// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);
After you have added all the codes, you will get this way:
Example
Since several have asked for an example here is what I was able to do to get it done
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
require_once('class/BCGcode128.barcode.php');
header('Content-Type: image/png');
$color_white = new BCGColor(255, 255, 255);
$code = new BCGcode128();
$code->parse('HELLO');
$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);
$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
If you want to actually create the image file so you can save it then change
$drawing = new BCGDrawing('', $color_white);
to
$drawing = new BCGDrawing('image.png', $color_white);
In my case(my machine is ubuntu 16), I append /etc/resolvconf/resolv.conf.d/base
file by adding below ns lines.
nameserver 8.8.8.8
nameserver 4.2.2.1
nameserver 2001:4860:4860::8844
nameserver 2001:4860:4860::8888
then run the update script,
resolvconf -u
Also as a side note: Mootools has the function toInt() which is used on any native string (or float (or integer)).
"2".toInt() // 2
"2px".toInt() // 2
2.toInt() // 2
I can do like that (sorry it's c# not java but it's not a problem...) :
private int iValue = 1234567890;
function void MyTest()
{
Intent oIntent = new Intent (this, typeof(Camera2Activity));
Bundle oBundle = new Bundle();
oBundle.PutInt("MYVALUE", iValue); //=> 1234567890
oIntent.PutExtras (oBundle);
iRequestCode = 1111;
StartActivityForResult (oIntent, 1111);
}
AND IN YOUR ACTIVITY FOR RESULT
private int iValue = 0;
protected override void OnCreate(Bundle bundle)
{
Bundle oBundle = Intent.Extras;
if (oBundle != null)
{
iValue = oBundle.GetInt("MYVALUE", 0);
//=>1234567890
}
}
private void FinishActivity(bool bResult)
{
Intent oIntent = new Intent();
Bundle oBundle = new Bundle();
oBundle.PutInt("MYVALUE", iValue);//=>1234567890
oIntent.PutExtras(oBundle);
if (bResult)
{
SetResult (Result.Ok, oIntent);
}
else
SetResult(Result.Canceled, oIntent);
GC.Collect();
Finish();
}
FINALLY
protected override void OnActivityResult(int iRequestCode, Android.App.Result oResultCode, Intent oIntent)
{
base.OnActivityResult (iRequestCode, oResultCode, oIntent);
iValue = oIntent.Extras.GetInt("MYVALUE", -1); //=> 1234567890
}
I have several JDK (1.4, 1.5, 1.6) installed in C:\Java
with their JREs. Then I let Sun update the public JRE in C:\Program Files\Java
.
Lately there is an improvement, installing in jre6. Previously, there was a different folder per new version (1.5.0_4, 1.5.0_5, etc.), which was taking lot of space
On my machine using Node.js, I ran the following:
console.log('Testing Array:');
console.time('using[]');
for(var i=0; i<200000000; i++){var arr = []};
console.timeEnd('using[]');
console.time('using new');
for(var i=0; i<200000000; i++){var arr = new Array};
console.timeEnd('using new');
console.log('Testing Object:');
console.time('using{}');
for(var i=0; i<200000000; i++){var obj = {}};
console.timeEnd('using{}');
console.time('using new');
for(var i=0; i<200000000; i++){var obj = new Object};
console.timeEnd('using new');
Note, this is an extension of what is found here: Why is arr = [] faster than arr = new Array?
my output was the following:
Testing Array:
using[]: 1091ms
using new: 2286ms
Testing Object:
using{}: 870ms
using new: 5637ms
so clearly {} and [] are faster than using new for creating empty objects/arrays.
In a Navigation based app you can put the code in AppDelegate. A more detailed code could be:
// Navigation bar appearance (background and title)
[[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor titleColor], NSForegroundColorAttributeName, [UIFont fontWithName:@"FontNAme" size:titleSize], NSFontAttributeName, nil]];
[[UINavigationBar appearance] setTintColor:[UIColor barColor]];
// Navigation bar buttons appearance
[[UIBarButtonItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor textBarColor], NSForegroundColorAttributeName, shadowColor, NSShadowAttributeName, [UIFont fontWithName:@"FontName" size:titleSize], NSFontAttributeName, nil];
On Ubuntu 16.04 LTS you can change the Port like that:
/etc/default/jenkins
to 8081 (or the port you like) HTTP_PORT=8081
service jenkins restart
That should do it:
FOR %%a IN (%Svcs%) DO (SC query %%a | FIND /i "RUNNING"
IF ERRORLEVEL 1 SC start %%a)
https://jsfiddle.net/SyedFayaz/ud0mpgoh/7/
<table class="table-bordered">
<col />
<col />
<col />
<colgroup span="4"></colgroup>
<col />
<tr>
<th rowspan="2" style="vertical-align: middle; text-align: center">
S.No.
</th>
<th rowspan="2" style="vertical-align: middle; text-align: center">Item</th>
<th rowspan="2" style="vertical-align: middle; text-align: center">
Description
</th>
<th
colspan="3"
style="horizontal-align: middle; text-align: center; width: 50%"
>
Items
</th>
<th rowspan="2" style="vertical-align: middle; text-align: center">
Rejected Reason
</th>
</tr>
<tr>
<th scope="col">Order</th>
<th scope="col">Received</th>
<th scope="col">Accepted</th>
</tr>
<tr>
<th>1</th>
<td>Watch</td>
<td>Analog</td>
<td>100</td>
<td>75</td>
<td>25</td>
<td>Not Functioning</td>
</tr>
<tr>
<th>2</th>
<td>Pendrive</td>
<td>5GB</td>
<td>250</td>
<td>165</td>
<td>85</td>
<td>Not Working</td>
</tr>
</table>
You can actually just use
$("#form").attr("target", "NewAction");
As far as I know, this will NOT fail silently.
If the page is opening in a new target, you may need to make sure the URL is unique each time because Webkit (chrome/safari) will cache the fact you have visited that URL and won't perform the post.
For example
$("form").attr("action", "/Pages/GeneratePreview?" + new Date().getMilliseconds());
To keep only one instance for the String, you could use the following.
str = " Hello ";
or
str = str.trim();
Then the value of the str
String, will be str = "Hello"
You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--'
as one of the values.
string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief, ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
// ... other parameters
myCommand.ExecuteNonQuery();
To start, using the same ID twice is not a good idea. ID's should be unique, if you need to style elements you should use a class to apply CSS instead.
At last, you defined the name of your submit button as Tea and Coffee, but in your PHP you are using submit as index. your index should have been $_POST['Tea'] for example. that would require you to check for it being set as it only sends one , you can do that with isset().
Buy anyway , user4035 just beat me to it , his code will "fix" this for you.
Use this:
public static void wait(int ms)
{
try
{
Thread.sleep(ms);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
and, then you can call this method anywhere like:
wait(1000);
Create a drawable/button_states.xml file containing:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false">
<shape android:shape="rectangle">
<corners android:radius="1000dp" />
<solid android:color="#41ba7a" />
<stroke
android:width="2dip"
android:color="#03ae3c" />
<padding
android:bottom="4dp"
android:left="4dp"
android:right="4dp"
android:top="4dp" />
</shape>
</item>
<item android:state_pressed="true">
<shape android:shape="rectangle">
<corners android:radius="1000dp" />
<solid android:color="#3AA76D" />
<stroke
android:width="2dip"
android:color="#03ae3c" />
<padding
android:bottom="4dp"
android:left="4dp"
android:right="4dp"
android:top="4dp" />
</shape>
</item>
</selector>
Use it in button tag in any layout file
<Button
android:layout_width="220dp"
android:layout_height="220dp"
android:background="@drawable/button_states"
android:text="@string/btn_scan_qr"
android:id="@+id/btn_scan_qr"
android:textSize="15dp"
/>
System.Uri.EscapeUriString() didn't seem to do anything, but System.Uri.EscapeDataString() worked for me.
I found DragSortListView worked well, although getting started on it could have been easier. Here's a brief tutorial on using it in Android Studio with an in-memory list:
Add this to the build.gradle
dependencies for your app:
compile 'asia.ivity.android:drag-sort-listview:1.0' // Corresponds to release 0.6.1
Create a resource for the drag handle ID by creating or adding to values/ids.xml
:
<resources>
... possibly other resources ...
<item type="id" name="drag_handle" />
</resources>
Create a layout for a list item that includes your favorite drag handle image, and assign its ID to the ID you created in step 2 (e.g. drag_handle
).
Create a DragSortListView layout, something like this:
<com.mobeta.android.dslv.DragSortListView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dslv="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
dslv:drag_handle_id="@id/drag_handle"
dslv:float_background_color="@android:color/background_light"/>
Set an ArrayAdapter
derivative with a getView
override that renders your list item view.
final ArrayAdapter<MyItem> itemAdapter = new ArrayAdapter<MyItem>(this, R.layout.my_item, R.id.my_item_name, items) { // The third parameter works around ugly Android legacy. http://stackoverflow.com/a/18529511/145173
@Override public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
MyItem item = getItem(position);
((TextView) view.findViewById(R.id.my_item_name)).setText(item.getName());
// ... Fill in other views ...
return view;
}
};
dragSortListView.setAdapter(itemAdapter);
Set a drop listener that rearranges the items as they are dropped.
dragSortListView.setDropListener(new DragSortListView.DropListener() {
@Override public void drop(int from, int to) {
MyItem movedItem = items.get(from);
items.remove(from);
if (from > to) --from;
items.add(to, movedItem);
itemAdapter.notifyDataSetChanged();
}
});
Try wrapping the spans in an anchor tag and apply the background image to that.
HTML:
<div class="header">
<a href="/">
<span class="header-title">My gray sea design</span><br />
<span class="header-title-two">A beautiful design</span>
</a>
</div>
CSS:
.header {
border-bottom:1px solid #eaeaea;
}
.header a {
display: block;
background-image: url("./images/embouchure.jpg");
background-repeat: no-repeat;
height:160px;
padding-left:280px;
padding-top:50px;
width:470px;
color: #eaeaea;
}
ol {
counter-reset: item;
}
ol li { display: block }
ol li:before {
content: counter(item) ". ";
counter-increment: item;
font-weight: bold;
}
Maybe I'm not understanding the question but here is my simple solution that works -
# I want to Display total heads bent this machine so I define a label -
TotalHeadsLabel3 = Label(leftFrame)
TotalHeadsLabel3.config(font=Helv12,fg='blue',text="Total heads " + str(TotalHeads))
TotalHeadsLabel3.pack(side=TOP)
# I update the int variable adding the quantity bent -
TotalHeads = TotalHeads + headQtyBent # update ready to write to file & display
TotalHeadsLabel3.config(text="Total Heads "+str(TotalHeads)) # update label with new qty
I agree that labels are not automatically updated but can easily be updated with the
<label name>.config(text="<new text>" + str(<variable name>))
That just needs to be included in your code after the variable is updated.
via Facebook's Platform Updates:
Change in Session Redirect Behavior
This week, we started adding a fragment #____=____ to the redirect_uri when this field is left blank. Please ensure that your app can handle this behavior.
To prevent this, set the redirect_uri in your login url request like so: (using Facebook php-sdk)
$facebook->getLoginUrl(array('redirect_uri' => $_SERVER['SCRIPT_URI'],'scope' => 'user_about_me'));
UPDATE
The above is exactly as the documentation says to fix this. However, Facebook's documented solution does not work. Please consider leaving a comment on the Facebook Platform Updates blog post and follow this bug to get a better answer. Until then, add the following to your head tag to resolve this issue:
<script type="text/javascript">
if (window.location.hash && window.location.hash == '#_=_') {
window.location.hash = '';
}
</script>
Or a more detailed alternative (thanks niftylettuce):
<script type="text/javascript">
if (window.location.hash && window.location.hash == '#_=_') {
if (window.history && history.pushState) {
window.history.pushState("", document.title, window.location.pathname);
} else {
// Prevent scrolling by storing the page's current scroll offset
var scroll = {
top: document.body.scrollTop,
left: document.body.scrollLeft
};
window.location.hash = '';
// Restore the scroll offset, should be flicker free
document.body.scrollTop = scroll.top;
document.body.scrollLeft = scroll.left;
}
}
</script>
I think we can do this with one line simple command
for i in `grep -rl eth0 . 2> /dev/null`; do sed -i ‘s/eth0/eth1/’ $i; done
Refer to this page.
I'm sure one of the pedants will come up with a better answer shortly, but the main difference is speed and size.
Stack
Dramatically faster to allocate. It is done in O(1) since it is allocated when setting up the stack frame so it is essentially free. The drawback is that if you run out of stack space you are boned. You can adjust the stack size, but IIRC you have ~2MB to play with. Also, as soon as you exit the function everything on the stack is cleared. So it can be problematic to refer to it later. (Pointers to stack allocated objects leads to bugs.)
Heap
Dramatically slower to allocate. But you have GB to play with, and point to.
Garbage Collector
The garbage collector is some code that runs in the background and frees memory. When you allocate memory on the heap it is very easy to forget to free it, which is known as a memory leak. Over time, the memory your application consumes grows and grows until it crashes. Having a garbage collector periodically free the memory you no longer need helps eliminate this class of bugs. Of course this comes at a price, as the garbage collector slows things down.
I'd say that the main rule of thumb is not to roll your own. Try to use something that has been thoroughly tested, e.g., SHA-1 or something along those lines.
SOLUTION
<style>
.container {
margin: 10px;
width: 115px;
height: 115px;
line-height: 115px;
text-align: center;
border: 1px solid red;
background-image: url("http://i.imgur.com/H9lpVkZ.jpg");
background-repeat: no-repeat;
background-position: center;
background-size: contain;
}
</style>
<div class='container'>
</div>
<div class='container' style='width:50px;height:100px;line-height:100px'>
</div>
<div class='container' style='width:140px;height:70px;line-height:70px'>
</div>
In the first case you are simply starting a new thread while in the second case you are entering in the thread pool.
The thread pool job is to share and recycle threads. It allows to avoid losing a few millisecond every time we need to create a new thread.
There are a several ways to enter the thread pool:
In Javascript method names are camel case, so it's replace
, not Replace
:
$scope.newString = oldString.replace("stackover","NO");
Note that contrary to how the .NET Replace
method works, the Javascript replace
method replaces only the first occurrence if you are using a string as first parameter. If you want to replace all occurrences you need to use a regular expression so that you can specify the global (g) flag:
$scope.newString = oldString.replace(/stackover/g,"NO");
See this example.
/* The following code was written by Matthew Wiggins
* and is released under the APACHE 2.0 license
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
package com.hlidskialf.android.hardware;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.content.Context;
import java.lang.UnsupportedOperationException;
public class ShakeListener implements SensorListener
{
private static final int FORCE_THRESHOLD = 350;
private static final int TIME_THRESHOLD = 100;
private static final int SHAKE_TIMEOUT = 500;
private static final int SHAKE_DURATION = 1000;
private static final int SHAKE_COUNT = 3;
private SensorManager mSensorMgr;
private float mLastX=-1.0f, mLastY=-1.0f, mLastZ=-1.0f;
private long mLastTime;
private OnShakeListener mShakeListener;
private Context mContext;
private int mShakeCount = 0;
private long mLastShake;
private long mLastForce;
public interface OnShakeListener
{
public void onShake();
}
public ShakeListener(Context context)
{
mContext = context;
resume();
}
public void setOnShakeListener(OnShakeListener listener)
{
mShakeListener = listener;
}
public void resume() {
mSensorMgr = (SensorManager)mContext.getSystemService(Context.SENSOR_SERVICE);
if (mSensorMgr == null) {
throw new UnsupportedOperationException("Sensors not supported");
}
boolean supported = mSensorMgr.registerListener(this, SensorManager.SENSOR_ACCELEROMETER, SensorManager.SENSOR_DELAY_GAME);
if (!supported) {
mSensorMgr.unregisterListener(this, SensorManager.SENSOR_ACCELEROMETER);
throw new UnsupportedOperationException("Accelerometer not supported");
}
}
public void pause() {
if (mSensorMgr != null) {
mSensorMgr.unregisterListener(this, SensorManager.SENSOR_ACCELEROMETER);
mSensorMgr = null;
}
}
public void onAccuracyChanged(int sensor, int accuracy) { }
public void onSensorChanged(int sensor, float[] values)
{
if (sensor != SensorManager.SENSOR_ACCELEROMETER) return;
long now = System.currentTimeMillis();
if ((now - mLastForce) > SHAKE_TIMEOUT) {
mShakeCount = 0;
}
if ((now - mLastTime) > TIME_THRESHOLD) {
long diff = now - mLastTime;
float speed = Math.abs(values[SensorManager.DATA_X] + values[SensorManager.DATA_Y] + values[SensorManager.DATA_Z] - mLastX - mLastY - mLastZ) / diff * 10000;
if (speed > FORCE_THRESHOLD) {
if ((++mShakeCount >= SHAKE_COUNT) && (now - mLastShake > SHAKE_DURATION)) {
mLastShake = now;
mShakeCount = 0;
if (mShakeListener != null) {
mShakeListener.onShake();
}
}
mLastForce = now;
}
mLastTime = now;
mLastX = values[SensorManager.DATA_X];
mLastY = values[SensorManager.DATA_Y];
mLastZ = values[SensorManager.DATA_Z];
}
}
}
Compilers translate
for (a; b; c)
{
...
}
to
a;
while(b)
{
...
end:
c;
}
So in your case (post/pre- increment) it doesn't matter.
EDIT: continues are simply replaced by goto end;
The initialization method easiest to remember is
vec = vector(,10); #the same as "vec = vector(length = 10);"
The values of vec are: "[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE" (logical mode) by default.
But after setting a character value, like
vec[2] = 'abc'
vec becomes: "FALSE" "abc" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE"", which is of the character mode.
Building on @IllidanS4 's answer, I have created a template class that allows virtually any member function with predefined arguments and class instance to be passed by reference for later calling.
template<class RET, class... RArgs> class Callback_t {
public:
virtual RET call(RArgs&&... rargs) = 0;
//virtual RET call() = 0;
};
template<class T, class RET, class... RArgs> class CallbackCalltimeArgs : public Callback_t<RET, RArgs...> {
public:
T * owner;
RET(T::*x)(RArgs...);
RET call(RArgs&&... rargs) {
return (*owner.*(x))(std::forward<RArgs>(rargs)...);
};
CallbackCalltimeArgs(T* t, RET(T::*x)(RArgs...)) : owner(t), x(x) {}
};
template<class T, class RET, class... Args> class CallbackCreattimeArgs : public Callback_t<RET> {
public:
T* owner;
RET(T::*x)(Args...);
RET call() {
return (*owner.*(x))(std::get<Args&&>(args)...);
};
std::tuple<Args&&...> args;
CallbackCreattimeArgs(T* t, RET(T::*x)(Args...), Args&&... args) : owner(t), x(x),
args(std::tuple<Args&&...>(std::forward<Args>(args)...)) {}
};
Test / example:
class container {
public:
static void printFrom(container* c) { c->print(); };
container(int data) : data(data) {};
~container() {};
void print() { printf("%d\n", data); };
void printTo(FILE* f) { fprintf(f, "%d\n", data); };
void printWith(int arg) { printf("%d:%d\n", data, arg); };
private:
int data;
};
int main() {
container c1(1), c2(20);
CallbackCreattimeArgs<container, void> f1(&c1, &container::print);
Callback_t<void>* fp1 = &f1;
fp1->call();//1
CallbackCreattimeArgs<container, void, FILE*> f2(&c2, &container::printTo, stdout);
Callback_t<void>* fp2 = &f2;
fp2->call();//20
CallbackCalltimeArgs<container, void, int> f3(&c2, &container::printWith);
Callback_t<void, int>* fp3 = &f3;
fp3->call(15);//20:15
}
Obviously, this will only work if the given arguments and owner class are still valid. As far as readability... please forgive me.
Edit: removed unnecessary malloc by making the tuple normal storage. Added inherited type for the reference. Added option to provide all arguments at calltime instead. Now working on having both....
Edit 2: As promised, both. Only restriction (that I see) is that the predefined arguments must come before the runtime supplied arguments in the callback function. Thanks to @Chipster for some help with gcc compliance. This works on gcc on ubuntu and visual studio on windows.
#ifdef _WIN32
#define wintypename typename
#else
#define wintypename
#endif
template<class RET, class... RArgs> class Callback_t {
public:
virtual RET call(RArgs... rargs) = 0;
virtual ~Callback_t() = default;
};
template<class RET, class... RArgs> class CallbackFactory {
private:
template<class T, class... CArgs> class Callback : public Callback_t<RET, RArgs...> {
private:
T * owner;
RET(T::*x)(CArgs..., RArgs...);
std::tuple<CArgs...> cargs;
RET call(RArgs... rargs) {
return (*owner.*(x))(std::get<CArgs>(cargs)..., rargs...);
};
public:
Callback(T* t, RET(T::*x)(CArgs..., RArgs...), CArgs... pda);
~Callback() {};
};
public:
template<class U, class... CArgs> static Callback_t<RET, RArgs...>* make(U* owner, CArgs... cargs, RET(U::*func)(CArgs..., RArgs...));
};
template<class RET2, class... RArgs2> template<class T2, class... CArgs2> CallbackFactory<RET2, RArgs2...>::Callback<T2, CArgs2...>::Callback(T2* t, RET2(T2::*x)(CArgs2..., RArgs2...), CArgs2... pda) : x(x), owner(t), cargs(std::forward<CArgs2>(pda)...) {}
template<class RET, class... RArgs> template<class U, class... CArgs> Callback_t<RET, RArgs...>* CallbackFactory<RET, RArgs...>::make(U* owner, CArgs... cargs, RET(U::*func)(CArgs..., RArgs...)) {
return new wintypename CallbackFactory<RET, RArgs...>::Callback<U, CArgs...>(owner, func, std::forward<CArgs>(cargs)...);
}
Being as it is a setting that is stored per-user, the session is an appropriate place to store the informtion.
I would change your controller to take the culture string as a parameter, rather than having a different action method for each potential culture. Adding a link to the page is easy, and you shouldn't need to write the same code repeatedly any time a new culture is required.
public class CultureController : Controller
{
public ActionResult SetCulture(string culture)
{
HttpContext.Session["culture"] = culture
return RedirectToAction("Index", "Home");
}
}
<li><%= Html.ActionLink("French", "SetCulture", new {controller = "Culture", culture = "fr-FR"})%></li>
<li><%= Html.ActionLink("Spanish", "SetCulture", new {controller = "Culture", culture = "es-ES"})%></li>
I think this works:
$(document).ready(function(){
// Hide (collapse) the toggle containers on load
$(".toggle_container").hide();
// Switch the "Open" and "Close" state per click then
// slide up/down (depending on open/close state)
$("h2.trigger").click(function(){
$(this).toggleClass("active").next().slideToggle("slow");
return false; // Prevent the browser jump to the link anchor
});
});
Use Query.setParameterList()
, Javadoc here.
There are four variants to pick from.
For me what worked is the following:
sudo xcode-select --reset
Then like in @High6's answer:
sudo xcodebuild -license
This will reveal a license which I assume is some Xcode license. Scroll to the bottom using space (or the mouse) then tap agree
.
This is what worked for me on MacOS Mojave v 10.14.
You are trying to access a member of a structure, but in something that is not a structure. For example:
struct {
int a;
int b;
} foo;
int fum;
fum.d = 5;
Maybe more simple;
var top = window.pageYOffset || document.documentElement.scrollTop,
left = window.pageXOffset || document.documentElement.scrollLeft;
Credits: so.dom.js#L492
You can simply use echo -n "|$COMMAND|"
.
This sometime happens when you had actually installed @angular/cli using yarn and not npm.
You can verify this by looking in to yarn's global install folder.
You can remove it from yarn using
yarn global remove @angular/cli
If you want to delete/ignore characters in a string, and, for instance, you have this string,
"[11:L:0]"
from a web API response or something like that, like a CSV file, let's say you are using requests
import requests
udid = 123456
url = 'http://webservices.yourserver.com/action/id-' + udid
s = requests.Session()
s.verify = False
resp = s.get(url, stream=True)
content = resp.content
loop and get rid of unwanted chars:
for line in resp.iter_lines():
line = line.replace("[", "")
line = line.replace("]", "")
line = line.replace('"', "")
Optional split, and you will be able to read values individually:
listofvalues = line.split(':')
Now accessing each value is easier:
print listofvalues[0]
print listofvalues[1]
print listofvalues[2]
This will print
11
L
0
The appropriate way to read text files in Cocoa/Objective-C is documented in Apple's String programming guide. The section for reading and writing files should be just what you're after. PS: What's a "line"? Two sections of a string separated by "\n"? Or "\r"? Or "\r\n"? Or maybe you're actually after paragraphs? The previously mentioned guide also includes a section on splitting a string into lines or paragraphs. (This section is called "Paragraphs and Line Breaks", and is linked to in the left-hand-side menu of the page I pointed to above. Unfortunately this site doesn't allow me to post more than one URL as I'm not a trustworthy user yet.)
To paraphrase Knuth: premature optimisation is the root of all evil. Don't simply assume that "reading the whole file into memory" is slow. Have you benchmarked it? Do you know that it actually reads the whole file into memory? Maybe it simply returns a proxy object and keeps reading behind the scenes as you consume the string? (Disclaimer: I have no idea if NSString actually does this. It conceivably could.) The point is: first go with the documented way of doing things. Then, if benchmarks show that this doesn't have the performance you desire, optimise.
If not using C++14, then I find below the simplest solution.
#define METHOD(NAME, ...) auto NAME __VA_ARGS__ -> decltype(m_T.r##NAME) { return m_T.r##NAME; }
template<typename T>
struct Reverse
{
T& m_T;
METHOD(begin());
METHOD(end());
METHOD(begin(), const);
METHOD(end(), const);
};
#undef METHOD
template<typename T>
Reverse<T> MakeReverse (T& t) { return Reverse<T>{t}; }
Demo.
It doesn't work for the containers/data-types (like array), which doesn't have begin/rbegin, end/rend
functions.
i usually use this in sh scripts
SCRIPTSRC=`readlink -f "$0" || echo "$0"`
RUN_PATH=`dirname "${SCRIPTSRC}" || echo .`
echo "Running from ${RUN_PATH}"
...
cd ${RUN_PATH}/subfolder
you can use this to automate things ...
To trim a list in place without creating copies of it, use del
:
>>> t = [1, 2, 3, 4, 5]
>>> # delete elements starting from index 4 to the end
>>> del t[4:]
>>> t
[1, 2, 3, 4]
>>> # delete elements starting from index 5 to the end
>>> # but the list has only 4 elements -- no error
>>> del t[5:]
>>> t
[1, 2, 3, 4]
>>>
Another possible way, in order to make the colors a bit more intense, is this one:
<span class="badge progress-bar-info">10</span>
<span class="badge progress-bar-success">20</span>
<span class="badge progress-bar-warning">30</span>
<span class="badge progress-bar-danger">40</span>
See Bootply
Just to be different, changed my answer so that this question doesn't have 5 answers with the same code.
<html>
<head>
<title>Page</title>
<script src="jquery-1.3.2.min.js"></script>
<script>
$(function() {
var select = $("body").append('<form></form>').children('form')
.append('<input type="hidden" value="" />').children('input[type=hidden]')
.attr('id', 'hiddenValue').end()
.append('<select></select>').children('select')
.attr('id', 'dropdown')
.change(function() {
alert($(this).val());
});
$.each({ one: 1, two: 2, three: 3, four: 4, five: 5 }, function(txt, val) {
select.append('<option value="' + val + '">' + txt + '</option>');
});
});
</script>
</head>
<body></body>
</html>
I had this problem also. The issue was because I was running an old version of PHP (5.6) and once I upgraded to PHP 7.4 the errors went away.
This was on Amazon Linux 2 for me and the command to upgrade was:
amazon-linux-extras install php7.4
Other flavors of *nix might have it in their repositories otherwise if you're on a flavor of Linux then Remi might have it for you here: https://rpms.remirepo.net/
The best solution is not to use the same element for column and panel:
<div class="row">
<div class="col-md-3">
<div class="panel" id="gameplay-away-team">Away Team</div>
</div>
<div class="col-md-6">
<div class="panel" id="gameplay-baseball-field">Baseball Field</div>
</div>
<div class="col-md-3">
<div class="panel" id="gameplay-home-team">Home Team</div>
</div>
</div>
and some more styles:
#gameplay-baseball-field {
padding-right: 10px;
padding-left: 10px;
}
As a more systematic and structured solution you could define folders where your classes are stored and create an autoloader (__autoload()
) which will search the class files in defined places:
require_once("../settings.php");
define('DIR_CLASSES', '/path/to/the/classes/folder/'); // this can be inside your settings.php
$user = new User();
$user->createUser($_POST["username"], $_POST["email"], $_POST["password"]);
function __autoload($classname) {
if(file_exists(DIR_CLASSES . 'class' . $classname . '.php')) {
include_once(DIR_CLASSES . 'class' . $classname . '.php'); // looking for the class in the project's classes folder
} else {
include_once($classname . '.php'); // looking for the class in include_path
}
}
How about this? Divide your file into chunks and then read it line by line, because when you read a file, your operating system will cache the next line. If you are reading the file line by line, you are not making efficient use of the cached information.
Instead, divide the file into chunks and load the whole chunk into memory and then do your processing.
def chunks(file,size=1024):
while 1:
startat=fh.tell()
print startat #file's object current position from the start
fh.seek(size,1) #offset from current postion -->1
data=fh.readline()
yield startat,fh.tell()-startat #doesnt store whole list in memory
if not data:
break
if os.path.isfile(fname):
try:
fh=open(fname,'rb')
except IOError as e: #file --> permission denied
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except Exception as e1: #handle other exceptions such as attribute errors
print "Unexpected error: {0}".format(e1)
for ele in chunks(fh):
fh.seek(ele[0])#startat
data=fh.read(ele[1])#endat
print data
You can also just use the top command and your user ID will indicate the jobs running and the their times.
$ top
(this will show all running jobs)
$ top -U [user ID]
(This will show jobs that are specific for the user ID)
Probably you don't have the service in your manifest, or it does not have an <intent-filter>
that matches your action. Examining LogCat (via adb logcat
, DDMS, or the DDMS perspective in Eclipse) should turn up some warnings that may help.
More likely, you should start the service via:
startService(new Intent(this, UpdaterServiceManager.class));
Use empty()
. It checks for both empty strings and null.
if (!empty($_POST['user'])) {
// do stuff
}
From the manual:
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Another way is to use the object tag. This works on Chrome, IE, Firefox, Safari and Opera.
<object data="html/stuff_to_include.html">
Your browser doesn’t support the object tag.
</object>
more info at http://www.w3schools.com/tags/tag_object.asp
I have a Samsung Galaxy and I had the same issue as you. Here's how to fix it:
In device manager on your Windows PC, even though it might say the USB drivers are installed correctly, there may exist corruption.
I went into device manager and uninstalled SAMSUNG Android USB Composite Device and made sure to check the box 'delete driver software'. Now the device will have an exclamation mark etc. I right clicked and installed the driver again (refresh copy). This finally made adb acknowledge my phone as an emulator.
As others noted, for Nexus 4, you can also try this fix.
ISNA is the best function to use. I just did. I wanted all cells whose value was NOT in an array to conditionally format to a certain color.
=ISNA(VLOOKUP($A2,Sheet1!$A:$D,2,FALSE))
I would recommend using Properties.Settings to store values like ConnectionStrings and so on inside of the class library. This is where all the connection strings are stores in by suggestion from visual studio when you try to add a table adapter for example. enter image description here
And then they will be accessible by using this code every where in the clas library
var cs= Properties.Settings.Default.[<name of defined setting>];
Looks like everybody has own problem Just sharing what I did to fix this problem in VS2015 (Windows 8.1), my solution has 6 web sites (not web apps)
See sample solution file ProjectSection(WebsiteProperties):
Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "BOSTONBEANCOFFEE.COM", "Source_WebOfficeV4\BOSTONBEANCOFFEE.COM", "{5106A8F5-401B-4907-981C-F37784DC4E9D}"
ProjectSection(WebsiteProperties) = preProject
SccProjectName = ""$/PrismRMSystem/VS2012/WebOfficeV4.root/WebOfficeV4", IPYHAAAA"
SccAuxPath = ""
SccLocalPath = "..\.."
SccProvider = "MSSCCI:Microsoft Visual SourceSafe"
TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.0"
ProjectReferences = "{04e527c3-bac6-4082-9d39-aad8771b368e}|YBTools.dll;{5d52eaec-42fb-4313-83b8-69e2f55ebf14}|AuthorizeNet.dll;{d8408f53-8f1e-4a71-8b05-76023b09b716}|AuthorizeNet.Helpers.dll;{77ebd08a-de0f-4793-b436-fad6980863e6}|WEBCUSTCONTROLS.dll;"
Debug.AspNetCompiler.VirtualPath = "/BOSTONBEANCOFFEE.COM"
Debug.AspNetCompiler.PhysicalPath = "Source_WebOfficeV4\BOSTONBEANCOFFEE.COM\"
Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\BOSTONBEANCOFFEE.COM\"
Debug.AspNetCompiler.Updateable = "true"
Debug.AspNetCompiler.ForceOverwrite = "true"
Debug.AspNetCompiler.KeyFile = "Key\StrongKey.snk"
Debug.AspNetCompiler.DelaySign = "false"
Debug.AspNetCompiler.AllowPartiallyTrustedCallers = "false"
Debug.AspNetCompiler.FixedNames = "true"
Debug.AspNetCompiler.Debug = "True"
Release.AspNetCompiler.VirtualPath = "/BOSTONBEANCOFFEE.COM"
Release.AspNetCompiler.PhysicalPath = "Source_WebOfficeV4\BOSTONBEANCOFFEE.COM\"
Release.AspNetCompiler.TargetPath = "PrecompiledWeb\BOSTONBEANCOFFEE.COM\"
Release.AspNetCompiler.Updateable = "true"
Release.AspNetCompiler.ForceOverwrite = "true"
Release.AspNetCompiler.KeyFile = "Key\StrongKey.snk"
Release.AspNetCompiler.DelaySign = "false"
Release.AspNetCompiler.AllowPartiallyTrustedCallers = "false"
Release.AspNetCompiler.FixedNames = "true"
Release.AspNetCompiler.Debug = "False"
VWDPort = "34781"
SlnRelativePath = "Source_WebOfficeV4\BOSTONBEANCOFFEE.COM\"
EndProjectSection
In my case, I tried to change URL from project properties, restart VS, reboot computer, nothing helped me only this SLN file manipulation fixed my problem.
Working with just one class:
select {
width: 268px;
padding: 5px;
font-size: 16px;
line-height: 1;
border: 0;
border-radius: 5px;
height: 34px;
background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right #ddd;
-webkit-appearance: none;
background-position-x: 244px;
}
You can avoid having your filename embedded in the NUMOFLINES variable by using redirection from JAVA_TAGS_FILE, rather than passing the filename as an argument to wc. For example:
NUMOFLINES=$(wc -l < "$JAVA_TAGS_FILE")
The wc utility will not print the name of the file in its output if input is taken from a pipe or redirection operator. Consider these various examples:
# wc shows filename when the file is an argument
$ wc -l /etc/passwd
41 /etc/passwd
# filename is ignored when piped in on standard input
$ cat /etc/passwd | wc -l
41
# unusual redirection, but wc still ignores the filename
$ < /etc/passwd wc -l
41
# typical redirection, taking standard input from a file
$ wc -l < /etc/passwd
41
As you can see, the only time wc will print the filename is when its passed as an argument, rather than as data on standard input. In some cases, you may want the filename to be printed, so it's useful to understand when it will be displayed.
TL;DR: This would very likely work:
python mypkg/tests/test_module.py MyCase.testItIsHot
The explanation:
The convenient way
python mypkg/tests/test_module.py MyCase.testItIsHot
would work, but its unspoken assumption is you already have this conventional code snippet inside (typically at the end of) your test file.
if __name__ == "__main__":
unittest.main()
The inconvenient way
python -m unittest mypkg.tests.test_module.TestClass.test_method
would always work, without requiring you to have that if __name__ == "__main__": unittest.main()
code snippet in your test source file.
So why is the second method considered inconvenient? Because it would be a pain in the <insert one of your body parts here> to type that long, dot-delimited path by hand. While in the first method, the mypkg/tests/test_module.py
part can be auto-completed, either by a modern shell, or by your editor.
You can also specify context location relatively to current classpath, which may be preferable
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
InputStream in = getResources().openRawResource(resourceName);
This will work correctly. Before that you have to create the xml file / text file in raw resource. Then it will be accessible.
Edit
Some times com.andriod.R will be imported if there is any error in layout file or image names. So You have to import package correctly, then only the raw file will be accessible.
if (code.indexOf("ST1")>=0) { location = "stoke central"; }
you can split using a third party software http://www.hjsplit.org/, for example give yours input that could be upto 9GB and then split, in my case I split 10 MB each
I had the same problem. SSMS launches the 32bit version of the import and export wizard which has this issue. Try launching the 64bit version application and it should work fine.
/// <summary>
/// map properties
/// </summary>
/// <param name="sourceObj"></param>
/// <param name="targetObj"></param>
private void MapProp(object sourceObj, object targetObj)
{
Type T1 = sourceObj.GetType();
Type T2 = targetObj.GetType();
PropertyInfo[] sourceProprties = T1.GetProperties(BindingFlags.Instance | BindingFlags.Public);
PropertyInfo[] targetProprties = T2.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var sourceProp in sourceProprties)
{
object osourceVal = sourceProp.GetValue(sourceObj, null);
int entIndex = Array.IndexOf(targetProprties, sourceProp);
if (entIndex >= 0)
{
var targetProp = targetProprties[entIndex];
targetProp.SetValue(targetObj, osourceVal);
}
}
}
Another way (credit):
@For /F "tokens=2,3,4 delims=/ " %%A in ('Date /t') do @(
Set Month=%%A
Set Day=%%B
Set Year=%%C
)
@echo DAY = %Day%
@echo Month = %Month%
@echo Year = %Year%
Note that both my answers here are still reliant on the order of the day and month as determined by regional settings - not sure how to work around that.
The practical use of this construct? It is a javascript replaceAll() on strings.
var s = 'stackoverflow_is_cool';
s = s.split('_').join(' ');
console.log(s);
will output:
stackoverflow is cool
android:layout_weight=".YOURVALUE" is best way to implement in percentage
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/logTextBox"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight=".20"
android:maxLines="500"
android:scrollbars="vertical"
android:singleLine="false"
android:text="@string/logText" >
</TextView>
</LinearLayout>
For a horizontal progress bar, you first need to define your progress bar and link it with your XML file like this, in the onCreate
:
final TextView txtview = (TextView)findViewById(R.id.tV1);
final ProgressBar pbar = (ProgressBar) findViewById(R.id.pB1);
Then, you may use onProgressChanged Method in your WebChromeClient:
MyView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if(progress < 100 && pbar.getVisibility() == ProgressBar.GONE){
pbar.setVisibility(ProgressBar.VISIBLE);
txtview.setVisibility(View.VISIBLE);
}
pbar.setProgress(progress);
if(progress == 100) {
pbar.setVisibility(ProgressBar.GONE);
txtview.setVisibility(View.GONE);
}
}
});
After that, in your layout you have something like this
<TextView android:text="Loading, . . ."
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="@+id/tV1" android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textColor="#000000"></TextView>
<ProgressBar android:id="@+id/pB1"
style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_centerVertical="true"
android:padding="2dip">
</ProgressBar>
This is how I did it in my app.
I prefer Python 3.x way.
cal = 123.4567
print(f"result {cal:.4E}")
4
indicates how many digits are shown shown in the floating part.
cal = 123.4567
totalDigitInFloatingPArt = 4
print(f"result {cal:.{totalDigitInFloatingPArt}E} ")
#This program is to read from excel workbook to fetch only the URL domain names and write to the existing excel workbook in a different sheet..
#Developer - Nilesh K
import pandas as pd
from openpyxl import load_workbook #for writting to the existing workbook
df = pd.read_excel("urlsearch_test.xlsx")
#You can use the below for the relative path.
# r"C:\Users\xyz\Desktop\Python\
l = [] #To make a list in for loop
#begin
#loop starts here for fetching http from a string and iterate thru the entire sheet. You can have your own logic here.
for index, row in df.iterrows():
try:
str = (row['TEXT']) #string to read and iterate
y = (index)
str_pos = str.index('http') #fetched the index position for http
str_pos1 = str.index('/', str.index('/')+2) #fetched the second 3rd position of / starting from http
str_op = str[str_pos:str_pos1] #Substring the domain name
l.append(str_op) #append the list with domain names
#Error handling to skip the error rows and continue.
except ValueError:
print('Error!')
print(l)
l = list(dict.fromkeys(l)) #Keep distinct values, you can comment this line to get all the values
df1 = pd.DataFrame(l,columns=['URL']) #Create dataframe using the list
#end
#Write using openpyxl so it can be written to same workbook
book = load_workbook('urlsearch_test.xlsx')
writer = pd.ExcelWriter('urlsearch_test.xlsx',engine = 'openpyxl')
writer.book = book
df1.to_excel(writer,sheet_name = 'Sheet3')
writer.save()
writer.close()
#The below can be used to write to a different workbook without using openpyxl
#df1.to_excel(r"C:\Users\xyz\Desktop\Python\urlsearch1_test.xlsx",index='false',sheet_name='sheet1')
It looks like you want this pluging as it follows your existing code, maybe the plug in js file got left out somewhere.
http://www.texotela.co.uk/code/jquery/select/
var myOptions = {
"Value 1" : "Text 1",
"Value 2" : "Text 2",
"Value 3" : "Text 3"
}
$("#myselect2").addOption(myOptions, false);
// use true if you want to select the added options » Run
The Java runtime you try to execute your program with is an earlier version than Java 7 which was the target you compile your program for.
For Ubuntu use
apt-get install openjdk-7-jdk
to get Java 7 as default. You may have to uninstall openjdk-6 first.
There should also be a YEAR().
As for comparing, you could compare dates that are the first days of those years and months, or you could convert the year/month pair into a number suitable for comparison (i.e. bigger = later). (Exercise left to the reader. For hints, read about the ISO date format.)
Or you could use multiple comparisons (i.e. years first, then months).
Use +
, the string concatenation operator:
ed = (EditText) findViewById (R.id.box);
int x = 10;
ed.setText(""+x);
or use String.valueOf(int)
:
ed.setText(String.valueOf(x));
or use Integer.toString(int)
:
ed.setText(Integer.toString(x));
Assert.Throws
returns the exception that's thrown which lets you assert on the exception.
var ex = Assert.Throws<Exception>(() => user.MakeUserActive());
Assert.That(ex.Message, Is.EqualTo("Actual exception message"));
So if no exception is thrown, or an exception of the wrong type is thrown, the first Assert.Throws
assertion will fail. However if an exception of the correct type is thrown then you can now assert on the actual exception that you've saved in the variable.
By using this pattern you can assert on other things than the exception message, e.g. in the case of ArgumentException
and derivatives, you can assert that the parameter name is correct:
var ex = Assert.Throws<ArgumentNullException>(() => foo.Bar(null));
Assert.That(ex.ParamName, Is.EqualTo("bar"));
You can also use the fluent API for doing these asserts:
Assert.That(() => foo.Bar(null),
Throws.Exception
.TypeOf<ArgumentNullException>()
.With.Property("ParamName")
.EqualTo("bar"));
or alternatively
Assert.That(
Assert.Throws<ArgumentNullException>(() =>
foo.Bar(null)
.ParamName,
Is.EqualTo("bar"));
A little tip when asserting on exception messages is to decorate the test method with the SetCultureAttribute
to make sure that the thrown message is using the expected culture. This comes into play if you store your exception messages as resources to allow for localization.
I've come up with a slightly longer version that tries to build a full method name including module and class.
https://gist.github.com/2151727 (rev 9cccbf)
# Public Domain, i.e. feel free to copy/paste
# Considered a hack in Python 2
import inspect
def caller_name(skip=2):
"""Get a name of a caller in the format module.class.method
`skip` specifies how many levels of stack to skip while getting caller
name. skip=1 means "who calls me", skip=2 "who calls my caller" etc.
An empty string is returned if skipped levels exceed stack height
"""
stack = inspect.stack()
start = 0 + skip
if len(stack) < start + 1:
return ''
parentframe = stack[start][0]
name = []
module = inspect.getmodule(parentframe)
# `modname` can be None when frame is executed directly in console
# TODO(techtonik): consider using __main__
if module:
name.append(module.__name__)
# detect classname
if 'self' in parentframe.f_locals:
# I don't know any way to detect call from the object method
# XXX: there seems to be no way to detect static method call - it will
# be just a function call
name.append(parentframe.f_locals['self'].__class__.__name__)
codename = parentframe.f_code.co_name
if codename != '<module>': # top level usually
name.append( codename ) # function or a method
## Avoid circular refs and frame leaks
# https://docs.python.org/2.7/library/inspect.html#the-interpreter-stack
del parentframe, stack
return ".".join(name)
If you need to 'see' the list of temporary tables, you could simply log the names used. (and as others have noted, it is possible to directly query this information)
If you need to 'see' the content of temporary tables, you will need to create real tables with a (unique) temporary name.
You can trace the SQL being executed using SQL Profiler:
[These articles target SQL Server versions later than 2000, but much of the advice is the same.]
If you have a lengthy process that is important to your business, it's a good idea to log various steps (step name/number, start and end time) in the process. That way you have a baseline to compare against when things don't perform well, and you can pinpoint which step(s) are causing the problem more quickly.
Here's how to get the scrollHeight
of an element obtained using a jQuery selector:
$(selector)[0].scrollHeight
If selector
is the id of the element (e.g. elemId
), it is guaranteed that the 0-indexed item of the array will be the element you wish to select, and scrollHeight
will be correct.
here is a quick implement, i used it to get a 'Matrix'(sruct) from a string. you can have a bigger array and change its values on the run also:
typedef struct { int** lines; int isDefined; }mat;
mat matA, matB, matC, matD, matE, matF;
/* an auxilary struct to be used in a dictionary */
typedef struct { char* str; mat *matrix; }stringToMat;
/* creating a 'dictionary' for a mat name to its mat. lower case only! */
stringToMat matCases [] =
{
{ "mat_a", &matA },
{ "mat_b", &matB },
{ "mat_c", &matC },
{ "mat_d", &matD },
{ "mat_e", &matE },
{ "mat_f", &matF },
};
mat* getMat(char * str)
{
stringToMat* pCase;
mat * selected = NULL;
if (str != NULL)
{
/* runing on the dictionary to get the mat selected */
for(pCase = matCases; pCase != matCases + sizeof(matCases) / sizeof(matCases[0]); pCase++ )
{
if(!strcmp( pCase->str, str))
selected = (pCase->matrix);
}
if (selected == NULL)
printf("%s is not a valid matrix name\n", str);
}
else
printf("expected matrix name, got NULL\n");
return selected;
}
When adding new element with jquery plugin calls, you can do like the following:
$('<div>...</div>').hoverCard(function(){...}).appendTo(...)
It might be that you do not have the necessary .jar files that give you access to the Java Mail API. These can be downloaded from here.
html, body {
height:100%;
}
#wrapper {
min-height:100%;
}
To remove all doted outline, including those in bootstrap
themes.
a, a:active, a:focus,
button, button:focus, button:active,
.btn, .btn:focus, .btn:active:focus, .btn.active:focus, .btn.focus, .btn.focus:active, .btn.active.focus {
outline: none;
outline: 0;
}
input::-moz-focus-inner {
border: 0;
}
Note: You should add link href for bootstrap css before the main css, so bootstrap doesn't override your style.
For Active Directory users, an alternative way to do this would be -- assuming all your groups are stored in OU=Groups,DC=CorpDir,DC=QA,DC=CorpName
-- to use the query (&(objectCategory=group)(CN=GroupCN))
. This will work well for all groups with less than 1500 members. If you want to list all members of a large AD group, the same query will work, but you'll have to use ranged retrieval to fetch all the members, 1500 records at a time.
The key to performing ranged retrievals is to specify the range in the attributes using this syntax: attribute;range=low-high. So to fetch all members of an AD Group with 3000 members, first run the above query asking for the member;range=0-1499
attribute to be returned, then for the member;range=1500-2999
attribute.
Pass the string and replace space with line break, it gives you desired result.
select replace('shailendra kumar',' ',chr(10)) from dual;
var marker = [];
for ( var i = 0; i < 6; i++) {
marker[i]='Hello'+i;
}
console.log(marker);
alert(marker);
You don't tend to execute the make file itself, rather you execute make
, giving it the make file as an argument:
make -f pax.mk
If your make file is actually one of the standard names (like makefile
or Makefile
), you don't even need to specify it. It'll be picked up by default (if you have more than one of these standard names in your build directory, you better look up the make
man page to see which takes precedence).
Here's a version using the excellent requests library:
from requests import session
payload = {
'action': 'login',
'username': USERNAME,
'password': PASSWORD
}
with session() as c:
c.post('http://example.com/login.php', data=payload)
response = c.get('http://example.com/protected_page.php')
print(response.headers)
print(response.text)
As per ECMAScript 6 specification, you can use findIndex
.
const magenicIndex = vendors.findIndex(vendor => vendor.Name === 'Magenic');
magenicIndex
will hold either 0
(which is the index in the array) or -1
if it wasn't found.
There are tons of questions like this out there, with many answers, but I could not find a satisfactory solution that did not involve events, scripts, plugins, etc. I wanted to keep it straight in HTML and CSS. I finally found a solution that worked, although it involved restructuring the markup to break the event chain.
1. Basic problem
Scrolling input (i.e.: mousewheel) applied to the modal element will spill over into an ancestor element and scroll it in the same direction, if some such element is scrollable:
(All examples are meant to be viewed on desktop resolutions)
https://jsfiddle.net/ybkbg26c/5/
HTML:
<div id="parent">
<div id="modal">
This text is pretty long here. Hope fully, we will get some scroll bars.
</div>
</div>
CSS:
#modal {
position: absolute;
height: 100px;
width: 100px;
top: 20%;
left: 20%;
overflow-y: scroll;
}
#parent {
height: 4000px;
}
2. No parent scroll on modal scroll
The reason why the ancestor ends up scrolling is because the scroll event bubbles and some element on the chain is able to handle it. A way to stop that is to make sure none of the elements on the chain know how to handle the scroll. In terms of our example, we can refactor the tree to move the modal out of the parent element. For obscure reasons, it is not enough to keep the parent and the modal DOM siblings; the parent must be wrapped by another element that establishes a new stacking context. An absolutely positioned wrapper around the parent can do the trick.
The result we get is that as long as the modal receives the scroll event, the event will not bubble to the "parent" element.
It should typically be possible to redesign the DOM tree to support this behavior without affecting what the end user sees.
https://jsfiddle.net/0bqq31Lv/3/
HTML:
<div id="context">
<div id="parent">
</div>
</div>
<div id="modal">
This text is pretty long here. Hope fully, we will get some scroll bars.
</div>
CSS (new only):
#context {
position: absolute;
overflow-y: scroll;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
3. No scroll anywhere except in modal while it is up
The solution above still allows the parent to receive scroll events, as long as they are not intercepted by the modal window (i.e. if triggered by mousewheel while the cursor is not over the modal). This is sometimes undesirable and we may want to forbid all background scrolling while the modal is up. To do that, we need to insert an extra stacking context that spans the whole viewport behind the modal. We can do that by displaying an absolutely positioned overlay, which can be fully transparent if necessary (but not visibility:hidden
).
https://jsfiddle.net/0bqq31Lv/2/
HTML:
<div id="context">
<div id="parent">
</div>
</div>
<div id="overlay">
</div>
<div id="modal">
This text is pretty long here. Hope fully, we will get some scroll bars.
</div>
CSS (new on top of #2):
#overlay {
background-color: transparent;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
Windows has the facility to prevent windows from stealing focus; instead it flashes the taskbar icon. In XP it's on by default (the only place I've seen to change it is using TweakUI, but there is a registry setting somewhere). In Vista they may have changed the default and/or exposed it as a user accessible setting with the out-of-the-box UI.
Preventing windows from forcing themselves to the front and taking focus is a feature since Windows 2K (and I, for one, am thankful for it).
That said, I have a little Java app I use to remind me to record my activities while working, and it makes itself the active window every 30 minutes (configurable, of course). It always works consistently under Windows XP and never flashes the title bar window. It uses the following code, called in the UI thread as a result of a timer event firing:
if(getState()!=Frame.NORMAL) { setState(Frame.NORMAL); }
toFront();
repaint();
(the first line restores if minimized... actually it would restore it if maximized too, but I never have it so).
While I usually have this app minimized, quite often it's simply behind my text editor. And, like I said, it always works.
I do have an idea on what your problem could be - perhaps you have a race condition with the setVisible() call. toFront() may not be valid unless the window is actually displayed when it is called; I have had this problem with requestFocus() before. You may need to put the toFront() call in a UI listener on a window activated event.
2014-09-07: At some point in time the above code stopped working, perhaps at Java 6 or 7. After some investigation and experimentation I had to update the code to override the window's toFront
method do this (in conjunction with modified code from what is above):
setVisible(true);
toFront();
requestFocus();
repaint();
...
public @Override void toFront() {
int sta = super.getExtendedState() & ~JFrame.ICONIFIED & JFrame.NORMAL;
super.setExtendedState(sta);
super.setAlwaysOnTop(true);
super.toFront();
super.requestFocus();
super.setAlwaysOnTop(false);
}
As of Java 8_20, this code seems to be working fine.
$ which nc
/bin/nc
$ rpm -qf /bin/nc
nmap-ncat-7.40-7.fc26.x86_64
$ ssh -o "ProxyCommand nc --proxy <addr[:port]> %h %p" USER@HOST
$ ssh -o "ProxyCommand nc --proxy <addr[:port]> --proxy-type <type> --proxy-auth <auth> %h %p" USER@HOST
Dim o
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET", "http://www.example.com", False
o.send
' o.responseText now holds the response as a string.
Give this a try:
Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files" -Filter *.log |
Foreach-Object {
$content = Get-Content $_.FullName
#filter and save content to the original file
$content | Where-Object {$_ -match 'step[49]'} | Set-Content $_.FullName
#filter and save content to a new file
$content | Where-Object {$_ -match 'step[49]'} | Set-Content ($_.BaseName + '_out.log')
}
I know this is not really an answer to the question, but based on the number of votes for the question and the accepted answer, I suspect the people are actually using the code to serialize an object to a string.
Using XML serialization adds unnecessary extra text rubbish to the output.
For the following class
public class UserData
{
public int UserId { get; set; }
}
it generates
<?xml version="1.0" encoding="utf-16"?>
<UserData xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<UserId>0</UserId>
</UserData>
Better solution is to use JSON serialization (one of the best is Json.NET). To serialize an object:
var userData = new UserData {UserId = 0};
var userDataString = JsonConvert.SerializeObject(userData);
To deserialize an object:
var userData = JsonConvert.DeserializeObject<UserData>(userDataString);
The serialized JSON string would look like:
{"UserId":0}
Erm, why would you want to? Leave PHP on the backend and NodeJS/Sockets to do its non-blocking thing.
Here is something to get you started: http://groups.google.com/group/socket_io/browse_thread/thread/74a76896d2b72ccc
Personally I have express running with an endpoint that is listening expressly for interaction from PHP.
For example, if I have sent a user an email, I want socket.io to display a real-time notification to the user.
Want interaction from socket.io to php, well you can just do something like this:
var http = require('http'),
host = WWW_HOST,
clen = 'userid=' + userid,
site = http.createClient(80, host),
request = site.request("POST", "/modules/nodeim/includes/signonuser.inc.php",
{'host':host,'Content-Length':clen.length,'Content-Type':'application/x-www-form-urlencoded'});
request.write('userid=' + userid);
request.end();
Seriously, PHP is great for doing server side stuff and let it be with the connections it has no place in this domain now. Why do anything long-polling when you have websockets or flashsockets.
>>> '\\&' == '\&'
True
>>> len('\\&')
2
>>> print('\\&')
\&
Or in other words: '\\&'
only contains one backslash. It's just escaped in the python shell's output for clarity.
"I do not know if it is out of ignorance, but I do not like that kind of programming, as it is using exceptions to perform flow control."
In the Python world, using exceptions for flow control is common and normal.
Even the Python core developers use exceptions for flow-control and that style is heavily baked into the language (i.e. the iterator protocol uses StopIteration to signal loop termination).
In addition, the try-except-style is used to prevent the race-conditions inherent in some of the "look-before-you-leap" constructs. For example, testing os.path.exists results in information that may be out-of-date by the time you use it. Likewise, Queue.full returns information that may be stale. The try-except-else style will produce more reliable code in these cases.
"It my understanding that exceptions are not errors, they should only be used for exceptional conditions"
In some other languages, that rule reflects their cultural norms as reflected in their libraries. The "rule" is also based in-part on performance considerations for those languages.
The Python cultural norm is somewhat different. In many cases, you must use exceptions for control-flow. Also, the use of exceptions in Python does not slow the surrounding code and calling code as it does in some compiled languages (i.e. CPython already implements code for exception checking at every step, regardless of whether you actually use exceptions or not).
In other words, your understanding that "exceptions are for the exceptional" is a rule that makes sense in some other languages, but not for Python.
"However, if it is included in the language itself, there must be a good reason for it, isn't it?"
Besides helping to avoid race-conditions, exceptions are also very useful for pulling error-handling outside loops. This is a necessary optimization in interpreted languages which do not tend to have automatic loop invariant code motion.
Also, exceptions can simplify code quite a bit in common situations where the ability to handle an issue is far removed from where the issue arose. For example, it is common to have top level user-interface code calling code for business logic which in turn calls low-level routines. Situations arising in the low-level routines (such as duplicate records for unique keys in database accesses) can only be handled in top-level code (such as asking the user for a new key that doesn't conflict with existing keys). The use of exceptions for this kind of control-flow allows the mid-level routines to completely ignore the issue and be nicely decoupled from that aspect of flow-control.
There is a nice blog post on the indispensibility of exceptions here.
Also, see this Stack Overflow answer: Are exceptions really for exceptional errors?
"What is the reason for the try-except-else to exist?"
The else-clause itself is interesting. It runs when there is no exception but before the finally-clause. That is its primary purpose.
Without the else-clause, the only option to run additional code before finalization would be the clumsy practice of adding the code to the try-clause. That is clumsy because it risks raising exceptions in code that wasn't intended to be protected by the try-block.
The use-case of running additional unprotected code prior to finalization doesn't arise very often. So, don't expect to see many examples in published code. It is somewhat rare.
Another use-case for the else-clause is to perform actions that must occur when no exception occurs and that do not occur when exceptions are handled. For example:
recip = float('Inf')
try:
recip = 1 / f(x)
except ZeroDivisionError:
logging.info('Infinite result')
else:
logging.info('Finite result')
Another example occurs in unittest runners:
try:
tests_run += 1
run_testcase(case)
except Exception:
tests_failed += 1
logging.exception('Failing test case: %r', case)
print('F', end='')
else:
logging.info('Successful test case: %r', case)
print('.', end='')
Lastly, the most common use of an else-clause in a try-block is for a bit of beautification (aligning the exceptional outcomes and non-exceptional outcomes at the same level of indentation). This use is always optional and isn't strictly necessary.
If you add helper fields to the coordinates table, you can improve response time of the query.
Like this:
CREATE TABLE `Coordinates` (
`id` INT(10) UNSIGNED NOT NULL COMMENT 'id for the object',
`type` TINYINT(4) UNSIGNED NOT NULL DEFAULT '0' COMMENT 'type',
`sin_lat` FLOAT NOT NULL COMMENT 'sin(lat) in radians',
`cos_cos` FLOAT NOT NULL COMMENT 'cos(lat)*cos(lon) in radians',
`cos_sin` FLOAT NOT NULL COMMENT 'cos(lat)*sin(lon) in radians',
`lat` FLOAT NOT NULL COMMENT 'latitude in degrees',
`lon` FLOAT NOT NULL COMMENT 'longitude in degrees',
INDEX `lat_lon_idx` (`lat`, `lon`)
)
If you're using TokuDB, you'll get even better performance if you add clustering indexes on either of the predicates, for example, like this:
alter table Coordinates add clustering index c_lat(lat);
alter table Coordinates add clustering index c_lon(lon);
You'll need the basic lat and lon in degrees as well as sin(lat) in radians, cos(lat)*cos(lon) in radians and cos(lat)*sin(lon) in radians for each point. Then you create a mysql function, smth like this:
CREATE FUNCTION `geodistance`(`sin_lat1` FLOAT,
`cos_cos1` FLOAT, `cos_sin1` FLOAT,
`sin_lat2` FLOAT,
`cos_cos2` FLOAT, `cos_sin2` FLOAT)
RETURNS float
LANGUAGE SQL
DETERMINISTIC
CONTAINS SQL
SQL SECURITY INVOKER
BEGIN
RETURN acos(sin_lat1*sin_lat2 + cos_cos1*cos_cos2 + cos_sin1*cos_sin2);
END
This gives you the distance.
Don't forget to add an index on lat/lon so the bounding boxing can help the search instead of slowing it down (the index is already added in the CREATE TABLE query above).
INDEX `lat_lon_idx` (`lat`, `lon`)
Given an old table with only lat/lon coordinates, you can set up a script to update it like this: (php using meekrodb)
$users = DB::query('SELECT id,lat,lon FROM Old_Coordinates');
foreach ($users as $user)
{
$lat_rad = deg2rad($user['lat']);
$lon_rad = deg2rad($user['lon']);
DB::replace('Coordinates', array(
'object_id' => $user['id'],
'object_type' => 0,
'sin_lat' => sin($lat_rad),
'cos_cos' => cos($lat_rad)*cos($lon_rad),
'cos_sin' => cos($lat_rad)*sin($lon_rad),
'lat' => $user['lat'],
'lon' => $user['lon']
));
}
Then you optimize the actual query to only do the distance calculation when really needed, for example by bounding the circle (well, oval) from inside and outside. For that, you'll need to precalculate several metrics for the query itself:
// assuming the search center coordinates are $lat and $lon in degrees
// and radius in km is given in $distance
$lat_rad = deg2rad($lat);
$lon_rad = deg2rad($lon);
$R = 6371; // earth's radius, km
$distance_rad = $distance/$R;
$distance_rad_plus = $distance_rad * 1.06; // ovality error for outer bounding box
$dist_deg_lat = rad2deg($distance_rad_plus); //outer bounding box
$dist_deg_lon = rad2deg($distance_rad_plus/cos(deg2rad($lat)));
$dist_deg_lat_small = rad2deg($distance_rad/sqrt(2)); //inner bounding box
$dist_deg_lon_small = rad2deg($distance_rad/cos(deg2rad($lat))/sqrt(2));
Given those preparations, the query goes something like this (php):
$neighbors = DB::query("SELECT id, type, lat, lon,
geodistance(sin_lat,cos_cos,cos_sin,%d,%d,%d) as distance
FROM Coordinates WHERE
lat BETWEEN %d AND %d AND lon BETWEEN %d AND %d
HAVING (lat BETWEEN %d AND %d AND lon BETWEEN %d AND %d) OR distance <= %d",
// center radian values: sin_lat, cos_cos, cos_sin
sin($lat_rad),cos($lat_rad)*cos($lon_rad),cos($lat_rad)*sin($lon_rad),
// min_lat, max_lat, min_lon, max_lon for the outside box
$lat-$dist_deg_lat,$lat+$dist_deg_lat,
$lon-$dist_deg_lon,$lon+$dist_deg_lon,
// min_lat, max_lat, min_lon, max_lon for the inside box
$lat-$dist_deg_lat_small,$lat+$dist_deg_lat_small,
$lon-$dist_deg_lon_small,$lon+$dist_deg_lon_small,
// distance in radians
$distance_rad);
EXPLAIN on the above query might say that it's not using index unless there's enough results to trigger such. The index will be used when there's enough data in the coordinates table. You can add FORCE INDEX (lat_lon_idx) to the SELECT to make it use the index with no regards to the table size, so you can verify with EXPLAIN that it is working correctly.
With the above code samples you should have a working and scalable implementation of object search by distance with minimal error.
The article linked to by MrMage is no longer working. So, here is what I've learned in my (very) short time coding in Objective-C:
nonatomic vs. atomic - "atomic" is the default. Always use "nonatomic". I don't know why, but the book I read said there is "rarely a reason" to use "atomic". (BTW: The book I read is the BNR "iOS Programming" book.)
readwrite vs. readonly - "readwrite" is the default. When you @synthesize, both a getter and a setter will be created for you. If you use "readonly", no setter will be created. Use it for a value you don't want to ever change after the instantiation of the object.
retain vs. copy vs. assign
If you need to insert into a specific position in the array, you can do this:
case ADD_ITEM :
return {
...state,
arr: [
...state.arr.slice(0, action.pos),
action.newItem,
...state.arr.slice(action.pos),
],
}
A programmer solution:
const int RADIUS = 64;
const int MATRIX_SIZE = RADIUS * 2;
bool matrix[MATRIX_SIZE][MATRIX_SIZE] = {0};
struct Point { int x; int y; };
Point lookupTable[MATRIX_SIZE * MATRIX_SIZE];
void init()
{
int numberOfOnBits = 0;
for (int x = 0 ; x < MATRIX_SIZE ; ++x)
{
for (int y = 0 ; y < MATRIX_SIZE ; ++y)
{
if (x * x + y * y < RADIUS * RADIUS)
{
matrix[x][y] = true;
loopUpTable[numberOfOnBits].x = x;
loopUpTable[numberOfOnBits].y = y;
++numberOfOnBits;
} // if
} // for
} // for
} // ()
Point choose()
{
int randomIndex = randomInt(numberOfBits);
return loopUpTable[randomIndex];
} // ()
The bitmap is only necessary for the explanation of the logic. This is the code without the bitmap:
const int RADIUS = 64;
const int MATRIX_SIZE = RADIUS * 2;
struct Point { int x; int y; };
Point lookupTable[MATRIX_SIZE * MATRIX_SIZE];
void init()
{
int numberOfOnBits = 0;
for (int x = 0 ; x < MATRIX_SIZE ; ++x)
{
for (int y = 0 ; y < MATRIX_SIZE ; ++y)
{
if (x * x + y * y < RADIUS * RADIUS)
{
loopUpTable[numberOfOnBits].x = x;
loopUpTable[numberOfOnBits].y = y;
++numberOfOnBits;
} // if
} // for
} // for
} // ()
Point choose()
{
int randomIndex = randomInt(numberOfBits);
return loopUpTable[randomIndex];
} // ()
First you need to use this command
npm config set registry https://registry.your-registry.npme.io/
This we are doing to set our companies Enterprise registry as our default registry.
You can try other given solutions also.
The ??
operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.
int? variable1 = null;
int variable2 = variable1 ?? 100;
Set variable2
to the value of variable1
, if variable1
is NOT null;
otherwise, if variable1 == null
, set variable2
to 100.
In my machine which is ubuntu 14.04 with python 2.7 installed, if I go here,
/usr/local/lib/python2.7/dist-packages/nltk/
there is a file called
VERSION
.
If I do a cat VERSION
it prints 3.1
, which is the NLTK version installed.
You need to use ajax.
http://api.jquery.com/jQuery.ajax/
<code>
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
</code>
The warning indicates that you're not returning something at the end of your map arrow function in every case.
A better approach to what you're trying to accomplish is first using a .filter
and then a .map
, like this:
this.props.comments
.filter(commentReply => commentReply.replyTo === comment.id)
.map((commentReply, idx) => <CommentItem key={idx} className="SubComment"/>);
In my case the error states that the assemly
Oracle.DataAccess, Version=2.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342
is missing.
When I run gacutil.exe /l 'Oracle.DataAccess'
the result was:
The Global Assembly Cache contains the following assemblies:
Oracle.DataAccess, Version=2.112.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
Number of items = 1
At this moment I have just installed the oracle client: win32_11gR2_client
Then I installed oracle developer tools ODTwithODAC112030_deleloper_tool
Now gacutil
is saying:
The Global Assembly Cache contains the following assemblies:
Oracle.DataAccess, Version=2.112.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
Oracle.DataAccess, Version=2.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
Number of items = 2
Fixed, one totally missing assembly case
Here is an excellent header only class template to measure the elapsed time of a function or any code block:
#ifndef EXECUTION_TIMER_H
#define EXECUTION_TIMER_H
template<class Resolution = std::chrono::milliseconds>
class ExecutionTimer {
public:
using Clock = std::conditional_t<std::chrono::high_resolution_clock::is_steady,
std::chrono::high_resolution_clock,
std::chrono::steady_clock>;
private:
const Clock::time_point mStart = Clock::now();
public:
ExecutionTimer() = default;
~ExecutionTimer() {
const auto end = Clock::now();
std::ostringstream strStream;
strStream << "Destructor Elapsed: "
<< std::chrono::duration_cast<Resolution>( end - mStart ).count()
<< std::endl;
std::cout << strStream.str() << std::endl;
}
inline void stop() {
const auto end = Clock::now();
std::ostringstream strStream;
strStream << "Stop Elapsed: "
<< std::chrono::duration_cast<Resolution>(end - mStart).count()
<< std::endl;
std::cout << strStream.str() << std::endl;
}
}; // ExecutionTimer
#endif // EXECUTION_TIMER_H
Here are some uses of it:
int main() {
{ // empty scope to display ExecutionTimer's destructor's message
// displayed in milliseconds
ExecutionTimer<std::chrono::milliseconds> timer;
// function or code block here
timer.stop();
}
{ // same as above
ExecutionTimer<std::chrono::microseconds> timer;
// code block here...
timer.stop();
}
{ // same as above
ExecutionTimer<std::chrono::nanoseconds> timer;
// code block here...
timer.stop();
}
{ // same as above
ExecutionTimer<std::chrono::seconds> timer;
// code block here...
timer.stop();
}
return 0;
}
Since the class is a template we can specify real easily in how we want our time to be measured & displayed. This is a very handy utility class template for doing bench marking and is very easy to use.
Rather than this expression to create a POSIX timestamp from dt
,
(dt - datetime(1970,1,1)).total_seconds()
Use this:
int(dt.strftime("%s"))
I get the right answer in your example using the second method.
EDIT: Some followup... After some comments (see below), I was curious about the lack of support or documentation for %s
in strftime
. Here's what I found:
In the Python source for datetime
and time
, the string STRFTIME_FORMAT_CODES
tells us:
"Other codes may be available on your platform.
See documentation for the C library strftime function."
So now if we man strftime
(on BSD systems such as Mac OS X), you'll find support for %s
:
"%s is replaced by the number of seconds since the Epoch, UTC (see mktime(3))."
Anyways, that's why %s
works on the systems it does. But there are better solutions to OP's problem (that take timezones into account). See @abarnert's accepted answer here.
JS Code:
function TodayDate(){
let data= new Date();
return data.getFullYear().toString()+'-' + (data.getMonth()+1).toString()+'-' + data.getDate().toString()
}
document.getElementById('today').innerHTML = '<input type="date" name="Data" value="'+TodayDate()+'" ><br>';
Html Code:
<div id="today" > </div>
A little bit rough but it works!
just add 'checked="checked"' in the correct radio button that you would like it to be default on. As example you could use php quick if notation to add that in:
<input type="radio" name="sex" value="Male" size="17" <?php echo($isMale?'checked="checked"':''); ?>>Male
<input type="radio" name="sex" value="Female" size="17" <?php echo($isFemale?'checked="checked"':''); ?>>Female
in this example $isMale & $isFemale is boolean values that you assign based on the value from your database.
You can use stri_paste
function with collapse
parameter from stringi
package like this:
stri_paste(letters, collapse='')
## [1] "abcdefghijklmnopqrstuvwxyz"
And some benchmarks:
require(microbenchmark)
test <- stri_rand_lipsum(100)
microbenchmark(stri_paste(test, collapse=''), paste(test,collapse=''), do.call(paste, c(as.list(test), sep="")))
Unit: microseconds
expr min lq mean median uq max neval
stri_paste(test, collapse = "") 137.477 139.6040 155.8157 148.5810 163.5375 226.171 100
paste(test, collapse = "") 404.139 406.4100 446.0270 432.3250 442.9825 723.793 100
do.call(paste, c(as.list(test), sep = "")) 216.937 226.0265 251.6779 237.3945 264.8935 405.989 100
For anyone running MySQL on Amazon RDS service, this change is done via parameter groups. You need to create a new PG or use an existing one (other than the default, which is read-only).
You should search for the max_allowed_packet
parameter, change its value, and then hit save.
Back in your MySQL instance, if you created a new PG, you should attach the PG to your instance (you may need a reboot). If you changed a PG that was already attached to your instance, changes will be applied without reboot, to all your instances that have that PG attached.
You can use multiple ssh keys on Windows 10 and specify the type of access allowed.
Assuming you have created the ssh secure keys already and they were stored in C:\Users\[User]\.ssh
Open the folder C:\Users\[User]\.ssh
Create the file config
(no file extension)
Open the file in a text editor like Notepad, and add these configuration details for the first remote host and user. Keep both CMD and BASH paths or only pick one format. Then copy-and-paste below it for the other host/user combinations and amend as required. Save the file.
Host [git.domain.com]
User [user]
Port [number]
IdentitiesOnly=yes
PreferredAuthentications publickey
PasswordAuthentication no
# CMD
IdentityFile C:\Users\[User]\.ssh\[name_of_PRIVATE_key_file]
# BASH
IdentityFile /c/Users/[User]/.ssh/[name_of_PRIVATE_key_file]
Testing
$ ssh -T git@[git.domain.com]
Welcome to GitLab, @[User]!
C:\Users\[User]>ssh -T git@[git.domain.com]
Welcome to GitLab, @[User]!
ssh -Tv git@[git.domain.com]
(or -Tvv
or -Tvvv
for higher verbosity levels).Try running the command
brew doctor
and let us know what sort of output you get
edit: And to answer the title question, this is from their FAQ :
Homebrew doesn’t write files outside its prefix. So generally you can just
rm -rf
the folder you installed it in.
So following that up with a clean re-install (following their latest recommended steps) should be your best bet.
To solve this simply add android:windowSoftInputMode="stateVisible|adjustPan
to that activity in android manifest file. for example
<activity
android:name="com.comapny.applicationname.activityname"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible|adjustPan"/>
Based on Fenton's answer, here's my implementation of a function to verify if a given object
has the keys an interface
has, both fully or partially.
Depending on your use case, you may also need to check the types of each of the interface's properties. The code below doesn't do that.
function implementsTKeys<T>(obj: any, keys: (keyof T)[]): obj is T {
if (!obj || !Array.isArray(keys)) {
return false;
}
const implementKeys = keys.reduce((impl, key) => impl && key in obj, true);
return implementKeys;
}
Example of usage:
interface A {
propOfA: string;
methodOfA: Function;
}
let objectA: any = { propOfA: '' };
// Check if objectA partially implements A
let implementsA = implementsTKeys<A>(objectA, ['propOfA']);
console.log(implementsA); // true
objectA.methodOfA = () => true;
// Check if objectA fully implements A
implementsA = implementsTKeys<A>(objectA, ['propOfA', 'methodOfA']);
console.log(implementsA); // true
objectA = {};
// Check again if objectA fully implements A
implementsA = implementsTKeys<A>(objectA, ['propOfA', 'methodOfA']);
console.log(implementsA); // false, as objectA now is an empty object
This Works for me in Windows 7 to 10 with parameters, when kick starting app or file from anywhere (including browser) and also when accessing file from anywhere. Replace (YOUR BATCH SCRIPT HERE anchor) with your code. This solution May Help :)
@echo off
call :isAdmin
if %errorlevel% == 0 (
goto :run
) else (
echo Requesting administrative privileges...
goto :UACPrompt
)
exit /b
:isAdmin
fsutil dirty query %systemdrive% >nul
exit /b
:run
<YOUR BATCH SCRIPT HERE>
exit /b
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "cmd.exe", "/c %~s0 %~1", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.pi
3.141592653589793
Check out the Python tutorial on modules and how to use them.
As for the second part of your question, Python comes with batteries included, of course:
>>> math.radians(90)
1.5707963267948966
>>> math.radians(180)
3.141592653589793
There are two ways to achieve what you want. Unfortunately, neither can be done using a view.
You can either create a table valued user defined function that takes the parameter you want and returns a query result
Or you can do pretty much the same thing but create a stored procedure instead of a user defined function.
For example:
the stored procedure would look like
CREATE PROCEDURE s_emp
(
@enoNumber INT
)
AS
SELECT
*
FROM
emp
WHERE
emp_id=@enoNumber
Or the user defined function would look like
CREATE FUNCTION u_emp
(
@enoNumber INT
)
RETURNS TABLE
AS
RETURN
(
SELECT
*
FROM
emp
WHERE
emp_id=@enoNumber
)
Google is going to shut the translate API down by the end of 2011, so you should be looking at the alternatives!
Generic toString() one-liner, using reflection and style customization:
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
...
public String toString()
{
return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
The rolling mean returns a Series
you only have to add it as a new column of your DataFrame
(MA
) as described below.
For information, the rolling_mean
function has been deprecated in pandas newer versions. I have used the new method in my example, see below a quote from the pandas documentation.
Warning Prior to version 0.18.0,
pd.rolling_*
,pd.expanding_*
, andpd.ewm*
were module level functions and are now deprecated. These are replaced by using theRolling
,Expanding
andEWM.
objects and a corresponding method call.
df['MA'] = df.rolling(window=5).mean()
print(df)
# Value MA
# Date
# 1989-01-02 6.11 NaN
# 1989-01-03 6.08 NaN
# 1989-01-04 6.11 NaN
# 1989-01-05 6.15 NaN
# 1989-01-09 6.25 6.14
# 1989-01-10 6.24 6.17
# 1989-01-11 6.26 6.20
# 1989-01-12 6.23 6.23
# 1989-01-13 6.28 6.25
# 1989-01-16 6.31 6.27
signal
isn't the most reliable way as it differs in implementations. I would recommend using sigaction
. Tom's code would now look like this :
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
void my_handler(int s){
printf("Caught signal %d\n",s);
exit(1);
}
int main(int argc,char** argv)
{
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = my_handler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
pause();
return 0;
}
On Unity3d, int.Parse
doesn't work well. So I use like bellow.
List<int> intList = new List<int>( Array.ConvertAll(sNumbers.Split(','),
new Converter<string, int>((s)=>{return Convert.ToInt32(s);}) ) );
Hope this help for Unity3d Users.
Are you sure you want to do this? In essence, you're duplicating the data that is in the three original columns. From that point on, you'll need to make sure that the data in the combined field matches the data in the first three columns. This is more overhead for your application, and other processes that update the system will need to understand the relationship.
If you need the data, why not select in when you need it? The SQL for selecting what would be in that field would be:
SELECT CONCAT(zipcode, ' - ', city, ', ', state) FROM Table;
This way, if the data in the fields changes, you don't have to update your combined field.
please don't try with the old cv module, use cv2:
import cv2
cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,0), 2)
x1,y1 ------
| |
| |
| |
--------x2,y2
[edit] to append the follow-up questions below:
cv2.imwrite("my.png",img)
cv2.imshow("lalala", img)
k = cv2.waitKey(0) # 0==wait forever
If you're working with server side code you could generate a random number and append it to the end of the src in the following manner....
src="yourJavascriptFile.js?randomNumber=434534"
with the randomNumber being randomly generated each time.
Try this
@echo off
setlocal enableextensions enabledelayedexpansion
set firstLine=1
for /f "delims=" %%i in (yourfilename.txt) do (
if !firstLine!==1 echo %%i
set firstLine=0
)
endlocal
If you are using a map()
operator on your response,you could maybe chain a toArray()
operator to it...then you should be able to iterate through newly created array...at least that worked for me :)
And to add multiple library files you can write as below:
INCLUDEPATH *= E:/DebugLibrary/VTK E:/DebugLibrary/VTK/Common E:/DebugLibrary/VTK/Filtering E:/DebugLibrary/VTK/GenericFiltering E:/DebugLibrary/VTK/Graphics E:/DebugLibrary/VTK/GUISupport/Qt E:/DebugLibrary/VTK/Hybrid E:/DebugLibrary/VTK/Imaging E:/DebugLibrary/VTK/IO E:/DebugLibrary/VTK/Parallel E:/DebugLibrary/VTK/Rendering E:/DebugLibrary/VTK/Utilities E:/DebugLibrary/VTK/VolumeRendering E:/DebugLibrary/VTK/Widgets E:/DebugLibrary/VTK/Wrapping
LIBS *= -LE:/DebugLibrary/VTKBin/bin/release -lvtkCommon -lvtksys -lQVTK -lvtkWidgets -lvtkRendering -lvtkGraphics -lvtkImaging -lvtkIO -lvtkFiltering -lvtkDICOMParser -lvtkpng -lvtktiff -lvtkzlib -lvtkjpeg -lvtkexpat -lvtkNetCDF -lvtkexoIIc -lvtkftgl -lvtkfreetype -lvtkHybrid -lvtkVolumeRendering -lQVTKWidgetPlugin -lvtkGenericFiltering
It should be
if (*message == '\0')
In C, simple quotes delimit a single character whereas double quotes are for strings.
Occurs when the text content of an element is changed through the user interface.
It's not quite an alias for keyup
because keyup
will fire even if the key does nothing (for example: pressing and then releasing the Control key will trigger a keyup
event).
A good way to think about it is like this: it's an event that triggers whenever the input changes. This includes -- but is not limited to -- pressing keys which modify the input (so, for example, Ctrl
by itself will not trigger the event, but Ctrl-V
to paste some text will), selecting an auto-completion option, Linux-style middle-click paste, drag-and-drop, and lots of other things.
See this page and the comments on this answer for more details.
You can check for a network connection in .NET 2.0 using GetIsNetworkAvailable()
:
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
To monitor changes in IP address or changes in network availability use the events from the NetworkChange class:
System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged
In the new desktop versions, you can add hyperlink by pressing ctrl + k and typing links.
"location" : null // this is not really an array it's a null object
"location" : [] // this is an empty array
It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.
you can modify search model like this
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => ['user_id ASC, document_id ASC']
]
]);
I want to present performance of different approaches, on Python 3.4, Linux x64. Excerpt from line profiler:
Line # Hits Time Per Hit % Time Line Contents
==============================================================
(...)
823 1508 11334 7.5 41.6 yday = int(period_end.strftime('%j'))
824 1508 2492 1.7 9.1 yday = period_end.toordinal() - date(period_end.year, 1, 1).toordinal() + 1
825 1508 1852 1.2 6.8 yday = (period_end - date(period_end.year, 1, 1)).days + 1
826 1508 5078 3.4 18.6 yday = period_end.timetuple().tm_yday
(...)
So most efficient is
yday = (period_end - date(period_end.year, 1, 1)).days
why not simplify it?
jquery
$('.clickable').on('click', function() {//on parent click
$(this).removeClass('spot').addClass('grown');//use remove/add Class here because it needs to perform the same action every time, you don't want a toggle
}).children('.close_button').on('click', function(e) {//on close click
e.stopPropagation();//stops click from triggering on parent
$(this).parent().toggleClass('spot grown');//since this only appears when .grown is present, toggling will work great instead of add/remove Class and save some space
});
This way it's much easier to maintain.
made a fiddle: http://jsfiddle.net/filever10/3SmaV/
This will happen when you doubleclick a JAR file in Windows explorer, but the JAR is by itself actually not an executable JAR. A real executable JAR should have at least a class with a main()
method and have it referenced in MANIFEST.MF
.
In Eclispe, you need to export the project as Runnable JAR file instead of as JAR file to get a real executable JAR.
Or, if your JAR is solely a container of a bunch of closely related classes (a library), then you shouldn't doubleclick it, but open it using some ZIP tool. Windows explorer namely by default associates JAR files with java.exe
, which won't work for those kind of libary JARs.
These instructions worked for me on apache-tomcat-8.5.20 on mac os 10.13.3 using jdk1.8.0_152:
$ cd /path/to/apache-tomcat-8.5.20/bin
$ export JPDA_ADDRESS="localhost:12321"
$ ./catalina.sh jpda run
Now connect to port 12321 from IntelliJ/Eclipse and enjoy remote debugging.
Found this workaround
.row {
margin-left: 0;
margin-right: 0;
}
[class^="col-"] > [class^="col-"]:first-child,
[class^="col-"] > [class*=" col-"]:first-child
[class*=" col-"] > [class^="col-"]:first-child,
[class*=" col-"]> [class*=" col-"]:first-child,
.row > [class^="col-"]:first-child,
.row > [class*=" col-"]:first-child{
padding-left: 0px;
}
[class^="col-"] > [class^="col-"]:last-child,
[class^="col-"] > [class*=" col-"]:last-child
[class*=" col-"] > [class^="col-"]:last-child,
[class*=" col-"]> [class*=" col-"]:last-child,
.row > [class^="col-"]:last-child,
.row > [class*=" col-"]:last-child{
padding-right: 0px;
}
I realize this question was posted a while ago; nonetheless, Bootstrap v4.0 has card layout support out of the box. You can find the documentation here: Bootstrap Card Layouts.
I've gotten back into using Bootstrap for a recent project that relies heavily on the card layout UI. I've found success with the following implementation across the standard breakpoints:
<link href="https://unpkg.com/[email protected]/css/tachyons.min.css" rel="stylesheet"/>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="flex justify-center" id="cars" v-cloak>_x000D_
<!-- RELEVANT MARKUP BEGINS HERE -->_x000D_
<div class="container mh0 w-100">_x000D_
<div class="page-header text-center mb5">_x000D_
<h1 class="avenir text-primary mb-0">Cars</h1>_x000D_
<p class="text-secondary">Add and manage your cars for sale.</p>_x000D_
<div class="header-button">_x000D_
<button class="btn btn-outline-primary" @click="clickOpenAddCarModalButton">Add a car for sale</button>_x000D_
</div>_x000D_
</div>_x000D_
<div class="container pa0 flex justify-center">_x000D_
<div class="listings card-columns">_x000D_
<div class="card mv2">_x000D_
<img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
alt="Mazda hatchback">_x000D_
<div class="card-body">_x000D_
<h5 class="card-title">Card title</h5>_x000D_
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
content._x000D_
</p>_x000D_
<a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
buttons here_x000D_
</div>_x000D_
</div>_x000D_
<div class="card mv2">_x000D_
<img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
alt="Mazda hatchback">_x000D_
<div class="card-body">_x000D_
<h5 class="card-title">Card title</h5>_x000D_
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
content._x000D_
</p>_x000D_
<a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
buttons here_x000D_
</div>_x000D_
</div>_x000D_
<div class="card mv2">_x000D_
<img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
alt="Mazda hatchback">_x000D_
<div class="card-body">_x000D_
<h5 class="card-title">Card title</h5>_x000D_
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
content._x000D_
</p>_x000D_
<a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
buttons here_x000D_
</div>_x000D_
</div>_x000D_
<div class="card mv2">_x000D_
<img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
alt="Mazda hatchback">_x000D_
<div class="card-body">_x000D_
<h5 class="card-title">Card title</h5>_x000D_
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
content._x000D_
</p>_x000D_
<a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
buttons here_x000D_
</div>_x000D_
</div>_x000D_
<div class="card mv2">_x000D_
<img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
alt="Mazda hatchback">_x000D_
<div class="card-body">_x000D_
<h5 class="card-title">Card title</h5>_x000D_
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
content._x000D_
</p>_x000D_
<a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
buttons here_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
After trying both the Bootstrap .card-group
and .card-deck
card layout classes with quirky results at best across the standard breakpoints, I finally decided to give the .card-columns
class a shot. And it worked!
Your results may vary, but .card-columns
seems to be the most stable implementation here.
There is one more important difference between a HashTable and Dictionary. If you use indexers to get a value out of a HashTable, the HashTable will successfully return null for a non-existent item, whereas the Dictionary will throw an error if you try accessing a item using a indexer which does not exist in the Dictionary
Just wanted to add to this, you can have the :not selector in oldIE using selectivizr: http://selectivizr.com/
This is a Python code that is working fine for me. Comments are in Spanish but the app is easy to understand
# coding=utf-8
from ftplib import FTP # Importamos la libreria ftplib desde FTP
import sys
def imprimirMensaje(): # Definimos la funcion para Imprimir el mensaje de bienvenida
print "------------------------------------------------------"
print "-- COMMAND LINE EXAMPLE --"
print "------------------------------------------------------"
print ""
print ">>> Cliente FTP en Python "
print ""
print ">>> python <appname>.py <host> <port> <user> <pass> "
print "------------------------------------------------------"
def f(s): # Funcion para imprimir por pantalla los datos
print s
def download(j): # Funcion para descargarnos el fichero que indiquemos según numero
print "Descargando=>",files[j]
fhandle = open(files[j], 'wb')
ftp.retrbinary('RETR ' + files[j], fhandle.write) # Imprimimos por pantalla lo que estamos descargando #fhandle.close()
fhandle.close()
ip = sys.argv[1] # Recogemos la IP desde la linea de comandos sys.argv[1]
puerto = sys.argv[2] # Recogemos el PUERTO desde la linea de comandos sys.argv[2]
usuario = sys.argv[3] # Recogemos el USUARIO desde la linea de comandos sys.argv[3]
password = sys.argv[4] # Recogemos el PASSWORD desde la linea de comandos sys.argv[4]
ftp = FTP(ip) # Creamos un objeto realizando una instancia de FTP pasandole la IP
ftp.login(usuario,password) # Asignamos al objeto ftp el usuario y la contraseña
files = ftp.nlst() # Ponemos en una lista los directorios obtenidos del FTP
for i,v in enumerate(files,1): # Imprimimos por pantalla el listado de directorios enumerados
print i,"->",v
print ""
i = int(raw_input("Pon un Nº para descargar el archivo or pulsa 0 para descargarlos\n")) # Introducimos algun numero para descargar el fichero que queramos. Lo convertimos en integer
if i==0: # Si elegimos el valor 0 nos decargamos todos los ficheros del directorio
for j in range(len(files)): # Hacemos un for para la lista files y
download(j) # llamamos a la funcion download para descargar los ficheros
if i>0 and i<=len(files): # Si elegimos unicamente un numero para descargarnos el elemento nos lo descargamos. Comprobamos que sea mayor de 0 y menor que la longitud de files
download(i-1) # Nos descargamos i-1 por el tema que que los arrays empiezan por 0