Try this:
colnames(DF) = DF[1, ] # the first row will be the header
DF = DF[-1, ] # removing the first row.
However, get a look if the data has been properly read. If you data.frame has numeric variables but the first row were characters, all the data has been read as character. To avoid this problem, it's better to save the data and read again with header=TRUE as you suggest. You can also get a look to this question: Reading a CSV file organized horizontally.
From this reference:
An int was originally intended to be the "natural" word size of the processor. Many modern processors can handle different word sizes with equal ease.
Also, this bit:
On many (but not all) C and C++ implementations, a long is larger than an int. Today's most popular desktop platforms, such as Windows and Linux, run primarily on 32 bit processors and most compilers for these platforms use a 32 bit int which has the same size and representation as a long.
Raymond Chen has a few ideas:
https://devblogs.microsoft.com/oldnewthing/20050128-00/?p=36573
Quoted here in full because MSDN archives tend to be somewhat unreliable:
The easy way is to use the
%CD%
pseudo-variable. It expands to the current working directory.
set OLDDIR=%CD%
.. do stuff ..
chdir /d %OLDDIR% &rem restore current directory
(Of course, directory save/restore could more easily have been done with
pushd
/popd
, but that's not the point here.)The
%CD%
trick is handy even from the command line. For example, I often find myself in a directory where there's a file that I want to operate on but... oh, I need to chdir to some other directory in order to perform that operation.
set _=%CD%\curfile.txt
cd ... some other directory ...
somecommand args %_% args
(I like to use
%_%
as my scratch environment variable.)Type
SET /?
to see the other pseudo-variables provided by the command processor.
Also the comments in the article are well worth scanning for example this one (via the WayBack Machine, since comments are gone from older articles):
http://blogs.msdn.com/oldnewthing/archive/2005/01/28/362565.aspx#362741
This covers the use of %~dp0:
If you want to know where the batch file lives:
%~dp0
%0
is the name of the batch file.~dp
gives you the drive and path of the specified argument.
When trying to silently install an MSI via PowerShell using this command:
Start-Process $webDeployInstallerFilePath -ArgumentList '/quiet' -Wait
I was getting the error:
The specified executable is not a valid application for this OS platform.
I instead switched to using msiexec.exe
to execute the MSI with this command, and it worked as expected:
$arguments = "/i `"$webDeployInstallerFilePath`" /quiet"
Start-Process msiexec.exe -ArgumentList $arguments -Wait
Hopefully others find this useful.
fs/promises and fs.Dirent
Here's an efficient, non-blocking ls
program using Node's fast fs.Dirent objects and fs/promises module. This approach allows you to skip wasteful fs.exist
or fs.stat
calls on every path -
// main.js
import { readdir } from "fs/promises"
import { join } from "path"
async function* ls (path = ".")
{ yield path
for (const dirent of await readdir(path, { withFileTypes: true }))
if (dirent.isDirectory())
yield* ls(join(path, dirent.name))
else
yield join(path, dirent.name)
}
async function* empty () {}
async function toArray (iter = empty())
{ let r = []
for await (const x of iter)
r.push(x)
return r
}
toArray(ls(".")).then(console.log, console.error)
Let's get some sample files so we can see ls
working -
$ yarn add immutable # (just some example package)
$ node main.js
[
'.',
'main.js',
'node_modules',
'node_modules/.yarn-integrity',
'node_modules/immutable',
'node_modules/immutable/LICENSE',
'node_modules/immutable/README.md',
'node_modules/immutable/contrib',
'node_modules/immutable/contrib/cursor',
'node_modules/immutable/contrib/cursor/README.md',
'node_modules/immutable/contrib/cursor/__tests__',
'node_modules/immutable/contrib/cursor/__tests__/Cursor.ts.skip',
'node_modules/immutable/contrib/cursor/index.d.ts',
'node_modules/immutable/contrib/cursor/index.js',
'node_modules/immutable/dist',
'node_modules/immutable/dist/immutable-nonambient.d.ts',
'node_modules/immutable/dist/immutable.d.ts',
'node_modules/immutable/dist/immutable.es.js',
'node_modules/immutable/dist/immutable.js',
'node_modules/immutable/dist/immutable.js.flow',
'node_modules/immutable/dist/immutable.min.js',
'node_modules/immutable/package.json',
'package.json',
'yarn.lock'
]
For added explanation and other ways to leverage async generators, see this Q&A.
The easiest way to do this is to make use of Apache Commons Lang. It has a handy ArrayUtils class that can do what you want. Use the toPrimitive
method with the overload for an array of Integer
s.
List<Integer> myList;
... assign and fill the list
int[] intArray = ArrayUtils.toPrimitive(myList.toArray(new Integer[myList.size()]));
This way you don't reinvent the wheel. Commons Lang has a great many useful things that Java left out. Above, I chose to create an Integer list of the right size. You can also use a 0-length static Integer array and let Java allocate an array of the right size:
static final Integer[] NO_INTS = new Integer[0];
....
int[] intArray2 = ArrayUtils.toPrimitive(myList.toArray(NO_INTS));
There is no equivalent of C# async/await in Java at the language level. A concept known as Fibers aka cooperative threads aka lightweight threads could be an interesting alternative. You can find Java libraries providing support for fibers.
Java libraries implementing Fibers
You can read this article (from Quasar) for a nice introduction to fibers. It covers what threads are, how fibers can be implemented on the JVM and has some Quasar specific code.
You've mentioned that they each have their own machines, but if they need to log onto a co-workers machine, and then use the file, saving it through "C:\Users\Public\Desktop\" will make it available to different usernames.
Public Sub SaveToDesktop()
ThisWorkbook.SaveAs Filename:="C:\Users\Public\Desktop\" & ThisWorkbook.Name & "_copy", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub
I'm not sure whether this would be a requirement, but may help!
I solving doing this:
Remove the target commit
git revert --strategy resolve 222
Save commit 222 to patch file
git diff HEAD~2 HEAD~1 > 222.patch
Apply this patch to unstage
patch -p1 < 222.patch
Push to stash
git stash
Remove temp file
rm -f 222.patch
Very simple strategy in my opinion
Swift 4
Register Nib
override func viewDidLoad() {
super.viewDidLoad()
tblMissions.register(UINib(nibName: "MissionCell", bundle: nil), forCellReuseIdentifier: "MissionCell")
}
In TableView DataSource
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "MissionCell", for: indexPath) as? MissionCell else { return UITableViewCell() }
return cell
}
FYI, this is probably faster,
SELECT count(1) FROM (SELECT distinct productId WHERE keyword = '$keyword') temp
than this,
SELECT COUNT(DISTINCT productId) WHERE keyword='$keyword'
Refer to here
write query with named parameter, use simple ListPreparedStatementSetter
with all parameters in sequence. Just add below snippet to convert the query in traditional form based to available parameters,
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);
List<Integer> parameters = new ArrayList<Integer>();
for (A a : paramBeans)
parameters.add(a.getId());
MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("placeholder1", parameters);
// create SQL with ?'s
String sql = NamedParameterUtils.substituteNamedParameters(parsedSql, parameterSource);
return sql;
Lets go over 4 methods
>>>
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l.insert(0, 5)
>>> l
[5, 0, 1, 2, 3, 4]
>>>
>>>
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l = [5] + l
>>> l
[5, 0, 1, 2, 3, 4]
>>>
>>>
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l[:0] = [5]
>>> l
[5, 0, 1, 2, 3, 4]
>>>
>>>
>>> from collections import deque
>>>
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l = deque(l)
>>> l.appendleft(5)
>>> l = list(l)
>>> l
[5, 0, 1, 2, 3, 4]
>>>
Leaving my specific solution of this for prosperity, as it's a tricky version of this problem:
Type 'System.Linq.Enumerable+WhereSelectArrayIterator[T...] was not marked as serializable
Due to a class with an attribute IEnumerable<int>
eg:
[Serializable]
class MySessionData{
public int ID;
public IEnumerable<int> RelatedIDs; //This can be an issue
}
Originally the problem instance of MySessionData
was set from a non-serializable list:
MySessionData instance = new MySessionData(){
ID = 123,
RelatedIDs = nonSerizableList.Select<int>(item => item.ID)
};
The cause here is the concrete class that the Select<int>(...)
returns, has type data that's not serializable, and you need to copy the id's to a fresh List<int>
to resolve it.
RelatedIDs = nonSerizableList.Select<int>(item => item.ID).ToList();
You can also use google-collections (guava) Joiner class if you want to customize the print format
If you really just want to subset each data frame by an index that exists in both data frames, you can do this with the 'match' function, like so:
data_A[match(data_B$index, data_A$index, nomatch=0),]
data_B[match(data_A$index, data_B$index, nomatch=0),]
This is, though, the same as:
data_A[data_A$index %in% data_B$index,]
data_B[data_B$index %in% data_A$index,]
Here is a demo:
# Set seed for reproducibility.
set.seed(1)
# Create two sample data sets.
data_A <- data.frame(index=sample(1:200, 90, rep=FALSE), value=runif(90))
data_B <- data.frame(index=sample(1:200, 120, rep=FALSE), value=runif(120))
# Subset data of each data frame by the index in the other.
t_A <- data_A[match(data_B$index, data_A$index, nomatch=0),]
t_B <- data_B[match(data_A$index, data_B$index, nomatch=0),]
# Make sure they match.
data.frame(t_A[order(t_A$index),], t_B[order(t_B$index),])[1:20,]
# index value index.1 value.1
# 27 3 0.7155661 3 0.65887761
# 10 12 0.6049333 12 0.14362694
# 88 14 0.7410786 14 0.42021589
# 56 15 0.4525708 15 0.78101754
# 38 18 0.2075451 18 0.70277874
# 24 23 0.4314737 23 0.78218212
# 34 32 0.1734423 32 0.85508236
# 22 38 0.7317925 38 0.56426384
# 84 39 0.3913593 39 0.09485786
# 5 40 0.7789147 40 0.31248966
# 74 43 0.7799849 43 0.10910096
# 71 45 0.2847905 45 0.26787813
# 57 46 0.1751268 46 0.17719454
# 25 48 0.1482116 48 0.99607737
# 81 53 0.6304141 53 0.26721208
# 60 58 0.8645449 58 0.96920881
# 30 59 0.6401010 59 0.67371223
# 75 61 0.8806190 61 0.69882454
# 63 64 0.3287773 64 0.36918946
# 19 70 0.9240745 70 0.11350771
You could use POSIX [[:blank:]]
to match a horizontal white-space character.
sed 's/[[:blank:]]\+/\n/g' file
or you may use [[:space:]]
instead of [[:blank:]]
also.
Example:
$ echo 'this is a sentence' | sed 's/[[:blank:]]\+/\n/g'
this
is
a
sentence
I did basically the same thing that you did Adam, but with a slight modification to make sure I was appending to the head tag to get the job done. I simply created an include function (code below) to handle both script and css files.
This function also checks to make sure that the script or CSS file hasn't already been loaded dynamically. It does not check for hand coded values and there may have been a better way to do that, but it served the purpose.
function include( url, type ){
// First make sure it hasn't been loaded by something else.
if( Array.contains( includedFile, url ) )
return;
// Determine the MIME-type
var jsExpr = new RegExp( "js$", "i" );
var cssExpr = new RegExp( "css$", "i" );
if( type == null )
if( jsExpr.test( url ) )
type = 'text/javascript';
else if( cssExpr.test( url ) )
type = 'text/css';
// Create the appropriate element.
var tag = null;
switch( type ){
case 'text/javascript' :
tag = document.createElement( 'script' );
tag.type = type;
tag.src = url;
break;
case 'text/css' :
tag = document.createElement( 'link' );
tag.rel = 'stylesheet';
tag.type = type;
tag.href = url;
break;
}
// Insert it to the <head> and the array to ensure it is not
// loaded again.
document.getElementsByTagName("head")[0].appendChild( tag );
Array.add( includedFile, url );
}
This is just complementary knowledge to all the other explanations here - I am not suggesting to use .constructor
everywhere.
TL;DR: In situations where typeof
is not an option, and when you know that you do not care about the prototype chain, Object.prototype.constructor
can be a viable or even better alternative than instanceof
:
x instanceof Y
x.constructor === Y
It's been in the standard since 1.1, so no worries about backwards compatibility.
Muhammad Umer briefly mentioned this in a comment somewhere here too. It works on everything with a prototype - so everything not null
or undefined
:
// (null).constructor; // TypeError: null has no properties
// (undefined).constructor; // TypeError: undefined has no properties
(1).constructor; // function Number
''.constructor; // function String
([]).constructor; // function Array
(new Uint8Array(0)).constructor; // function Uint8Array
false.constructor; // function Boolean()
true.constructor; // function Boolean()
(Symbol('foo')).constructor; // function Symbol()
// Symbols work, just remember that this is not an actual constructor:
// new Symbol('foo'); //TypeError: Symbol is not a constructor
Array.prototype === window.frames.Array; // false
Array.constructor === window.frames.Array.constructor; // true
Furthermore, depending on your use case it can be a lot faster than instanceof
(the reason likely being that it doesn't have to check the entire prototype chain). In my case I needed a fast way to check if a value is a typed array:
function isTypedArrayConstructor(obj) {
switch (obj && obj.constructor){
case Uint8Array:
case Float32Array:
case Uint16Array:
case Uint32Array:
case Int32Array:
case Float64Array:
case Int8Array:
case Uint8ClampedArray:
case Int16Array:
return true;
default:
return false;
}
}
function isTypedArrayInstanceOf(obj) {
return obj instanceof Uint8Array ||
obj instanceof Float32Array ||
obj instanceof Uint16Array ||
obj instanceof Uint32Array ||
obj instanceof Int32Array ||
obj instanceof Float64Array ||
obj instanceof Int8Array ||
obj instanceof Uint8ClampedArray ||
obj instanceof Int16Array;
}
https://run.perf.zone/view/isTypedArray-constructor-vs-instanceof-1519140393812
And the results:
Chrome 64.0.3282.167 (64-bit, Windows)
Firefox 59.0b10 (64-bit, Windows)
Out of curiousity, I did a quick toy benchmark against typeof
; surprisingly it doesn't perform much worse, and it seems even a bit faster in Chrome:
let s = 0,
n = 0;
function typeofSwitch(t) {
switch (typeof t) {
case "string":
return ++s;
case "number":
return ++n;
default:
return 0;
}
}
// note: no test for null or undefined here
function constructorSwitch(t) {
switch (t.constructor) {
case String:
return ++s;
case Number:
return ++n;
default:
return 0;
}
}
let vals = [];
for (let i = 0; i < 1000000; i++) {
vals.push(Math.random() <= 0.5 ? 0 : 'A');
}
https://run.perf.zone/view/typeof-vs-constructor-string-or-number-1519142623570
NOTE: Order in which functions are listed switches between images!
Chrome 64.0.3282.167 (64-bit, Windows)
Firefox 59.0b10 (64-bit, Windows)
NOTE: Order in which functions are listed switches between images!
kindly executed these commands.
pip install google
pip install google-core-api
will definitely solve your problem
There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.
This can not have a variable:
create function Func() returns table
as
return
select 10 as ColName
You have to do like this instead:
create function Func()
returns @T table(ColName int)
as
begin
declare @Var int
set @Var = 10
insert into @T(ColName) values (@Var)
return
end
you can include maven dependency like below in your pom.xml file
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
Please see http://msdn.microsoft.com/en-us/library/aa260631(v=SQL.80).aspx In SQL server a timestamp is not the same as a DateTime column. This is used to uniquely identify a row in a database, not just a table but the entire database. This can be used for optimistic concurrency. for example UPDATE [Job] SET [Name]=@Name, [XCustomData]=@XCustomData WHERE ([ModifiedTimeStamp]=@Original_ModifiedTimeStamp AND [GUID]=@Original_GUID
the ModifiedTimeStamp ensures that you are updating the original data and will fail if another update has occurred to the row.
Mentioning this because you mentioned "when developing".
You can control the mobile device via your Chrome Desktop Browser.
Visit chrome://inspect/#devices
on your desktop. And Inspect
the device that's connected to your desktop. Agree when asked for permission.
You should now see a full fledged Devtool window for the current page on mobile device.
Now, Use the hard reload shortcut (Cmd+Shift+R) on desktop to do hard reload on mobile device!
echo -e "\033[31m Hello World"
The [31m
controls the text color:
30
-37
sets foreground color40
-47
sets background colorA more complete list of color codes can be found here.
It is good practice to reset the text color back to \033[0m
at the end of the string.
You actually cannot draw Container Elements
But you can use a "foreignObject" with a "SVG" inside it to simulate what you need.
<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">
<foreignObject id="G" width="300" height="200">
<svg>
<rect fill="blue" stroke-width="2" height="112" width="84" y="55" x="55" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke="#000000"/>
<ellipse fill="#FF0000" stroke="#000000" stroke-width="5" stroke-dasharray="null" stroke-linejoin="null" stroke-linecap="null" cx="155" cy="65" id="svg_7" rx="64" ry="56"/>
</svg>
<style>
#G {
background: #cff; border: 1px dashed black;
}
#G:hover {
background: #acc; border: 1px solid black;
}
</style>
</foreignObject>
</svg>
since the solutions with new FileInfo(filePath)
are not easily testable, I suggest to use Wrappers for classes like Directory
, File
and Path
like this:
public interface IDirectory
{
string[] GetFiles(string path);
}
public sealed class DirectoryWrapper : IDirectory
{
public string[] GetFiles(string path) => Directory.GetFiles(path);
}
public interface IFile
{
void Delete(string path);
DateTime GetLastAccessTime(string path);
}
public sealed class FileWrapper : IFile
{
public void Delete(string path) => File.Delete(path);
public DateTime GetLastAccessTimeUtc(string path) => File.GetLastAccessTimeUtc(path);
}
Then use something like this:
public sealed class FooBar
{
public FooBar(IFile file, IDirectory directory)
{
File = file;
Directory = directory;
}
private IFile File { get; }
private IDirectory Directory { get; }
public void DeleteFilesBeforeTimestamp(string path, DateTime timestamp)
{
if(!Directory.Exists(path))
throw new DirectoryNotFoundException($"The path {path} was not found.");
var files = Directory
.GetFiles(path)
.Select(p => new
{
Path = p,
// or File.GetLastWriteTime() or File.GetCreationTime() as needed
LastAccessTimeUtc = File.GetLastAccessTimeUtc(p)
})
.Where(p => p.LastAccessTimeUtc < timestamp);
foreach(var file in files)
{
File.Delete(file.Path);
}
}
}
The second time you're referring to div2, you're not using the # id selector.
There's no element named div2.
get-aduser -Server "servername" -Identity %username% -Properties *
get-aduser -Server "testdomain.test.net" -Identity testuser -Properties *
These work when you have the username. Also less to type than using the -filter
property.
EDIT: Formatting.
Since this must have an input element as a parent, you could just use
<input type="text" ng-model="foo" ng-change="myOnChangeFunction()">
Alternatively, you could use the ngModelController
and add a function to $formatters
, which executes functions on input change. See http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController
.directive("myDirective", function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
ngModel.$formatters.push(function(value) {
// Do stuff here, and return the formatted value.
});
};
};
I was having same issue. A stop should stop the stream and onplay go to live if it is a radio. All solutions I saw had a disadvantage:
player.currentTime = 0
keeps downloading the stream.player.src = ''
raise error
eventMy solution:
var player = document.getElementById('radio');
player.pause();
player.src = player.src;
And the HTML
<audio src="http://radio-stream" id="radio" class="hidden" preload="none"></audio>
Include the phrase:
@echo off
Right at the top of your bat script.
It's enabled by default. Probably you just tried on an expression that failed to autocomplete.
In case you deactivated it somehow... you can enable it in the Visual Studio settings. Just browse to the Editor settings, then to the subgroup C/C++ and activate it again... should read something like "List members automatically" or "Auto list members" (sorry, I have the german Visual Studio).
Upon typing something like std::cout. a dropwdownlist with possible completitions should pop up.
In addition to the above I personally recommend
onKeyUp():
Programatically Speaking keydown will fire when the user depresses a key initially but It will repeat while the user keeps the key depressed.*
This remains true for all development platforms.
Google development suggested that if you are intercepting the BACK button in a view you should track the KeyEvent with starttracking on keydown then invoke with keyup.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
event.startTracking();
return true;
}
return super.onKeyDown(keyCode, event);
}
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
&& !event.isCanceled()) {
// *** Your Code ***
return true;
}
return super.onKeyUp(keyCode, event);
}
You can reset your branch to the state it was in just before the merge if you find the commit it was on then.
One way is to use git reflog
, it will list all the HEADs you've had.
I find that git reflog --relative-date
is very useful as it shows how long ago each change happened.
Once you find that commit just do a git reset --hard <commit id>
and your branch will be as it was before.
If you have SourceTree, you can look up the <commit id>
there if git reflog
is too overwhelming.
Try this:
private void btnAtt_Click(object sender, EventArgs e) {
openFileDialog1.ShowDialog();
Attachment myFile = new Attachment(openFileDialog1.FileName);
MyMsg.Attachments.Add(myFile);
}
If you extend String object like this..
String.prototype.float = function() {
return parseFloat(this.replace(',', '.'));
}
.. you can run it like this
"554,20".float()
> 554.20
works with dot as well
"554.20".float()
> 554.20
typeof "554,20".float()
> "number"
"val means immutable and var means mutable."
To paraphrase, "val means value and var means variable".
A distinction that happens to be extremely important in computing (because those two concepts define the very essence of what programming is all about), and that OO has managed to blur almost completely, because in OO, the only axiom is that "everything is an object". And that as a consequence, lots of programmers these days tend not to understand/appreciate/recognize, because they have been brainwashed into "thinking the OO way" exclusively. Often leading to variable/mutable objects being used like everywhere, when value/immutable objects might/would often have been better.
you can add builder.show(); after validation message before return;
like this
public void login()
{
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(R.layout.login_layout);
builder.setTitle("Login");
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});// put the negative button before the positive button, so it will appear
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int id)
{
Dialog d = (Dialog) dialog;
final EditText etUserName = (EditText) d.findViewById(R.id.etLoginName);
final EditText etPassword = (EditText) d.findViewById(R.id.etLoginPassword);
String userName = etUserName.getText().toString().trim();
String password = etPassword.getText().toString().trim();
if (userName.isEmpty() || password.isEmpty())
{
Toast.makeText(getApplicationContext(),
"Please Fill all fields", Toast.LENGTH_SHORT).show();
builder.show();// here after validation message before retrun
// it will reopen the dialog
// till the user enter the right condition
return;
}
user = Manager.get(getApplicationContext()).getUserByName(userName);
if (user == null)
{
Toast.makeText(getApplicationContext(),
"Error ethier username or password are wrong", Toast.LENGTH_SHORT).show();
builder.show();
return;
}
if (password.equals(user.getPassword()))
{
etPassword.setText("");
etUserName.setText("");
setLogged(1);
setLoggedId(user.getUserId());
Toast.makeText(getApplicationContext(),
"Successfully logged in", Toast.LENGTH_SHORT).show();
dialog.dismiss();// if every thing is ok then dismiss the dialog
}
else
{
Toast.makeText(getApplicationContext(),
"Error ethier username or password are wrong", Toast.LENGTH_SHORT).show();
builder.show();
return;
}
}
});
builder.show();
}
Append new column in existing csv file using python without header name
default_text = 'Some Text'
# Open the input_file in read mode and output_file in write mode
with open('problem-one-answer.csv', 'r') as read_obj, \
open('output_1.csv', 'w', newline='') as write_obj:
# Create a csv.reader object from the input file object
csv_reader = reader(read_obj)
# Create a csv.writer object from the output file object
csv_writer = csv.writer(write_obj)
# Read each row of the input csv file as list
for row in csv_reader:
# Append the default text in the row / list
row.append(default_text)
# Add the updated row / list to the output file
csv_writer.writerow(row)
Thankyou
Use the Figure.savefig()
method, like so:
ax = s.hist() # s is an instance of Series
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')
It doesn't have to end in pdf
, there are many options. Check out the documentation.
Alternatively, you can use the pyplot
interface and just call the savefig
as a function to save the most recently created figure:
import matplotlib.pyplot as plt
s.hist()
plt.savefig('path/to/figure.pdf') # saves the current figure
Open a connection to your server first (SQL IDE) from the home screen. Then use the context menu in the schema tree to run a query that simply selects rows from the selected table. The LIMIT attached to that is to avoid reading too many rows by accident. This limit can be switched off (or adjusted) in the preferences dialog.
This quick way to select rows is however not very flexible. Normally you would run a query (File / New Query Tab) in the editor with additional conditions, like a sort order:
Here is a better way of doing it: if you are getting the data from API. Then PARSE the JSON and loading it onto your listview:
protected void onPostExecute(String result) {
Log.v(TAG + " result);
if (!result.equals("")) {
// Set up variables for API Call
ArrayList<String> list = new ArrayList<String>();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.get(i).toString());
}//end for
} catch (JSONException e) {
Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
e.printStackTrace();
}
adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText( ListViewData.this, "Position :" + itemPosition + " ListItem : " + itemValue, Toast.LENGTH_LONG).show();
}
});
adapter.notifyDataSetChanged();
adapter.notifyDataSetChanged();
...
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
Try this:
$('#id').change();
Works for me.
On one line together with setting the value:
$('#id').val(16).change();
There is no portable function that allows to check if a key is hit and continue if not. This is always system dependent.
Solution for linux and other posix compliant systems:
Here, for Morgan Mattews's code provide kbhit()
functionality in a way compatible with any POSIX compliant system. He uses the trick of desactivating buffering at termios level.
Solution for windows:
For windows, Microsoft offers _kbhit()
I don't know the direct answer to your question, but if you do a lot of these scripts, it might be worth learning a more powerful language like perl. Free implementations exist for Windows (e.g. activestate, cygwin). I've found it worth the initial effort for my own tasks.
Edit:
As suggested by @Ferruccio, if you can't install extra software, consider vbscript and/or javascript. They're built into the Windows scripting host.
Please set http content type in header and also make sure the server is authenticating CORS. This is how to do it in PHP:
//NOT A TESTED CODE
header('Content-Type: application/json;charset=UTF-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: DELETE, HEAD, GET, OPTIONS, POST, PUT');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
header('Access-Control-Max-Age: 1728000');
Please refer to:
http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0
The --force
option is useful for refreshing the local tags. Mainly if you have floating tags:
git fetch --tags --force
The git pull option has also the --force
options, and the description is the same:
When git fetch is used with <rbranch>:<lbranch> refspec, it refuses to update the local branch <lbranch> unless the remote branch <rbranch> it fetches is a descendant of <lbranch>. This option overrides that check.
but, according to the doc of --no-tags
:
By default, tags that point at objects that are downloaded from the remote repository are fetched and stored locally.
If that default statement is not a restriction, then you can also try
git pull --force
As Mike Nakis said, echo off
only prevents the printing of commands, not results. To hide the result of a command add >nul
to the end of the line, and to hide errors add 2>nul
. For example:
Del /Q *.tmp >nul 2>nul
Like Krister Andersson said, the reason you get an error is your variable is expanding with spaces:
set INSTALL_PATH=C:\My App\Installer
if exist %INSTALL_PATH% (
Becomes:
if exist C:\My App\Installer (
Which means:
If "C:\My" exists, run "App\Installer" with "(" as the command line argument.
You see the error because you have no folder named "App". Put quotes around the path to prevent this splitting.
To be quite honest, regular expressions are not the best idea for this type of parsing. The regular expression you posted will probably work great for simple cases, but if things get more complex you are going to have huge problems (same reason why you cant reliably parse HTML with regular expressions). I know you probably don't want to hear this, I know I didn't when I asked the same type of questions, but string parsing became WAY more reliable for me after I stopped trying to use regular expressions for everything.
jTopas is an AWESOME tokenizer that makes it quite easy to write parsers by hand (I STRONGLY suggest jtopas over the standard java scanner/etc.. libraries). If you want to see jtopas in action, here are some parsers I wrote using jTopas to parse this type of file
If you are parsing XML files, you should be using an xml parser library. Dont do it youself unless you are just doing it for fun, there are plently of proven options out there
iBeacon Profile contains 31 Bytes which includes the followings
If an algorithm is of T(g(n)), it means that the running time of the algorithm as n (input size) gets larger is proportional to g(n).
If an algorithm is of O(g(n)), it means that the running time of the algorithm as n gets larger is at most proportional to g(n).
Normally, even when people talk about O(g(n)) they actually mean T(g(n)) but technically, there is a difference.
O(n) represents upper bound. T(n) means tight bound. O(n) represents lower bound.
f(x) = T(g(x)) iff f(x) = O(g(x)) and f(x) = O(g(x))
Basically when we say an algorithm is of O(n), it's also O(n2), O(n1000000), O(2n), ... but a T(n) algorithm is not T(n2).
In fact, since f(n) = T(g(n)) means for sufficiently large values of n, f(n) can be bound within c1g(n) and c2g(n) for some values of c1 and c2, i.e. the growth rate of f is asymptotically equal to g: g can be a lower bound and and an upper bound of f. This directly implies f can be a lower bound and an upper bound of g as well. Consequently,
f(x) = T(g(x)) iff g(x) = T(f(x))
Similarly, to show f(n) = T(g(n)), it's enough to show g is an upper bound of f (i.e. f(n) = O(g(n))) and f is a lower bound of g (i.e. f(n) = O(g(n)) which is the exact same thing as g(n) = O(f(n))). Concisely,
f(x) = T(g(x)) iff f(x) = O(g(x)) and g(x) = O(f(x))
There are also little-oh and little-omega (?
) notations representing loose upper and loose lower bounds of a function.
To summarize:
f(x) = O(g(x))
(big-oh) means that the growth rate off(x)
is asymptotically less than or equal to to the growth rate ofg(x)
.
f(x) = O(g(x))
(big-omega) means that the growth rate off(x)
is asymptotically greater than or equal to the growth rate ofg(x)
f(x) = o(g(x))
(little-oh) means that the growth rate off(x)
is asymptotically less than the growth rate ofg(x)
.
f(x) = ?(g(x))
(little-omega) means that the growth rate off(x)
is asymptotically greater than the growth rate ofg(x)
f(x) = T(g(x))
(theta) means that the growth rate off(x)
is asymptotically equal to the growth rate ofg(x)
For a more detailed discussion, you can read the definition on Wikipedia or consult a classic textbook like Introduction to Algorithms by Cormen et al.
It's seems the obvious answer was missing. To get all data from a table (Ttable) where the column (DatetimeColumn) is a datetime with a timestamp the following query can be used:
SELECT * FROM Ttable
WHERE DATEDIFF(day,Ttable.DatetimeColumn ,GETDATE()) = 1 -- yesterday
This can easily be changed to today, last month, last year, etc.
Here is how I would do it if working with a large number of "to remove" values that would take a long time to manually remove.
As mentioned here, https://stackoverflow.com/a/50941562/2186220, use gradle plugin version 3 or higher while using 'implementation'.
Also, use the google()
repository in buildscript
.
buildscript {
repositories {
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.2'
}
}
These changes should solve the issue.
Either one of the below three options gets rid of the message (but for different reasons and with different side-effects I suppose):
node_modules
directory or explicitly include
the directory where your app resides (which presumably does not contain files in excess of 100KB)compact
to true
(actually any value other than "auto")compact
to false
(see above)#1 in the above list can be achieved by either excluding the node_modules
directory or be explicitly including the directory where your app resides.
E.g. in webpack.config.js
:
let path = require('path');
....
module: {
loaders: [
...
loader: 'babel',
exclude: path.resolve(__dirname, 'node_modules/')
... or by using include: path.resolve(__dirname, 'app/')
(again in webpack.config.js
).
#2 and #3 in the above list can be accomplished by the method suggested in this answer or (my preference) by editing the .babelrc
file. E.g.:
$ cat .babelrc
{
"presets": ["es2015", "react"],
"compact" : true
}
Tested with the following setup:
$ npm ls --depth 0 | grep babel
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
C++11 Thread safe implementation:
#include <iostream>
#include <thread>
class Singleton
{
private:
static Singleton * _instance;
static std::mutex mutex_;
protected:
Singleton(const std::string value): value_(value)
{
}
~Singleton() {}
std::string value_;
public:
/**
* Singletons should not be cloneable.
*/
Singleton(Singleton &other) = delete;
/**
* Singletons should not be assignable.
*/
void operator=(const Singleton &) = delete;
//static Singleton *GetInstance(const std::string& value);
static Singleton *GetInstance(const std::string& value)
{
if (_instance == nullptr)
{
std::lock_guard<std::mutex> lock(mutex_);
if (_instance == nullptr)
{
_instance = new Singleton(value);
}
}
return _instance;
}
std::string value() const{
return value_;
}
};
/**
* Static methods should be defined outside the class.
*/
Singleton* Singleton::_instance = nullptr;
std::mutex Singleton::mutex_;
void ThreadFoo(){
std::this_thread::sleep_for(std::chrono::milliseconds(10));
Singleton* singleton = Singleton::GetInstance("FOO");
std::cout << singleton->value() << "\n";
}
void ThreadBar(){
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
Singleton* singleton = Singleton::GetInstance("BAR");
std::cout << singleton->value() << "\n";
}
int main()
{
std::cout <<"If you see the same value, then singleton was reused (yay!\n" <<
"If you see different values, then 2 singletons were created (booo!!)\n\n" <<
"RESULT:\n";
std::thread t1(ThreadFoo);
std::thread t2(ThreadBar);
t1.join();
t2.join();
std::cout << "Complete!" << std::endl;
return 0;
}
Neither text-align:center
nor display:inline-block
worked for me on their own, but combining both did:
ul {
text-align: center;
}
li {
display: inline-block;
}
You may also get that error when CSRF "token" for the active user session is out of date, even if the token was specified in ajax request.
A simple example where the operator checks if player's id is 1 and sets enemy id depending on the result
player_id=1
....
player_id==1? enemy_id=2 : enemy_id=1
# => enemy=2
And I found a post about to the topic which seems pretty helpful.
format
supports a percentage floating point precision type:
>>> print "{0:.0%}".format(1./3)
33%
If you don't want integer division, you can import Python3's division from __future__
:
>>> from __future__ import division
>>> 1 / 3
0.3333333333333333
# The above 33% example would could now be written without the explicit
# float conversion:
>>> print "{0:.0f}%".format(1/3 * 100)
33%
# Or even shorter using the format mini language:
>>> print "{:.0%}".format(1/3)
33%
Here you go:
^[^<>]*$
This will test for string that has no <
and no >
If you want to test for a string that may have <
and >
, but must also have something other you should use just
[^<>] (or ^.*[^<>].*$)
Where [<>]
means any of <
or >
and [^<>]
means any that is not of <
or >
.
And of course the mandatory link.
Meder Omuraliev suggested to use an event handler and set scrollTo(0,0). This is an example for Wassim-azirar. Bringing it all together, I assume this is the final solution.
We have 3 problems: the scrollbar, scrolling with mouse, and keyboard. This hides the scrollbar:
html, body{overflow:hidden;}
Unfortunally, you can still scroll with the keyboard: To prevent this, we can:
function keydownHandler(e) {
var evt = e ? e:event;
var keyCode = evt.keyCode;
if (keyCode==38 || keyCode==39 || keyCode==40 || keyCode==37){ //arrow keys
e.preventDefault()
scrollTo(0,0);
}
}
document.onkeydown=keydownHandler;
The scrolling with the mouse just naturally doesn't work after this code, so we have prevented the scrolling.
For example: https://jsfiddle.net/aL7pes70/1/
The thing you will need to do here is use a linear gradient as background and animate the background position. In code:
Use a linear gradient (50% red, 50% blue) and tell the browser that background is 2 times larger than the element's width (width:200%, height:100%), then tell it to position the background left.
background: linear-gradient(to right, red 50%, blue 50%);
background-size: 200% 100%;
background-position:left bottom;
On hover, change the background position to right bottom
and with transition:all 2s ease;
, the position will change gradually (it's nicer with linear
tough)
background-position:right bottom;
As for the -vendor-prefix'es, see the comments to your question
extra If you wish to have a "transition" in the colour, you can make it 300% width and make the transition start at 34% (a bit more than 1/3) and end at 65% (a bit less than 2/3).
background: linear-gradient(to right, red 34%, blue 65%);
background-size: 300% 100%;
div {
font: 22px Arial;
display: inline-block;
padding: 1em 2em;
text-align: center;
color: white;
background: red; /* default color */
/* "to left" / "to right" - affects initial color */
background: linear-gradient(to left, salmon 50%, lightblue 50%) right;
background-size: 200%;
transition: .5s ease-out;
}
div:hover {
background-position: left;
}
_x000D_
<div>Hover me</div>
_x000D_
For MAMP
ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock
UPDATE: Every time my computer restarts I have to enter this command, so I created a shortcut.
Do the following in terminal type:
~: vi ~/.profile
Add
alias ...='source ~/.profile'
alias sockit='sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock'
Save.
In terminal type:
~: ...
to source the .profile config.
Now in terminal you can just type
~: sockit
I can't find any shortcut to generate javadoc comments. But if you type /**
before the method declaration and press Enter, the javadoc comment block will be generated automatically.
Read this for more information.
We're getting errors about duplicate configuration directives on the one of our apps. After investigation it looks like it's because of this issue.
In brief, our root website is ASP.NET 3.5 (which is 2.0 with specific libraries added), and we have a subapplication that is ASP.NET 4.0.
web.config inheritance causes the ASP.NET 4.0 sub-application to inherit the web.config file of the parent ASP.NET 3.5 application.
However, the ASP.NET 4.0 application's global (or "root") web.config, which resides at C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config and C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config (depending on your bitness), already contains these config sections.
The ASP.NET 4.0 app then tries to merge together the root ASP.NET 4.0 web.config, and the parent web.config (the one for an ASP.NET 3.5 app), and runs into duplicates in the node.
The only solution I've been able to find is to remove the config sections from the parent web.config, and then either
I just met you,
And this is crazy,
But here's my number (delegate),
So if something happens (event),
Call me, maybe (callback)?
try
block contains set of statements where an exception can occur.
catch
block will be used to used to handle the exception that occur with in try
block. A try
block is always followed by a catch
block and we can have multiple catch blocks.
finally
block is executed after catch block. We basically use it to put some common code when there are multiple catch blocks. Even if there is an exception or not finally block gets executed.
throw
keyword will allow you to throw an exception and it is used to transfer control from try block to catch block.
throws
keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.
// Java program to demonstrate working of throws, throw, try, catch and finally.
public class MyExample {
static void myMethod() throws IllegalAccessException
{
System.out.println("Inside myMethod().");
throw new IllegalAccessException("demo");
}
// This is a caller function
public static void main(String args[])
{
try {
myMethod();
}
catch (IllegalAccessException e) {
System.out.println("exception caught in main method.");
}
finally(){
System.out.println("I am in final block.");
}
}
}
Output:
Inside myMethod().
exception caught in main method.
I am in final block.
Simply you can use the following code:
$arr=explode('sep1',str_replace(array('sep2','sep3','sep4'),'sep1',$mystring));
dblink executes a query (usually a SELECT, but it can be any SQL statement that returns rows) in a remote database.
When two text arguments are given, the first one is first looked up as a persistent connection's name; if found, the command is executed on that connection. If not found, the first argument is treated as a connection info string as for dblink_connect, and the indicated connection is made just for the duration of this command.
one of the good example:
SELECT *
FROM table1 tb1
LEFT JOIN (
SELECT *
FROM dblink('dbname=db2','SELECT id, code FROM table2')
AS tb2(id int, code text);
) AS tb2 ON tb2.column = tb1.column;
Note: I am giving this information for future reference. Refrence
For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
While this will not (note the leading space before the opening <?
tag)
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
Also, this will not work either (the echo
will break it):
<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.
add ob_start ();
at the top and at the end add ob_end_flush();
<?php
ob_start();
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
ob_end_flush();
?>
give me an error as below:
FPDF error: Some data has already been output, can't send PDF
to over come this error:
go to fpdf.php
in that,goto line number 996
function Output($name='', $dest='')
after that make changes like this:
function Output($name='', $dest='') {
ob_clean(); //Output PDF to so
Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.
<?
while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);
?>
cheers :-)
In my case i had set:
ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);
When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off
the display_errors
option, the report was generated successfully.
Anyone wanting a drop-in fully SLF4J compatible solution to this problem might want to check out Lidalia SLF4J Extensions - it's on Maven Central.
If there is someone interested in achieve the @Pedro Silva solution in JS, I just ported this same solution for it:
const getBase64Size = (base64) => {
let padding = base64.length
? getBase64Padding(base64)
: 0
return ((Math.ceil(base64.length / 4) * 3 ) - padding) / 1000
}
const getBase64Padding = (base64) => {
return endsWith(base64, '==')
? 2
: 1
}
const endsWith = (str, end) => {
let charsFromEnd = end.length
let extractedEnd = str.slice(-charsFromEnd)
return extractedEnd === end
}
Working fine after removing the Android Wear ARM EABI v7a system image and wear intel x86 Atom System image.
As suggested by A Star, I always use something along the lines of:
DATE(NOW()) - INTERVAL 1 MONTH
Similarly you can do:
NOW() + INTERVAL 5 MINUTE
"2013-01-01 00:00:00" + INTERVAL 10 DAY
and so on. Much easier than typing DATE_ADD
or DATE_SUB
all the time :)!
Is your website also on the oxfordlearnersdictionaries.com domain? or your trying to make a call to a domain and the same origin policy is blocking you?
Unless you have permission to set header via CORS on the oxfordlearnersdictionaries.com domain you may want to look for another approach.
target="_blank"
Opens a new window and show the related data.
target="_self"
Opens the window in the same frame, it means existing window itself.
target="_top"
Opens the linked document in the full body of the window.
target="_parent"
Opens data in the size of parent window.
I'm with Stroustrup on this one :-) Since NULL is not part of the language, I prefer to use 0.
Here's a jsfiddle with a function call: https://jsfiddle.net/8282emwn/
var marker = new L.Marker([46.947, 7.4448]).on('click', markerOnClick).addTo(map);
function markerOnClick(e)
{
alert("hi. you clicked the marker at " + e.latlng);
}
Stack memory is specifically the range of memory that is accessible via the Stack register of the CPU. The Stack was used as a way to implement the "Jump-Subroutine"-"Return" code pattern in assembly language, and also as a means to implement hardware-level interrupt handling. For instance, during an interrupt, the Stack was used to store various CPU registers, including Status (which indicates the results of an operation) and Program Counter (where was the CPU in the program when the interrupt occurred).
Stack memory is very much the consequence of usual CPU design. The speed of its allocation/deallocation is fast because it is strictly a last-in/first-out design. It is a simple matter of a move operation and a decrement/increment operation on the Stack register.
Heap memory was simply the memory that was left over after the program was loaded and the Stack memory was allocated. It may (or may not) include global variable space (it's a matter of convention).
Modern pre-emptive multitasking OS's with virtual memory and memory-mapped devices make the actual situation more complicated, but that's Stack vs Heap in a nutshell.
Based on different answers but mainly on this, this works for what I need:
UIImage *image1 = ...; // The image from where you want a pixel data
int pixelX = ...; // The X coordinate of the pixel you want to retrieve
int pixelY = ...; // The Y coordinate of the pixel you want to retrieve
uint32_t pixel1; // Where the pixel data is to be stored
CGContextRef context1 = CGBitmapContextCreate(&pixel1, 1, 1, 8, 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst);
CGContextDrawImage(context1, CGRectMake(-pixelX, -pixelY, CGImageGetWidth(image1.CGImage), CGImageGetHeight(image1.CGImage)), image1.CGImage);
CGContextRelease(context1);
As a result of this lines, you will have a pixel in AARRGGBB format with alpha always set to FF in the 4 byte unsigned integer pixel1
.
A good solution that can work is go to files > and check the reallocate all files
Given that 'table-layout:fixed' is the essential layout requirement, that this creates evenly spaced non-adjustable columns, but that you need to make cells of different percentage widths, perhaps set the 'colspan' of your cells to a multiple?
For example, using a total width of 100 for easy percentage calculations, and saying that you need one cell of 80% and another of 20%, consider:
<TABLE width=100% style="table-layout:fixed;white-space:nowrap;overflow:hidden;">
<tr>
<td colspan=100>
text across entire width of table
</td>
<tr>
<td colspan=80>
text in lefthand bigger cell
</td>
<td colspan=20>
text in righthand smaller cell
</td>
</TABLE>
Of course, for columns of 80% and 20%, you could just set the 100% width cell colspan to 5, the 80% to 4, and the 20% to 1.
If you use CDATA, you could embed the line breaks directly into the XML I think. Example:
<song>
<title>Song Title</title>
<lyric><![CDATA[Line 1
Line 2
Line 3]]></lyric>
</song>
You need to find what your local network's IP of that computer is. Then other people can access to your site by that IP.
You can find your local network's IP by go to Command Prompt or press Windows + R then type in ipconfig
. It will give out some information and your local IP should look like 192.168.1.x.
You should in fact do both, so that all browsers will find the icon.
Naming the file "favicon.ico" and putting it in the root of your website is the method "discouraged" by W3C:
Method 2 (Discouraged): Putting the favicon at a predefined URI
A second method for specifying a favicon relies on using a predefined URI to identify the image: "/favicon", which is relative to the server root. This method works because some browsers have been programmed to look for favicons using that URI.
W3C - How to add a favicon to your site
So, to cover all situations, I always do that in addition to the recommended method of adding a "rel" attribute and pointing it to the same .ico file.
In addition of export EDITOR="code --wait"
, note that, with VSCode v1.47 (June 2020), those diff editors will survice a VSCode reload/restart.
See issue 99290:
with commit 1428d44, diff editors now have a chance to survive reloads and this works OK unless the diff editor on a git resource is opened as the active one:
(and commit 24f1b69 fixes that)
In Standard SQL, no. A WHERE
clause implies a table expression.
From the SQL-92 spec:
7.6 "where clause"
Function
Specify a table derived by the application of a "search condition" to the result of the preceding "from clause".
In turn:
7.4 "from clause"
Function
Specify a table derived from one or more named tables.
A Standard way of doing it (i.e. should work on any SQL product):
SELECT DISTINCT 'Hello world' AS new_value
FROM AnyTableWithOneOrMoreRows
WHERE 1 = 1;
...assuming you want to change the WHERE
clause to something more meaningful, otherwise it can be omitted.
Here's my thread control function:
#!/bin/bash
# This function just checks jobs in background, don't do more things.
# if jobs number is lower than MAX, then return to get more jobs;
# if jobs number is greater or equal to MAX, then wait, until someone finished.
# Usage:
# thread_max 8
# thread_max 0 # wait, until all jobs completed
thread_max() {
local CHECK_INTERVAL="3s"
local CUR_THREADS=
local MAX=
[[ $1 ]] && MAX=$1 || return 127
# reset MAX value, 0 is easy to remember
[ $MAX -eq 0 ] && {
MAX=1
DEBUG "waiting for all tasks finish"
}
while true; do
CUR_THREADS=`jobs -p | wc -w`
# workaround about jobs bug. If don't execute it explicitily,
# CUR_THREADS will stick at 1, even no jobs running anymore.
jobs &>/dev/null
DEBUG "current thread amount: $CUR_THREADS"
if [ $CUR_THREADS -ge $MAX ]; then
sleep $CHECK_INTERVAL
else
return 0
fi
done
}
OK - I had the same problem. I didn't want to use "config.assets.compile = true" - I had to add all of my .css files to the list in config/environments/production.rb:
config.assets.precompile += %w( carts.css )
Then I had to create (and later delete) tmp/restart.txt
I consistently used the stylesheet_link_tag helper, so I found all the extra css files I needed to add with:
find . \( -type f -o -type l \) -exec grep stylesheet_link_tag {} /dev/null \;
If you're using Google Chrome you can use the Chrome Dev Editor: https://github.com/dart-lang/chromedeveditor
There are two differences:
We can use Iterator to traverse Set and List and also Map type of Objects. While a ListIterator can be used to traverse for List-type Objects, but not for Set-type of Objects.
That is, we can get a Iterator object by using Set and List, see here:
By using Iterator we can retrieve the elements from Collection Object in forward direction only.
Methods in Iterator:
hasNext()
next()
remove()
Iterator iterator = Set.iterator();
Iterator iterator = List.iterator();
But we get ListIterator object only from the List interface, see here:
where as a ListIterator allows you to traverse in either directions (Both forward and backward). So it has two more methods like hasPrevious()
and previous()
other than those of Iterator. Also, we can get indexes of the next or previous elements (using nextIndex()
and previousIndex()
respectively )
Methods in ListIterator:
ListIterator listiterator = List.listIterator();
i.e., we can't get ListIterator object from Set interface.
Reference : - What is the difference between Iterator and ListIterator ?
To remove specific key and element from hashmap use
hashmap.remove(key)
full source code is like
import java.util.HashMap;
public class RemoveMapping {
public static void main(String a[]){
HashMap hashMap = new HashMap();
hashMap.put(1, "One");
hashMap.put(2, "Two");
hashMap.put(3, "Three");
System.out.println("Original HashMap : "+hashMap);
hashMap.remove(3);
System.out.println("Changed HashMap : "+hashMap);
}
}
It fails "when trying to execute the function manually
" because you have a different 'this'. This will refer not to the thing you have in mind when invoking the method manually, but something else, probably the window object, or whatever context object you have when invoking manually.
You can also use the RestSharp library for example
var userName = "myuser";
var password = "mypassword";
var host = "170.170.170.170:333";
var client = new RestClient("https://" + host + "/method1");
client.Authenticator = new HttpBasicAuthenticator(userName, password);
var request = new RestRequest(Method.POST);
request.AddHeader("Accept", "application/json");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json","{}",ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
If you are running a standalone application then you have to use SparkContext
instead of SparkSession
val conf = new SparkConf().setAppName("Samples").setMaster("local")
val sc = new SparkContext(conf)
val textData = sc.textFile("sample.txt").cache()
The old way:
xcopy [source] [destination] /E
xcopy is deprecated. Robocopy replaces Xcopy. It comes with Windows 8, 8.1 and 10.
robocopy [source] [destination] /E
robocopy has several advantages:
More details here.
You can use the COALESCE function in MS SQL.
INSERT INTO t ( value ) VALUES( COALESCE(@value, 'something') )
Personally, I'm not crazy about this solution as it is a maintenance nightmare if you want to change the default value.
My preference would be Mitchel Sellers proposal, but that doesn't work in MS SQL. Can't speak to other SQL dbms.
You can acheive this using window.open()
method, passing _blank
as one of the parameter. You can refer the below links which has more information on this.
http://www.w3schools.com/jsref/met_win_open.asp
http://msdn.microsoft.com/en-us/library/ms536651(v=vs.85).aspx
Hope this will help you.
Allows getting any URL on your system, not just a current one.
import org.springframework.hateoas.mvc.ControllerLinkBuilder
...
ControllerLinkBuilder linkBuilder = ControllerLinkBuilder.linkTo(methodOn(YourController.class).getSomeEntityMethod(parameterId, parameterTwoId))
URI methodUri = linkBuilder.Uri()
String methodUrl = methodUri.getPath()
You can use =A4, in case A4 is having long formula
You can convert the value to a date using a formula like this, next to the cell:
=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2))
Where A1 is the field you need to convert.
Alternatively, you could use this code in VBA:
Sub ConvertYYYYMMDDToDate()
Dim c As Range
For Each c In Selection.Cells
c.Value = DateSerial(Left(c.Value, 4), Mid(c.Value, 5, 2), Right(c.Value, 2))
'Following line added only to enforce the format.
c.NumberFormat = "mm/dd/yyyy"
Next
End Sub
Just highlight any cells you want fixed and run the code.
Note as RJohnson mentioned in the comments, this code will error if one of your selected cells is empty. You can add a condition on c.value to skip the update if it is blank.
The order of execution is:
A
's constructorB
's constructorThe assignment occurs in B
's constructor after A
's constructor—_super
—has been called:
function B() {
_super.apply(this, arguments); // MyvirtualMethod called in here
this.testString = "Test String"; // testString assigned here
}
So the following happens:
var b = new B(); // undefined
b.MyvirtualMethod(); // "Test String"
You will need to change your code to deal with this. For example, by calling this.MyvirtualMethod()
in B
's constructor, by creating a factory method to create the object and then execute the function, or by passing the string into A
's constructor and working that out somehow... there's lots of possibilities.
the string in your question is not a valid json string. From json.org website:
JSON is built on two structures:
* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. * An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
Basically a json string will always start with either { or [.
Then as @Andy E and @Cryo said you can parse the string with json2.js or some other libraries.
IMHO you should avoid eval because it will any javascript program, so you might incur in security issues.
Try This:
/// <summary>
/// AlphabetizeDropDownList alphabetizes a given dropdown list by it's displayed text.
/// </summary>
/// <param name="dropDownList">The drop down list you wish to modify.</param>
/// <remarks></remarks>
private void AlphabetizeDropDownList(ref DropDownList dropDownList)
{
//Create a datatable to sort the drop down list items
DataTable machineDescriptionsTable = new DataTable();
machineDescriptionsTable.Columns.Add("DescriptionCode", typeof(string));
machineDescriptionsTable.Columns.Add("UnitIDString", typeof(string));
machineDescriptionsTable.AcceptChanges();
//Put each of the list items into the datatable
foreach (ListItem currentDropDownListItem in dropDownList.Items) {
string currentDropDownUnitIDString = currentDropDownListItem.Value;
string currentDropDownDescriptionCode = currentDropDownListItem.Text;
DataRow currentDropDownDataRow = machineDescriptionsTable.NewRow();
currentDropDownDataRow["DescriptionCode"] = currentDropDownDescriptionCode.Trim();
currentDropDownDataRow["UnitIDString"] = currentDropDownUnitIDString.Trim();
machineDescriptionsTable.Rows.Add(currentDropDownDataRow);
machineDescriptionsTable.AcceptChanges();
}
//Sort the data table by description
DataView sortedView = new DataView(machineDescriptionsTable);
sortedView.Sort = "DescriptionCode";
machineDescriptionsTable = sortedView.ToTable();
//Clear the items in the original dropdown list
dropDownList.Items.Clear();
//Create a dummy list item at the top
ListItem dummyListItem = new ListItem(" ", "-1");
dropDownList.Items.Add(dummyListItem);
//Begin transferring over the items alphabetically from the copy to the intended drop
downlist
foreach (DataRow currentDataRow in machineDescriptionsTable.Rows) {
string currentDropDownValue = currentDataRow["UnitIDString"].ToString().Trim();
string currentDropDownText = currentDataRow["DescriptionCode"].ToString().Trim();
ListItem currentDropDownListItem = new ListItem(currentDropDownText, currentDropDownValue);
//Don't deal with dummy values in the list we are transferring over
if (!string.IsNullOrEmpty(currentDropDownText.Trim())) {
dropDownList.Items.Add(currentDropDownListItem);
}
}
}
This will take a given drop down list with a Text and a Value property of the list item and put them back into the given drop down list. Best of Luck!
Not sure why the code above did not work for the library rgl
, but the following link has a great example with the same library.
Run the code in R and you will obtain a beautiful 3d plot that you can turn around in all angles.
http://statisticsr.blogspot.de/2008/10/some-r-functions.html
########################################################################
## another example of 3d plot from my personal reserach, use rgl library
########################################################################
# 3D visualization device system
library(rgl);
data(volcano)
dim(volcano)
peak.height <- volcano;
ppm.index <- (1:nrow(volcano));
sample.index <- (1:ncol(volcano));
zlim <- range(peak.height)
zlen <- zlim[2] - zlim[1] + 1
colorlut <- terrain.colors(zlen) # height color lookup table
col <- colorlut[(peak.height-zlim[1]+1)] # assign colors to heights for each point
open3d()
ppm.index1 <- ppm.index*zlim[2]/max(ppm.index);
sample.index1 <- sample.index*zlim[2]/max(sample.index)
title.name <- paste("plot3d ", "volcano", sep = "");
surface3d(ppm.index1, sample.index1, peak.height, color=col, back="lines", main = title.name);
grid3d(c("x", "y+", "z"), n =20)
sample.name <- paste("col.", 1:ncol(volcano), sep="");
sample.label <- as.integer(seq(1, length(sample.name), length = 5));
axis3d('y+',at = sample.index1[sample.label], sample.name[sample.label], cex = 0.3);
axis3d('y',at = sample.index1[sample.label], sample.name[sample.label], cex = 0.3)
axis3d('z',pos=c(0, 0, NA))
ppm.label <- as.integer(seq(1, length(ppm.index), length = 10));
axes3d('x', at=c(ppm.index1[ppm.label], 0, 0), abs(round(ppm.index[ppm.label], 2)), cex = 0.3);
title3d(main = title.name, sub = "test", xlab = "ppm", ylab = "samples", zlab = "peak")
rgl.bringtotop();
Instead of removeClass and addClass, you can also do it like this:
$('.IsBestAnswer').toggleClass('IsBestAnswer bestanswer');
bool isMultiple = a % b == 0;
This will be true if a is a multiple of b
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
echo $obj->access_token;
The trick here is that the ToolTip control is an extender control, which means that it will extend the set of properties for other controls on the form. Behind the scenes this is achieved by generating code like in Svetlozar's answer. There are other controls working in the same manner (such as the HelpProvider
).
Just define them yourself.
#ifdef _MSC_VER
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
#include <stdint.h>
#endif
Bryan Rowe and AdamCrawford thanks for your answers!
But if somebody need method for get Discription (not extension) you can use it:
string GetEnumDiscription(Enum EnumValue)
{
var type = EnumValue.GetType();
var memInfo = type.GetMember(EnumValue.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
return (attributes.Length > 0) ? ((DescriptionAttribute)attributes[0]).Description : null;
}
The Easiest way to implement scrollbar using java swing is as below :
its solved. Use nuget and search for the "ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client".
and install the package. it will resolve the issue for me.
First add the # -*- coding: utf-8 -*-
line to the beginning of the file and then use u'foo'
for all your non-ASCII unicode data:
def NewFunction():
return u'£'
or use the magic available since Python 2.6 to make it automatic:
from __future__ import unicode_literals
Make sure that the CellIdentifier == identifier of the cell in a storyboard, both names are same. Hope this works for u
It is a generic type parameter, see Generics documentation.
T
is not a reserved keyword. T
, or any given name, means a type parameter. Check the following method (just as a simple example).
T GetDefault<T>()
{
return default(T);
}
Note that the return type is T
. With this method you can get the default value of any type by calling the method as:
GetDefault<int>(); // 0
GetDefault<string>(); // null
GetDefault<DateTime>(); // 01/01/0001 00:00:00
GetDefault<TimeSpan>(); // 00:00:00
.NET uses generics in collections, ... example:
List<int> integerList = new List<int>();
This way you will have a list that only accepts integers, because the class is instancited with the type T
, in this case int
, and the method that add elements is written as:
public class List<T> : ...
{
public void Add(T item);
}
Some more information about generics.
You can limit the scope of the type T
.
The following example only allows you to invoke the method with types that are classes:
void Foo<T>(T item) where T: class
{
}
The following example only allows you to invoke the method with types that are Circle
or inherit from it.
void Foo<T>(T item) where T: Circle
{
}
And there is new()
that says you can create an instance of T
if it has a parameterless constructor. In the following example T
will be treated as Circle
, you get intellisense...
void Foo<T>(T item) where T: Circle, new()
{
T newCircle = new T();
}
As T
is a type parameter, you can get the object Type
from it. With the Type
you can use reflection...
void Foo<T>(T item) where T: class
{
Type type = typeof(T);
}
As a more complex example, check the signature of ToDictionary
or any other Linq method.
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
There isn't a T
, however there is TKey
and TSource
. It is recommended that you always name type parameters with the prefix T
as shown above.
You could name TSomethingFoo
if you want to.
If you use
std::vector<std::reference_wrapper<std::string>> names{ };
Do not forget, when you use auto in the for loop, to use also get, like this:
for (auto element in : names)
{
element.get()//do something
}
Override the controllers Json/JsonResult to return JSON.Net:
You will certainly be able to do that using WITH clause, or use analytic functions available in Oracle SQL.
With some effort you'd be able to get anything out of them in terms of cycles as in ordinary procedural languages. Both approaches are pretty powerful compared to ordinary SQL.
http://www.dba-oracle.com/t_with_clause.htm
It requires some effort though. Don't be afraid to post a concrete example.
Using simple pseudo table DUAL helps too.
// Some more complex constant variable/pointer declaration.
// Observing cases when we get error and warning would help
// understanding it better.
int main(void)
{
char ca1[10]= "aaaa"; // char array 1
char ca2[10]= "bbbb"; // char array 2
char *pca1= ca1;
char *pca2= ca2;
char const *ccs= pca1;
char * const csc= pca2;
ccs[1]='m'; // Bad - error: assignment of read-only location ‘*(ccs + 1u)’
ccs= csc; // Good
csc[1]='n'; // Good
csc= ccs; // Bad - error: assignment of read-only variable ‘csc’
char const **ccss= &ccs; // Good
char const **ccss1= &csc; // Bad - warning: initialization from incompatible pointer type
char * const *cscs= &csc; // Good
char * const *cscs1= &ccs; // Bad - warning: initialization from incompatible pointer type
char ** const cssc= &pca1; // Good
char ** const cssc1= &ccs; // Bad - warning: initialization from incompatible pointer type
char ** const cssc2= &csc; // Bad - warning: initialization discards ‘const’
// qualifier from pointer target type
*ccss[1]= 'x'; // Bad - error: assignment of read-only location ‘**(ccss + 8u)’
*ccss= ccs; // Good
*ccss= csc; // Good
ccss= ccss1; // Good
ccss= cscs; // Bad - warning: assignment from incompatible pointer type
*cscs[1]= 'y'; // Good
*cscs= ccs; // Bad - error: assignment of read-only location ‘*cscs’
*cscs= csc; // Bad - error: assignment of read-only location ‘*cscs’
cscs= cscs1; // Good
cscs= cssc; // Good
*cssc[1]= 'z'; // Good
*cssc= ccs; // Bad - warning: assignment discards ‘const’
// qualifier from pointer target type
*cssc= csc; // Good
*cssc= pca2; // Good
cssc= ccss; // Bad - error: assignment of read-only variable ‘cssc’
cssc= cscs; // Bad - error: assignment of read-only variable ‘cssc’
cssc= cssc1; // Bad - error: assignment of read-only variable ‘cssc’
}
When you run the code
listoflists.append((list, list[0]))
You are not (as I think you expect) adding a copy of list
to the end of listoflists
. What you are doing is adding a reference to list
to the end of listoflists
. Thus, every time you update list
, it updates every reference to list
, which in this case, is every item in listoflists
What you could do instead is something like this:
listoflists = []
for i in range(1, 10):
listoflists.append((range(i), 0))
I usually use selectors in my main stylesheet, then make an ie6 specific .js (jquery) file that adds a class to all of the input types. Example:
$(document).ready(function(){
$("input[type='text']").addClass('text');
)};
And then just duplicate my styles in the ie6 specific stylesheet using the classes. That way the actual markup is a little bit cleaner.
The most idiomatic way to do this is to use symbols. For example, instead of:
enum {
FOO,
BAR,
BAZ
}
myFunc(FOO);
...you can just use symbols:
# You don't actually need to declare these, of course--this is
# just to show you what symbols look like.
:foo
:bar
:baz
my_func(:foo)
This is a bit more open-ended than enums, but it fits well with the Ruby spirit.
Symbols also perform very well. Comparing two symbols for equality, for example, is much faster than comparing two strings.
loadXMLDoc JS function should return false, otherwise it will result in postback.
If you have sequences of multiple blank lines in a row, and would like only one blank line per sequence, try
grep -v "unwantedThing" foo.txt | cat -s
cat -s
suppresses repeated empty output lines.
Your output would go from
match1
match2
to
match1
match2
The three blank lines in the original output would be compressed or "squeezed" into one blank line.
You're currently writing the binary data in the string
-object to your file. This binary data will probably only consist of a pointer to the actual data, and an integer representing the length of the string.
If you want to write to a text file, the best way to do this would probably be with an ofstream
, an "out-file-stream". It behaves exactly like std::cout
, but the output is written to a file.
The following example reads one string from stdin, and then writes this string to the file output.txt
.
#include <fstream>
#include <string>
#include <iostream>
int main()
{
std::string input;
std::cin >> input;
std::ofstream out("output.txt");
out << input;
out.close();
return 0;
}
Note that out.close()
isn't strictly neccessary here: the deconstructor of ofstream
can handle this for us as soon as out
goes out of scope.
For more information, see the C++-reference: http://cplusplus.com/reference/fstream/ofstream/ofstream/
Now if you need to write to a file in binary form, you should do this using the actual data in the string. The easiest way to acquire this data would be using string::c_str()
. So you could use:
write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );
You can use this jQuery function instead of plus Bootstrap tooltip
function DDLSToolTipping(ddlsArray) {
$(ddlsArray).each(function (index, ddl) {
DDLToolTipping(ddl)
});
}
function DDLToolTipping(ddlID, maxLength, allowDots) {
if (maxLength == null) { maxLength = 12 }
if (allowDots == null) { allowDots = true }
var selectedOption = $(ddlID).find('option:selected').text();
if (selectedOption.length > maxLength) {
$(ddlID).attr('data-toggle', "tooltip")
.attr('title', selectedOption);
if (allowDots) {
$(ddlID).prev('sup').remove();
$(ddlID).before(
"<sup style='font-size: 9.5pt;position: relative;top: -1px;left: -17px;z-index: 1000;background-color: #f7f7f7;border-radius: 229px;font-weight: bold;color: #666;'>...</sup>"
)
}
}
else if ($(ddlID).attr('title') != null) {
$(ddlID).removeAttr('data-toggle')
.removeAttr('title');
}
}
Use window.open("file2.html");
Syntax
var windowObjectReference = window.open(strUrl, strWindowName[, strWindowFeatures]);
Return value and parameters
windowObjectReference
A reference to the newly created window. If the call failed, it will be null. The reference can be used to access properties and methods of the new window provided it complies with Same origin policy security requirements.
strUrl
The URL to be loaded in the newly opened window. strUrl
can be an HTML document on the web, image file or any resource supported by the browser.
strWindowName
A string name for the new window. The name can be used as the target of links and forms using the target attribute of an <a>
or <form>
element. The name should not contain any blank space. Note that strWindowName
does not specify the title of the new window.
strWindowFeatures
Optional parameter listing the features (size, position, scrollbars, etc.) of the new window. The string must not contain any blank space, each feature name and value must be separated by a comma.
For OSX users:
Run the following command to install Memcached:
brew install memcached
I think clang could be an alternative.
GCC and clang have some differences on expressions like a+++++a
, and I've got many different answers with my peer who use clang on Mac while I use gcc.
GCC has become the standard, and clang could be an alternative. Because GCC is very stable and clang is still under developing.
First find the class name for particular select.
$('#id').val('');
$('#selectoptionclassname').selectpicker('refresh');
I like @Alex Howansky have used 'cmp --silent' for this. But I need both positive and negative response so I use:
cmp --silent file1 file2 && echo '### SUCCESS: Files Are Identical! ###' || echo '### WARNING: Files Are Different! ###'
I can then run this in the terminal or with a ssh to check files against a constant file.
The basic one, ask tasklist to filter its output and only show the indicated process id information
tasklist /fi "pid eq 4444"
To only get the process name, the line must be splitted
for /f "delims=," %%a in ('
tasklist /fi "pid eq 4444" /nh /fo:csv
') do echo %%~a
In this case, the list of processes is retrieved without headers (/nh
) in csv format (/fo:csv
). The commas are used as token delimiters and the first token in the line is the image name
note: In some windows versions (one of them, my case, is the spanish windows xp version), the pid filter in the tasklist does not work. In this case, the filter over the list of processes must be done out of the command
for /f "delims=," %%a in ('
tasklist /fo:csv /nh ^| findstr /b /r /c:"[^,]*,\"4444\","
') do echo %%~a
This will generate the task list and filter it searching for the process id in the second column of the csv output.
edited: alternatively, you can suppose what has been made by the team that translated the OS to spanish. I don't know what can happen in other locales.
tasklist /fi "idp eq 4444"
With these two steps we can check if it LL(1) or not. Both of them have to be satisfied.
1.If we have the production:A->a1|a2|a3|a4|.....|an. Then,First(a(i)) intersection First(a(j)) must be phi(empty set)[a(i)-a subscript i.]
2.For every non terminal 'A',if First(A) contains epsilon Then First(A) intersection Follow(A) must be phi(empty set).
You can use SELECT
as lambacck said
or add parentheses:
SET @times = (SELECT COUNT(DidWin)as "I Win"
FROM thetable
WHERE DidWin = 1 AND Playername='Me');
This is due to the fact that your element is dynamically created. You should use event delegation to handle the event.
document.addEventListener('click',function(e){
if(e.target && e.target.id== 'brnPrepend'){
//do something
}
});
jquery makes it easier:
$(document).on('click','#btnPrepend',function(){//do something})
Here is an article about event delegation event delegation article
I had the same problem.
I wanted to view my diagram, which I created the same day at work, at home. But I couldn't because of this message.
I found out that the owner of the database was the user of my computer -as expected. but since the computer is in the company's domain, and I am not connected to the company's network, the database couldn't resolve the owner.
So what I did is change the owner to a local user and it worked!!
Hope this helps someone.
You change the user by right-click on the database, properties, files, owner
Sorry, but at this time is not possible resize arrays, and may be never will be.
So my recommendation, is to think more to find a solution that allow you get from the beginning of the process, the size of the arrays that you will requiere. This often will implicate that your code need a little more time (lines) to run, but you will save a lot of memory resources.
As noted by other answers, the general solution is to use an index expression in an assignment of the special form:
v, ok = a[x]
v, ok := a[x]
var v, ok = a[x]
var v, ok T = a[x]
This is nice and clean. It has some restrictions though: it must be an assignment of special form. Right-hand side expression must be the map index expression only, and the left-hand expression list must contain exactly 2 operands, first to which the value type is assignable, and a second to which a bool
value is assignable. The first value of the result of this special form will be the value associated with the key, and the second value will tell if there is actually an entry in the map with the given key (if the key exists in the map). The left-hand side expression list may also contain the blank identifier if one of the results is not needed.
It's important to know that if the indexed map value is nil
or does not contain the key, the index expression evaluates to the zero value of the value type of the map. So for example:
m := map[int]string{}
s := m[1] // s will be the empty string ""
var m2 map[int]float64 // m2 is nil!
f := m2[2] // f will be 0.0
fmt.Printf("%q %f", s, f) // Prints: "" 0.000000
Try it on the Go Playground.
So if we know that we don't use the zero value in our map, we can take advantage of this.
For example if the value type is string
, and we know we never store entries in the map where the value is the empty string (zero value for the string
type), we can also test if the key is in the map by comparing the non-special form of the (result of the) index expression to the zero value:
m := map[int]string{
0: "zero",
1: "one",
}
fmt.Printf("Key 0 exists: %t\nKey 1 exists: %t\nKey 2 exists: %t",
m[0] != "", m[1] != "", m[2] != "")
Output (try it on the Go Playground):
Key 0 exists: true
Key 1 exists: true
Key 2 exists: false
In practice there are many cases where we don't store the zero-value value in the map, so this can be used quite often. For example interfaces and function types have a zero value nil
, which we often don't store in maps. So testing if a key is in the map can be achieved by comparing it to nil
.
Using this "technique" has another advantage too: you can check existence of multiple keys in a compact way (you can't do that with the special "comma ok" form). More about this: Check if key exists in multiple maps in one condition
Getting the zero value of the value type when indexing with a non-existing key also allows us to use maps with bool
values conveniently as sets. For example:
set := map[string]bool{
"one": true,
"two": true,
}
fmt.Println("Contains 'one':", set["one"])
if set["two"] {
fmt.Println("'two' is in the set")
}
if !set["three"] {
fmt.Println("'three' is not in the set")
}
It outputs (try it on the Go Playground):
Contains 'one': true
'two' is in the set
'three' is not in the set
See related: How can I create an array that contains unique strings?
while(!feof(fp))
{
ch = fgetc(fp);
if(ch == '\n')
{
lines++;
}
}
But please note: Why is “while ( !feof (file) )” always wrong?.
I did some speed tests on Firefox.
-100/3 // -33.33..., 0.3663 millisec
Math.floor(-100/3) // -34, 0.5016 millisec
~~(-100/3) // -33, 0.3619 millisec
(-100/3>>0) // -33, 0.3632 millisec
(-100/3|0) // -33, 0.3856 millisec
(-100-(-100%3))/3 // -33, 0.3591 millisec
/* a=-100, b=3 */
a/b // -33.33..., 0.4863 millisec
Math.floor(a/b) // -34, 0.6019 millisec
~~(a/b) // -33, 0.5148 millisec
(a/b>>0) // -33, 0.5048 millisec
(a/b|0) // -33, 0.5078 millisec
(a-(a%b))/b // -33, 0.6649 millisec
The above is based on 10 million trials for each.
Conclusion: Use (a/b>>0)
(or (~~(a/b))
or (a/b|0)
) to achieve about 20% gain in efficiency. Also keep in mind that they are all inconsistent with Math.floor
, when a/b<0 && a%b!=0
.
Use the DataFrame returned by:
yourDF.orderBy(account)
There is no explicit way to use partitionBy
on a DataFrame, only on a PairRDD, but when you sort a DataFrame, it will use that in it's LogicalPlan and that will help when you need to make calculations on each Account.
I just stumbled upon the same exact issue, with a dataframe that I want to partition by account.
I assume that when you say "want to have the data partitioned so that all of the transactions for an account are in the same Spark partition", you want it for scale and performance, but your code doesn't depend on it (like using mapPartitions()
etc), right?
You need to use padding on the list item layout so space is added on the edges of the item (just increasing the font size won't do that).
<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="@+id/text1"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp" />
You can also lean on the IDE a little. If you run the program using the "Start without debugging" command (Ctrl+F5 for me), the console window will stay open even after the program ends with a "Press any key to continue . . ." message.
Of course, if want to use the "Hit any key" to keep your program running (i.e. keep a thread alive), this won't work. And it does not work when you run "with debugging". But then you can use break points to hold the window open.
Well I know this maybe rather dumb than and simple, but I think it should work:
string n;
cin>> n;
char b[200];
for (int i = 0; i < sizeof(n); i++)
{
b[i] = n[i];
cout<< b[i]<< " ";
}
Here my solution without going backward and without a temporary list
while (listBox1.Items.Count > 0)
{
string s = listBox1.Items[0] as string;
// do something with s
listBox1.Items.RemoveAt(0);
}
$now = date("Y-m-d H:i:s");
date("Y-m-d H:i:s", strtotime("+1 hours $now"));
Creating Custom ProgressBar like hotstar.
activity_main.xml
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="@+id/player_progressbar"
android:indeterminateDrawable="@drawable/custom_progress_bar"
/>
custom_progress_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="2000"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="1080" >
<shape
android:innerRadius="35dp"
android:shape="ring"
android:thickness="3dp"
android:useLevel="false" >
<size
android:height="80dp"
android:width="80dp" />
<gradient
android:centerColor="#80b7b4b2"
android:centerY="0.5"
android:endColor="#f4eef0"
android:startColor="#00938c87"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
It's running every minute of the hour 22 I guess. Try the following to run it every first minute of the hour 22:
0 22 * * * ....
The best and simplest way to solve this problem is by using an arrow function () => {}
:
addToBasket() {
var item = this.photo;
this.$http.post('/api/buy/addToBasket', item);
this.basketAddSuccess = true;
// now 'this' is referencing the Vue object and not the 'setTimeout' scope
setTimeout(() => this.basketAddSuccess = false, 2000);
}
This works because the this
of arrow functions is bound to the this
of its enclosing scope- in Vue, that's the parent/ enclosing component. Inside a traditional function called by setTimeout
, however, this
refers to the window
object (which is why you ran into errors when you tried to access this.basketAddSuccess
in that context).
Another way of doing this would be passing this
as an arg to your function through setTimeout
's prototype using its setTimeout(callback, delay, arg1, arg2, ...)
form:
addToBasket() {
item = this.photo;
this.$http.post('/api/buy/addToBasket', item);
this.basketAddSuccess = true;
//Add scope argument to func, pass this after delay in setTimeout
setTimeout(function(scope) {
scope.basketAddSuccess = false;
}, 2000, this);
}
(It's worth noting that the arg passing syntax is incompatible with IE 9 and below, however.)
Another possible, but less eloquent and less encouraged, way is to bind this
to a var outside of setTimeout
:
addToBasket() {
item = this.photo;
this.$http.post('/api/buy/addToBasket', item);
this.basketAddSuccess = true;
//Declare self, which is accessible inside setTimeout func
var self = this;
setTimeout(function() {
self.basketAddSuccess = false;
}, 2000);
}
Using an arrow function would eliminate the need for this extra variable entirely however, and really should be used unless something else is preventing its use.
1) It is the only difference in C++.
2) POD: plain old data Other classes -> not POD
Have you thought about this:
try {
ko.applyBindings(PersonListViewModel);
}
catch (err) {
console.log(err.message);
}
I came up with this because in Knockout, i found this code
var alreadyBound = ko.utils.domData.get(node, boundElementDomDataKey);
if (!sourceBindings) {
if (alreadyBound) {
throw Error("You cannot apply bindings multiple times to the same element.");
}
ko.utils.domData.set(node, boundElementDomDataKey, true);
}
So to me its not really an issue that its already bound, its that the error was not caught and dealt with...
My Swift 4 version of shouldChangeCharactersIn
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
guard let preText = textField.text as NSString?,
preText.replacingCharacters(in: range, with: string).count <= MAX_TEXT_LENGTH else {
return false
}
return true
}
Here you can find a tool that can validate a JSON file, or you could just deserialize your JSON file with any JSON library and if the operation is successful then it should be valid (google-json for example that will throw an exception if the input it is parsing is not valid JSON).
Don't agree with post above. I have a Hero with only English available and I want Spanish.
I installed MoreLocale 2, and it has lots of different languages (Dutch among them). I choose Spanish, Sense UI restarted and EVERYTHING in my phone changed to Spanish: menus, settings, etc. The keyboard predictive text defaulted to Spanish and started suggesting words in Spanish. This means, somewhere within the OS there is a Spanish dictionary hidden and MoreLocale made it available.
The problem is that English is still the only option available in keyboard input language so I can switch to English but can't switch back to Spanish unless I restart Sense UI, which takes a couple of minutes so not a very practical solution.
Still looking for an easier way to do it so please help.
JS:
function fun(obj) {
var uid= $(obj).data('uid');
var name= $(obj).data('name');
var value= $(obj).data('value');
}
enum Enum{ Banana, Orange, Apple } ;
static const char * EnumStrings[] = { "bananas & monkeys", "Round and orange", "APPLE" };
const char * getTextForEnum( int enumVal )
{
return EnumStrings[enumVal];
}
#alertlist li:hover:after,#alertlist li.selected:after
{
position:absolute;
top: 0;
right:-10px;
bottom:0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid #303030;
content: "";
}?
Quick:
var siblings = n => [...n.parentElement.children].filter(c=>c!=n)
https://codepen.io/anon/pen/LLoyrP?editors=1011
Get the parent's children as an array, filter out this element.
Edit:
And to filter out text nodes (Thanks pmrotule):
var siblings = n => [...n.parentElement.children].filter(c=>c.nodeType == 1 && c!=n)
The following is my configuration:
cmake_minimum_required(VERSION 2.8)
set(Boost_INCLUDE_DIR /usr/local/src/boost_1_46_1)
set(Boost_LIBRARY_DIR /usr/local/src/boost_1_46_1/stage/lib)
find_package(Boost COMPONENTS system filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARY_DIR})
add_executable(main main.cpp)
target_link_libraries( main ${Boost_LIBRARIES} )
Just use:
mail
d 1-15
quit
Which will delete all messages between number 1 and 15. to delete all, use the d *
.
I just used this myself on ubuntu 12.04.4, and it worked like a charm.
For example:
eric@dev ~ $ mail
Heirloom Mail version 12.4 7/29/08. Type ? for help.
"/var/spool/mail/eric": 2 messages 2 new
>N 1 Cron Daemon Tue Jul 29 17:43 23/1016 "Cron <eric@ip-10-0-1-51> /usr/bin/php /var/www/sandbox/eric/c"
N 2 Cron Daemon Tue Jul 29 17:44 23/1016 "Cron <eric@ip-10-0-1-51> /usr/bin/php /var/www/sandbox/eric/c"
& d *
& quit
Then check your mail again:
eric@dev ~ $ mail
No mail for eric
eric@dev ~ $
What is tripping you up is you are using x
or exit
to quit which rolls back the changes during that session.
If your blog outputs an RSS feed you can use Facebook's "RSS Graffiti" application to post that feed to your wall in Facebook. There are other RSS Facebook apps as well; just search "Facebook for RSS apps"...
It's also much more better to not modify the app/config/database.php
file itself... otherwise modify .env
file and put your DB info there. (.env
file is available in Laravel 5, not sure if it was there in previous versions...)
NOTE: Of course you should have already set mysql
as your default database connection in the app/config/database.php
file.
Well, I'm not sure that merge would be the way to go. Personally I would build a new data frame by creating an index of the dates and then constructing the columns using list comprehensions. Possibly not the most pythonic way, but it seems to work for me!
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.random.randn(5,3), index=pd.date_range('01/02/2014',periods=5,freq='D'), columns=['a','b','c'] )
df2 = pd.DataFrame(np.random.randn(8,3), index=pd.date_range('01/01/2014',periods=8,freq='D'), columns=['a','b','c'] )
# Create an index list from the set of dates in both data frames
Index = list(set(list(df1.index) + list(df2.index)))
Index.sort()
df3 = pd.DataFrame({'df1': [df1.loc[Date, 'c'] if Date in df1.index else np.nan for Date in Index],\
'df2': [df2.loc[Date, 'c'] if Date in df2.index else np.nan for Date in Index],},\
index = Index)
df3
Works GReat.
Category Question Apple Banana Cherry<input type="text" name="cat_q" id="cat_q">
$(document).ready(function(){
$("#btn_cat div a").click(function(){
alert($(this).text());
});
});
I assume with the second line you actually mean:
Thing *thing = new Thing("uiae");
which would be the standard way of creating new dynamic objects (necessary for dynamic binding and polymorphism) and storing their address to a pointer. Your code does what JaredPar described, namely creating two objects (one passed a const char*
, the other passed a const Thing&
), and then calling the destructor (~Thing()
) on the first object (the const char*
one).
By contrast, this:
Thing thing("uiae");
creates a static object which is destroyed automatically upon exiting the current scope.
val source_html = Source.fromResource("file.html").mkString
Build an expression that matches, and use !match()... (logical negation) That's probably how grep does anyway...
I really find very difficult from the above answers. From debugging perspective i almost spent 8 hours to know the silly mistake.
I have testing spring+hibernate+dozer+Mysql project. To be clear.
I have User entity, Book Entity. You do the calculations of mapping.
Were the Multiple books tied to One user. But in UserServiceImpl i was trying to find it by getOne(userId);
public UserDTO getById(int userId) throws Exception {
final User user = userDao.getOne(userId);
if (user == null) {
throw new ServiceException("User not found", HttpStatus.NOT_FOUND);
}
userDto = mapEntityToDto.transformBO(user, UserDTO.class);
return userDto;
}
The Rest result is
{
"collection": {
"version": "1.0",
"data": {
"id": 1,
"name": "TEST_ME",
"bookList": null
},
"error": null,
"statusCode": 200
},
"booleanStatus": null
}
The above code did not fetch the books which is read by the user let say.
The bookList was always null because of getOne(ID). After changing to findOne(ID). The result is
{
"collection": {
"version": "1.0",
"data": {
"id": 0,
"name": "Annama",
"bookList": [
{
"id": 2,
"book_no": "The karma of searching",
}
]
},
"error": null,
"statusCode": 200
},
"booleanStatus": null
}
add in your activity in manifasts this property
android:windowSoftInputMode="stateHidden"
This worked for me in Angular 2:
var img = new Image()
img.src = 'assets/sample.png'
pdf.addImage(img, 'png', 10, 78, 12, 15)
jsPDF version 1.5.3
assets directory is in src directory of the Angular project root
With your ANDs you shouldn't have a FALSE value -2, until right at the end, e.g. with just 2 ANDs
=IF(AND(E2="In Play",F2="Closed"),3,IF(AND(E2="In Play",F2=" Suspended"),3,-2))
although it might be better with a combination of nested IFs and ANDs - try like this for the full formula:[Edited - thanks David]
=IF(E2="In Play",IF(F2="Closed",3,IF(F2="Suspended",2,IF(F2="Null",1))),IF(AND(E2="Pre-play",F2="Null"),-1,IF(AND(E2="Completed",F2="Closed"),2,IF(AND(E2="Pre-play",F2="Null"),3,-2))))
To avoid a long formula like the above you could create a table with all E2 possibilities in a column like K2:K5 and all F2 possibilities in a row like L1:N1 then fill in the required results in L2:N5 and use this formula
=INDEX($L$2:$N$5,MATCH(E2,$K$2:$K$5,0),MATCH(F2,$L$1:$N$1,0))
Since JavaScript Exceptions are difficult to sub-class, I don't sub-class. I just create a new Exception class and use an Error inside of it. I change the Error.name property so that it looks like my custom exception on the console:
var InvalidInputError = function(message) {
var error = new Error(message);
error.name = 'InvalidInputError';
return error;
};
The above new exception can be thrown just like a regular Error and it will work as expected, for example:
throw new InvalidInputError("Input must be a string");
// Output: Uncaught InvalidInputError: Input must be a string
Caveat: the stack trace is not perfect, as it will bring you to where the new Error is created and not where you throw. This is not a big deal on Chrome because it provides you with a full stack trace directly in the console. But it's more problematic on Firefox, for example.
To check for null and empty:
coalesce(string, '') = ''
To check for null, empty and spaces (trim the string)
coalesce(TRIM(string), '') = ''
WMI is the way to do this.
Get-WmiObject -Query "Select StartMode From Win32_Service Where Name='winmgmt'"
Or
Get-WmiObject -Class Win32_Service -Property StartMode -Filter "Name='Winmgmt'"
Using merge
is different from lookup in Excel as it has potential to duplicate (multiply) your data if primary key constraint is not enforced in lookup table or reduce the number of records if you are not using all.x = T
.
To make sure you don't get into trouble with that and lookup safely, I suggest two strategies.
First one is to make a check on a number of duplicated rows in lookup key:
safeLookup <- function(data, lookup, by, select = setdiff(colnames(lookup), by)) {
# Merges data to lookup making sure that the number of rows does not change.
stopifnot(sum(duplicated(lookup[, by])) == 0)
res <- merge(data, lookup[, c(by, select)], by = by, all.x = T)
return (res)
}
This will force you to de-dupe lookup dataset before using it:
baseSafe <- safeLookup(largetable, house.ids, by = "HouseType")
# Error: sum(duplicated(lookup[, by])) == 0 is not TRUE
baseSafe<- safeLookup(largetable, unique(house.ids), by = "HouseType")
head(baseSafe)
# HouseType HouseTypeNo
# 1 Apartment 4
# 2 Apartment 4
# ...
Second option is to reproduce Excel behaviour by taking the first matching value from the lookup dataset:
firstLookup <- function(data, lookup, by, select = setdiff(colnames(lookup), by)) {
# Merges data to lookup using first row per unique combination in by.
unique.lookup <- lookup[!duplicated(lookup[, by]), ]
res <- merge(data, unique.lookup[, c(by, select)], by = by, all.x = T)
return (res)
}
baseFirst <- firstLookup(largetable, house.ids, by = "HouseType")
These functions are slightly different from lookup
as they add multiple columns.
http://docs.jquery.com/UI/API/1.8/Dialog
Example for fixed dialog on the left top corner:
$("#dialogId").dialog({
autoOpen: false,
modal: false,
draggable: false,
height: "auto",
width: "auto",
resizable: false,
position: [0,28],
create: function (event) { $(event.target).parent().css('position', 'fixed');},
open: function() {
//$('#object').load...
}
});
$("#dialogOpener").click(function() {
$("#dialogId").dialog("open");
});
If you're using CloudFlare, you can just create a Page Rule to always use HTTPS: This will redirect every http:// request to https://
In addition to that, you would also have to add something like this to your \app\Providers\AppServiceProvider.php boot() function:
if (env('APP_ENV') === 'production' || env('APP_ENV') === 'dev') {
\URL::forceScheme('https');
}
This would ensure that every link / path in your app is using https:// instead of http://.
Use this :
#Inputs
L1 = [1, 2]
L2 = [3,4,5]
#Code
L1+L2
#Output
[1, 2, 3, 4, 5]
By using the (+) operator you can skip the multiple append & extend operators in just one line of code and this is valid for more then two of lists by L1+L2+L3+L4.......etc.
Happy Learning...:)
on Mac, how I usually solve it
Hope this helps OP or someone else reading
Found the solution myself in the end. The problem was not with the LinearLayout
, but with the ScrollView
(seems weird, considering the fact that the ScrollView
was expanding, while the LinearLayout
wasn't).
The solution was to use android:fillViewport="true"
on the ScrollView
.
If you are using TortoiseHg you have to perform these three steps shown in the attached screen shot, this would add your credentials for the specific repository you are working with.
To add global settings you can access the file C:\users\user.name\mercurial.ini and add the section
[auth]
bb.prefix=https://bitbucket.org/zambezia/packagemanager
bb.username = $username
bb.password = $password
Hope this helps.
FileReader
uses Java's platform default encoding, which depends on the system settings of the computer it's running on and is generally the most popular encoding among users in that locale.
If this "best guess" is not correct then you have to specify the encoding explicitly. Unfortunately, FileReader
does not allow this (major oversight in the API). Instead, you have to use new InputStreamReader(new FileInputStream(filePath), encoding)
and ideally get the encoding from metadata about the file.
You can create a SqlCommand with CommandText
equal to
INSERT INTO aspnet_GameProfiles(UserId, GameId) OUTPUT INSERTED.ID VALUES(@UserId, @GameId)
and execute int id = (int)command.ExecuteScalar
.
This MSDN article will give you some additional techniques.
It might be the JavaScript check for some valid condition.
Two things you can perform a/c to your requirements:
String barcode="0000000047166";
WebElement strLocator = driver.findElement(By.xpath("//*[@id='div-barcode']"));
strLocator.sendKeys(barcode);
You can use the createQuery
method (direct in the controller) :
$query = $em->createQuery("SELECT o FROM AcmeCodeBundle:Orders o WHERE o.OrderMail = :ordermail and o.Product like :searchterm")
->setParameter('searchterm', '%'.$searchterm.'%')
->setParameter('ordermail', '[email protected]');
You need to change AcmeCodeBundle to match your bundle name
Or even better - create a repository class for the entity and create a method in there - this will make it reusable
And very nice and clean solution in koltin from com.nhaarman.mockito_kotlin
verify(mock).execute(argThat {
this.param = expected
})
supposing you have a function:
var fetchPage(page, callback) {
....
request(uri, function (error, response, body) {
....
if (something_good) {
callback(true, page+1);
} else {
callback(false);
}
.....
});
};
you can make use of callbacks like this:
fetchPage(1, x = function(next, page) {
if (next) {
console.log("^^^ CALLBACK --> fetchPage: " + page);
fetchPage(page, x);
}
});
This is not just a Chrome/Safari issue, I experienced a quite similar behavior with Firefox 18.0.1. The funny part is that this does not happen on MSIE! The problem here is the first mouseup event that forces to unselect the input content, so just ignore the first occurence.
$(':text').focus(function(){
$(this).one('mouseup', function(event){
event.preventDefault();
}).select();
});
The timeOut approach causes a strange behavior, and blocking every mouseup event you can not remove the selection clicking again on the input element.
This means the version of android of your avd is older than the version being used to compile the code
Other answers have covered pretty much everything about how we can pass model to our layout page. But I have found a way using which you can pass variables to your layout page dynamically without using any model or partial view in your layout. Let us say you have this model -
public class SubLocationsViewModel
{
public string city { get; set; }
public string state { get; set; }
}
And you want to get city and state dynamically. For e.g
in your index.cshtml you can put these two variables in ViewBag
@model MyProject.Models.ViewModel.SubLocationsViewModel
@{
ViewBag.City = Model.city;
ViewBag.State = Model.state;
}
And then in your layout.cshtml you can access those viewbag variables
<div class="text-wrap">
<div class="heading">@ViewBag.City @ViewBag.State</div>
</div>
This works reliably for me. Cell borders and height added for effect and clarity:
<table>_x000D_
<tr>_x000D_
<td style="text-align:right; border: thin solid; height:50px">Some label:</td>_x000D_
<td style="border: thin solid;">_x000D_
<input type="checkbox" checked="checked" id="chk1" style="cursor:pointer; "><label for="chk1" style="margin-top:auto; margin-left:5px; margin-bottom:auto; cursor:pointer;">Check Me</label>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
I saw a lot of comments about handling copy/pasting.
To piggy back off of @omeralper answer, you can add a paste event handler to the onlyNumber directive to handle copy/pasting:
@HostListener('paste', ['$event']) onPaste(event) {
// Don't allow pasted text that contains non-numerics
var pastedText = (event.originalEvent || event).clipboardData.getData('text/plain');
if (pastedText) {
var regEx = new RegExp('^[0-9]*$');
if (!regEx.test(pastedText)) {
event.preventDefault();
}
}
This will only allow content to be copy and pasted into the textbox ONLY if it is a number. That's the simplest solution. Changing the content of the clipboard to remove non-numerics is a lot more complicated and might not be worth it.
To get pasted text from IE you can use the following:
window.clipboardData.getData('Text');
I got a way which finally resolve this 1. check your calsspath in the top build.gradle,e.g mine is classpath 'com.android.tools.build:gradle:2.1.0-alpha3' then go to https://jcenter.bintray.com/com/android/tools/build/gradle/ find a release which is newer than yours,here I choose 2.1.0-beta3 change classpath to below, then launch the build. classpath 'com.android.tools.build:gradle:2.1.0-beta3'
In a few words:
Use git reflog
to list all changes made in your git history. Copy an action id and type git reset ACTION_ID
INSERT
syntax cannot have WHERE
but you can use UPDATE
.
The syntax is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Hi heres a javascript version which changes the background image src according to screen resolution. You have to have the different images saved in the right size.
<html>
<head>
<title>Javascript Change Div Background Image</title>
<style type="text/css">
body {
margin:0;
width:100%;
height:100%;
}
#div1 {
background-image:url('sky.jpg');
width:100%
height:100%
}
p {
font-family:Verdana;
font-weight:bold;
font-size:11px;
}
</style>
<script language="javascript" type="text/javascript">
function changeDivImage()
{
//change the image path to a string
var imgPath = new String();
imgPath = document.getElementById("div1").style.backgroundImage;
//get screen res of customer
var custHeight=screen.height;
var custWidth=screen.width;
//if their screen width is less than or equal to 640 then use the 640 pic url
if (custWidth <= 640)
{
document.getElementById("div1").style.backgroundImage = "url(640x480.jpg)";
}
else if (custWidth <= 800)
{
document.getElementById("div1").style.backgroundImage = "url(800x600.jpg)";
}
else if (custWidth <= 1024)
{
document.getElementById("div1").style.backgroundImage = "url(1024x768.jpg)";
}
else if (custWidth <= 1280)
{
document.getElementById("div1").style.backgroundImage = "url(1280x960.jpg)";
}
else if (custWidth <= 1600)
{
document.getElementById("div1").style.backgroundImage = "url(1600x1200.jpg)";
}
else {
document.getElementById("div1").style.backgroundImage = "url(graffiti.jpg)";
}
/*if(imgPath == "url(sky.jpg)" || imgPath == "")
{
document.getElementById("div1").style.backgroundImage = "url(graffiti.jpg)";
}
else
{
document.getElementById("div1").style.backgroundImage = "url(sky.jpg)";
}*/
}
</script>
</head>
<body onload="changeDivImage()">
<div id="div1">
<p>This Javascript Example will change the background image of<br />HTML Div Tag onload using javascript screen resolution.</p>
<p>paragraph</p>
</div>
<br/>
</body>
</html>