Lots of reads in every query, fewer regular writes
Both databases perform well on reads where the hot data set fits in memory. Both also emphasize join-less data models (and encourage denormalization instead), and both provide indexes on documents or rows, although MongoDB's indexes are currently more flexible.
Cassandra's storage engine provides constant-time writes no matter how big your data set grows. Writes are more problematic in MongoDB, partly because of the b-tree based storage engine, but more because of the multi-granularity locking it does.
For analytics, MongoDB provides a custom map/reduce implementation; Cassandra provides native Hadoop support, including for Hive (a SQL data warehouse built on Hadoop map/reduce) and Pig (a Hadoop-specific analysis language that many think is a better fit for map/reduce workloads than SQL). Cassandra also supports use of Spark.
Not worried about "massive" scalability
If you're looking at a single server, MongoDB is probably a better fit. For those more concerned about scaling, Cassandra's no-single-point-of-failure architecture will be easier to set up and more reliable. (MongoDB's global write lock tends to become more painful, too.) Cassandra also gives a lot more control over how your replication works, including support for multiple data centers.
More concerned about simple setup, maintenance and code
Both are trivial to set up, with reasonable out-of-the-box defaults for a single server. Cassandra is simpler to set up in a multi-server configuration since there are no special-role nodes to worry about.
If you're presently using JSON blobs, MongoDB is an insanely good match for your use case, given that it uses BSON to store the data. You'll be able to have richer and more queryable data than you would in your present database. This would be the most significant win for Mongo.
Try to change the rpc_address
to point to the node's IP instead of 0.0.0.0 and specify the IP while connecting to the cqlsh, as if the IP is 10.0.1.34 and the rpc_port
left to the default value 9160 then the following should work:
cqlsh 10.0.1.34 9160
Or:
cqlsh 10.0.1.34
Also make sure that start_rpc is set to true in /etc/cassandra/cassandra.yaml configuration file.
you can go:
var cp = require('child_process');
and then:
cp.exec('./myScript.sh', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a command in your $SHELL.
Or go
cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a file WITHOUT a shell.
Or go
cp.execFile();
which is the same as cp.exec() but doesn't look in the $PATH.
You can also go
cp.fork('myJS.js', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a javascript file with node.js, but in a child process (for big programs).
You might also have to access stdin and stdout with event listeners. e.g.:
var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
// handle stdout as `data`
});
Adding a summary answer as the accepted one is quite long. The terms "row" and "column" are used in the context of CQL, not how Cassandra is actually implemented.
Examples:
PRIMARY KEY (a)
: The partition key is a
.PRIMARY KEY (a, b)
: The partition key is a
, the clustering key is b
.PRIMARY KEY ((a, b))
: The composite partition key is (a, b)
.PRIMARY KEY (a, b, c)
: The partition key is a
, the composite clustering key is (b, c)
.PRIMARY KEY ((a, b), c)
: The composite partition key is (a, b)
, the clustering key is c
.PRIMARY KEY ((a, b), c, d)
: The composite partition key is (a, b)
, the composite clustering key is (c, d)
.Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');
The second one is normally used for case-sensitive column names.
Ports 57311 and 57312 are randomly assigned ports used for RMI communication. These ports change each time Cassandra starts up, but need to be open in the firewall, along with 8080/7199 (depending on version), to allow for remote JMX access. Something that doesn't appear to be particularly well documented, but has tripped me up in the past.
Once logged in to cqlsh or cassandra-cli. run below commands
desc keyspaces;
or
describe keyspaces;
or
select * from system_schema.keyspaces;
show keyspaces;
Left Click on chart. «PivotTable Field List» will appear on right. On the right down quarter of PivotTable Field List (S Values), you see the names of the legends. Left Click on the legend name. Left Click on the «Value field settings». At the top there is «Source Name». You can’t change it. Below there is «Custom Name». Change the Custom Name as you wish. Now the legend name on the chart has the new name you gave.
When you have related tables you often have one-to-many or many-to-many relationships. So when you join to TableB each record in TableA many have multiple records in TableB. This is normal and expected.
Now at times you only need certain columns and those are all the same for all the records, then you would need to do some sort of group by or distinct to remove the duplicates. Let's look at an example:
TableA
Id Field1
1 test
2 another test
TableB
ID Field2 field3
1 Test1 something
1 test1 More something
2 Test2 Anything
So when you join them and select all the files you get:
select *
from tableA a
join tableb b on a.id = b.id
a.Id a.Field1 b.id b.field2 b.field3
1 test 1 Test1 something
1 test 1 Test1 More something
2 another test 2 2 Test2 Anything
These are not duplicates because the values of Field3 are different even though there are repeated values in the earlier fields. Now when you only select certain columns the same number of records are being joined together but since the columns with the different information is not being displayed they look like duplicates.
select a.Id, a.Field1, b.field2
from tableA a
join tableb b on a.id = b.id
a.Id a.Field1 b.field2
1 test Test1
1 test Test1
2 another test Test2
This appears to be duplicates but it is not because of the multiple records in TableB.
You normally fix this by using aggregates and group by, by using distinct or by filtering in the where clause to remove duplicates. How you solve this depends on exactly what your business rule is and how your database is designed and what kind of data is in there.
This way might makes more sense if you don't want to use str methods
int first = 1;
for (int i = 10; i < number; i *= 10) {
first = number / i;
}
Here is something I used to drop files and/or folders full of files. In my case I was filtering for *.dwg
files only and chose to include all subfolders.
fileList
is an IEnumerable
or similar In my case was bound to a WPF control...
var fileList = (IList)FileList.ItemsSource;
See https://stackoverflow.com/a/19954958/492 for details of that trick.
The drop Handler ...
private void FileList_OnDrop(object sender, DragEventArgs e)
{
var dropped = ((string[])e.Data.GetData(DataFormats.FileDrop));
var files = dropped.ToList();
if (!files.Any())
return;
foreach (string drop in dropped)
if (Directory.Exists(drop))
files.AddRange(Directory.GetFiles(drop, "*.dwg", SearchOption.AllDirectories));
foreach (string file in files)
{
if (!fileList.Contains(file) && file.ToLower().EndsWith(".dwg"))
fileList.Add(file);
}
}
Per Mozilla's Map documentation, you can initialize as follows:
private _gridOptions:Map<string, Array<string>> =
new Map([
["1", ["test"]],
["2", ["test2"]]
]);
I think that you'll probably have to use $.ajax()
if you want to change the encoding, see the contentType
param below (the success
and error
callbacks assume you have <div id="success"></div>
and <div id="error"></div>
in the html):
$.ajax({
type: "POST",
url: "SomePage.aspx/GetSomeObjects",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{id: '" + someId + "'}",
success: function(json) {
$("#success").html("json.length=" + json.length);
itemAddCallback(json);
},
error: function (xhr, textStatus, errorThrown) {
$("#error").html(xhr.responseText);
}
});
I actually just had to do this about an hour ago, what a coincidence!
I think stash -p
is probably the choice you want, but just in case you run into other even more tricky things in the future, remember that:
Stash
is really just a very simple alternative to the only slightly more complex branch
sets. Stash is very useful for moving things around quickly, but you can accomplish more complex things with branches without that much more headache and work.
# git checkout -b tmpbranch
# git add the_file
# git commit -m "stashing the_file"
# git checkout master
go about and do what you want, and then later simply rebase
and/or merge
the tmpbranch. It really isn't that much extra work when you need to do more careful tracking than stash will allow.
You can try this:
var theValue = document.getElementById("demo").getAttribute("value");
Just be careful when dividing by 60: division between integers returns an integer -> 12/60 = 0 unless you import division from future. The following is copy and pasted from Python 2.6.2:
IDLE 2.6.2
>>> 12/60
0
>>> from __future__ import division
>>> 12/60
0.20000000000000001
Change your code to.
<?php
$sqlupdate1 = "UPDATE table SET commodity_quantity=".$qty."WHERE user=".$rows['user'];
?>
There was syntax error in your query.
The main difference from other solutions here is that this one reuses logic in RequiredAttribute
on the server side, and uses required
's validation method depends
property on the client side:
public class RequiredIf : RequiredAttribute, IClientValidatable
{
public string OtherProperty { get; private set; }
public object OtherPropertyValue { get; private set; }
public RequiredIf(string otherProperty, object otherPropertyValue)
{
OtherProperty = otherProperty;
OtherPropertyValue = otherPropertyValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherProperty);
if (otherPropertyInfo == null)
{
return new ValidationResult($"Unknown property {OtherProperty}");
}
object otherValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
if (Equals(OtherPropertyValue, otherValue)) // if other property has the configured value
return base.IsValid(value, validationContext);
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "requiredif"; // data-val-requiredif
rule.ValidationParameters.Add("other", OtherProperty); // data-val-requiredif-other
rule.ValidationParameters.Add("otherval", OtherPropertyValue); // data-val-requiredif-otherval
yield return rule;
}
}
$.validator.unobtrusive.adapters.add("requiredif", ["other", "otherval"], function (options) {
var value = {
depends: function () {
var element = $(options.form).find(":input[name='" + options.params.other + "']")[0];
return element && $(element).val() == options.params.otherval;
}
}
options.rules["required"] = value;
options.messages["required"] = options.message;
});
if you use Bootstrap 2.2.1 then maybe is this what you are looking for.
Sample file index.html
<!DOCTYPE html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<title></title>_x000D_
<link href="Content/bootstrap.min.css" rel="stylesheet" />_x000D_
<link href="Content/Site.css" rel="stylesheet" />_x000D_
</head>_x000D_
<body>_x000D_
<menu>_x000D_
<div class="navbar navbar-default navbar-fixed-top">_x000D_
<div class="container">_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="/">Application name</a>_x000D_
</div>_x000D_
<div class="navbar-collapse collapse">_x000D_
<ul class="nav navbar-nav">_x000D_
<li><a href="/">Home</a></li>_x000D_
<li><a href="/Home/About">About</a></li>_x000D_
<li><a href="/Home/Contact">Contact</a></li>_x000D_
</ul>_x000D_
<ul class="nav navbar-nav navbar-right">_x000D_
<li><a href="/Account/Register" id="registerLink">Register</a></li>_x000D_
<li><a href="/Account/Login" id="loginLink">Log in</a></li>_x000D_
</ul>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</menu>_x000D_
_x000D_
<nav>_x000D_
<div class="col-md-2">_x000D_
<a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
<a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
<a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
<a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
</div>_x000D_
_x000D_
</nav>_x000D_
<content>_x000D_
<div class="col-md-10">_x000D_
_x000D_
<h2>About.</h2>_x000D_
<h3>Your application description page.</h3>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<hr />_x000D_
</div>_x000D_
</content>_x000D_
_x000D_
<footer>_x000D_
<div class="navbar navbar-default navbar-fixed-bottom">_x000D_
<div class="container" style="font-size: .8em">_x000D_
<p class="navbar-text">_x000D_
© Some info_x000D_
</p>_x000D_
</div>_x000D_
</div>_x000D_
</footer>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
body {_x000D_
padding-bottom: 70px;_x000D_
padding-top: 70px;_x000D_
}
_x000D_
From the comments, the problem was caused by using dlls that were built with Visual Studio 2013 in a project compiled with Visual Studio 2012. The reason for this was a third party library named the folders containing the dlls vc11, vc12. One has to be careful with any system that uses the compiler version (less than 4 digits) since this does not match the version of Visual Studio (except for Visual Studio 2010).
The Microsoft C++ runtime dlls use a 2 or 3 digit code also based on the compiler version not the version of Visual Studio.
There is binary compatibility between Visual Studio 2015, 2017 and 2019.
In its simplest form, this technique aims to wrap code inside a function scope.
It helps decreases chances of:
It does not detect when the document is ready - it is not some kind of document.onload
nor window.onload
It is commonly known as an Immediately Invoked Function Expression (IIFE)
or Self Executing Anonymous Function
.
var someFunction = function(){ console.log('wagwan!'); };
(function() { /* function scope starts here */
console.log('start of IIFE');
var myNumber = 4; /* number variable declaration */
var myFunction = function(){ /* function variable declaration */
console.log('formidable!');
};
var myObject = { /* object variable declaration */
anotherNumber : 1001,
anotherFunc : function(){ console.log('formidable!'); }
};
console.log('end of IIFE');
})(); /* function scope ends */
someFunction(); // reachable, hence works: see in the console
myFunction(); // unreachable, will throw an error, see in the console
myObject.anotherFunc(); // unreachable, will throw an error, see in the console
In the example above, any variable defined in the function (i.e. declared using var
) will be "private" and accessible within the function scope ONLY (as Vivin Paliath puts it). In other words, these variables are not visible/reachable outside the function. See live demo.
Javascript has function scoping. "Parameters and variables defined in a function are not visible outside of the function, and that a variable defined anywhere within a function is visible everywhere within the function." (from "Javascript: The Good Parts").
In the end, the code posted before could also be done as follows:
var someFunction = function(){ console.log('wagwan!'); };
var myMainFunction = function() {
console.log('start of IIFE');
var myNumber = 4;
var myFunction = function(){ console.log('formidable!'); };
var myObject = {
anotherNumber : 1001,
anotherFunc : function(){ console.log('formidable!'); }
};
console.log('end of IIFE');
};
myMainFunction(); // I CALL "myMainFunction" FUNCTION HERE
someFunction(); // reachable, hence works: see in the console
myFunction(); // unreachable, will throw an error, see in the console
myObject.anotherFunc(); // unreachable, will throw an error, see in the console
One day, someone probably thought "there must be a way to avoid naming 'myMainFunction', since all we want is to execute it immediately."
If you go back to the basics, you find out that:
expression
: something evaluating to a value. i.e. 3+11/x
statement
: line(s) of code doing something BUT it does not evaluate to a value. i.e. if(){}
Similarly, function expressions evaluate to a value. And one consequence (I assume?) is that they can be immediately invoked:
var italianSayinSomething = function(){ console.log('mamamia!'); }();
So our more complex example becomes:
var someFunction = function(){ console.log('wagwan!'); };
var myMainFunction = function() {
console.log('start of IIFE');
var myNumber = 4;
var myFunction = function(){ console.log('formidable!'); };
var myObject = {
anotherNumber : 1001,
anotherFunc : function(){ console.log('formidable!'); }
};
console.log('end of IIFE');
}();
someFunction(); // reachable, hence works: see in the console
myFunction(); // unreachable, will throw an error, see in the console
myObject.anotherFunc(); // unreachable, will throw an error, see in the console
The next step is the thought "why have var myMainFunction =
if we don't even use it!?".
The answer is simple: try removing this, such as below:
function(){ console.log('mamamia!'); }();
It won't work because "function declarations are not invokable".
The trick is that by removing var myMainFunction =
we transformed the function expression into a function declaration. See the links in "Resources" for more details on this.
The next question is "why can't I keep it as a function expression with something other than var myMainFunction =
?
The answer is "you can", and there are actually many ways you could do this: adding a +
, a !
, a -
, or maybe wrapping in a pair of parenthesis (as it's now done by convention), and more I believe. As example:
(function(){ console.log('mamamia!'); })(); // live demo: jsbin.com/zokuwodoco/1/edit?js,console.
or
+function(){ console.log('mamamia!'); }(); // live demo: jsbin.com/wuwipiyazi/1/edit?js,console
or
-function(){ console.log('mamamia!'); }(); // live demo: jsbin.com/wejupaheva/1/edit?js,console
So once the relevant modification is added to what was once our "Alternative Code", we return to the exact same code as the one used in the "Code Explained" example
var someFunction = function(){ console.log('wagwan!'); };
(function() {
console.log('start of IIFE');
var myNumber = 4;
var myFunction = function(){ console.log('formidable!'); };
var myObject = {
anotherNumber : 1001,
anotherFunc : function(){ console.log('formidable!'); }
};
console.log('end of IIFE');
})();
someFunction(); // reachable, hence works: see in the console
myFunction(); // unreachable, will throw an error, see in the console
myObject.anotherFunc(); // unreachable, will throw an error, see in the console
Read more about Expressions vs Statements
:
One thing one might wonder is "what happens when you do NOT define the variable 'properly' inside the function -- i.e. do a simple assignment instead?"
(function() {
var myNumber = 4; /* number variable declaration */
var myFunction = function(){ /* function variable declaration */
console.log('formidable!');
};
var myObject = { /* object variable declaration */
anotherNumber : 1001,
anotherFunc : function(){ console.log('formidable!'); }
};
myOtherFunction = function(){ /* oops, an assignment instead of a declaration */
console.log('haha. got ya!');
};
})();
myOtherFunction(); // reachable, hence works: see in the console
window.myOtherFunction(); // works in the browser, myOtherFunction is then in the global scope
myFunction(); // unreachable, will throw an error, see in the console
Basically, if a variable that was not declared in its current scope is assigned a value, then "a look up the scope chain occurs until it finds the variable or hits the global scope (at which point it will create it)".
When in a browser environment (vs a server environment like nodejs) the global scope is defined by the window
object. Hence we can do window.myOtherFunction()
.
My "Good practices" tip on this topic is to always use var
when defining anything: whether it's a number, object or function, & even when in the global scope. This makes the code much simpler.
Note:
block scope
(Update: block scope local variables added in ES6.)function scope
& global scope
(window
scope in a browser environment)Read more about Javascript Scopes
:
Once you get this IIFE
concept, it leads to the module pattern
, which is commonly done by leveraging this IIFE pattern. Have fun :)
It might be useful to assign a null in a string rather than explicitly making some index the null char '\0'
. I've used this for testing functions that handle strings ensuring they stay within their appropriate bounds.
With:
char test_src[] = "fuu\0foo";
This creates an array of size 8 with values:
{'f', 'u', 'u', '\0', 'f', 'o', 'o', '\0'}
Below is a fully functional example of what I believe you're trying to do (with a functional snippet).
Based on your question, you seem to be modifying 1 property in state
for all of your elements. That's why when you click on one, all of them are being changed.
In particular, notice that the state tracks an index of which element is active. When MyClickable
is clicked, it tells the Container
its index, Container
updates the state
, and subsequently the isActive
property of the appropriate MyClickable
s.
class Container extends React.Component {_x000D_
state = {_x000D_
activeIndex: null_x000D_
}_x000D_
_x000D_
handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
render() {_x000D_
return <div>_x000D_
<MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
<MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
<MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
</div>_x000D_
}_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
handleClick = () => this.props.onClick(this.props.index)_x000D_
_x000D_
render() {_x000D_
return <button_x000D_
type='button'_x000D_
className={_x000D_
this.props.isActive ? 'active' : 'album'_x000D_
}_x000D_
onClick={ this.handleClick }_x000D_
>_x000D_
<span>{ this.props.name }</span>_x000D_
</button>_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
display: block;_x000D_
margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable
elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.
// New render method for `Container`
render() {
const clickables = [
{ name: "a" },
{ name: "b" },
{ name: "c" },
]
return <div>
{ clickables.map(function(clickable, i) {
return <MyClickable key={ clickable.name }
name={ clickable.name }
index={ i }
isActive={ this.state.activeIndex === i }
onClick={ this.handleClick }
/>
} )
}
</div>
}
SELECT 'if object_id(''' + TABLE_NAME + ''') is not null begin drop table "' + TABLE_NAME + '" end;'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '[prefix]%'
There's a difference.
var x = 1
declares variable x
in current scope (aka execution context). If the declaration appears in a function - a local variable is declared; if it's in global scope - a global variable is declared.
x = 1
, on the other hand, is merely a property assignment. It first tries to resolve x
against scope chain. If it finds it anywhere in that scope chain, it performs assignment; if it doesn't find x
, only then does it creates x
property on a global object (which is a top level object in a scope chain).
Now, notice that it doesn't declare a global variable, it creates a global property.
The difference between the two is subtle and might be confusing unless you understand that variable declarations also create properties (only on a Variable Object) and that every property in Javascript (well, ECMAScript) have certain flags that describe their properties - ReadOnly, DontEnum and DontDelete.
Since variable declaration creates property with the DontDelete flag, the difference between var x = 1
and x = 1
(when executed in global scope) is that the former one - variable declaration - creates the DontDelete'able property, and latter one doesn't. As a consequence, the property created via this implicit assignment can then be deleted from the global object, and the former one - the one created via variable declaration - cannot be deleted.
But this is just theory of course, and in practice there are even more differences between the two, due to various bugs in implementations (such as those from IE).
Hope it all makes sense : )
[Update 2010/12/16]
In ES5 (ECMAScript 5; recently standardized, 5th edition of the language) there's a so-called "strict mode" — an opt-in language mode, which slightly changes the behavior of undeclared assignments. In strict mode, assignment to an undeclared identifier is a ReferenceError. The rationale for this was to catch accidental assignments, preventing creation of undesired global properties. Some of the newer browsers have already started rolling support for strict mode. See, for example, my compat table.
Under NT-style cmd.exe, you can loop through the lines of a text file with
FOR /F %i IN (file.txt) DO @echo %i
Type "help for" on the command prompt for more information. (don't know if that works in whatever "DOS" you are using)
Is this what you are after? Just index the element and assign a new value.
A[2,1]=150
A
Out[345]:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 150, 11, 12],
[13, 14, 15, 16]])
In my case I was getting this error trying to use the IS_ROLEMEMBER()
function on SQL Server 2008 R2. This function isn't valid prior to SQL Server 2012.
Instead of this function I ended up using
select 1
from sys.database_principals u
inner join sys.database_role_members ur
on u.principal_id = ur.member_principal_id
inner join sys.database_principals r
on ur.role_principal_id = r.principal_id
where r.name = @role_name
and u.name = @username
Significantly more verbose, but it gets the job done.
In order to avoid having to fully specify the git push command you could alternatively modify your git config file:
[remote "gerrit"]
url = https://your.gerrit.repo:44444/repo
fetch = +refs/heads/master:refs/remotes/origin/master
push = refs/heads/master:refs/for/master
Now you can simply:
git fetch gerrit
git push gerrit
This is according to Gerrit
First of all, check out my post on retained Fragments. It might help.
Now to answer your questions:
Does the fragment also retain its
viewstate, or will this be recreated on configuration change - what exactly is "retained"?
Yes, the Fragment
's state will be retained across the configuration change. Specifically, "retained" means that the fragment will not be destroyed on configuration changes. That is, the Fragment
will be retained even if the configuration change causes the underlying Activity
to be destroyed.
Will the fragment be destroyed when the user leaves the activity?
Just like Activity
s, Fragment
s may be destroyed by the system when memory resources are low. Whether you have your fragments retain their instance state across configuration changes will have no effect on whether or not the system will destroy the Fragment
s once you leave the Activity
. If you leave the Activity
(i.e. by pressing the home button), the Fragment
s may or may not be destroyed. If you leave the Activity
by pressing the back button (thus, calling finish()
and effectively destroying the Activity
), all of the Activity
s attached Fragment
s will also be destroyed.
Why doesn't it work with fragments on the back stack?
There are probably multiple reasons why it's not supported, but the most obvious reason to me is that the Activity
holds a reference to the FragmentManager
, and the FragmentManager
manages the backstack. That is, no matter if you choose to retain your Fragment
s or not, the Activity
(and thus the FragmentManager
's backstack) will be destroyed on a configuration change. Another reason why it might not work is because things might get tricky if both retained fragments and non-retained fragments were allowed to exist on the same backstack.
Which are the use cases where it makes sense to use this method?
Retained fragments can be quite useful for propagating state information — especially thread management — across activity instances. For example, a fragment can serve as a host for an instance of Thread
or AsyncTask
, managing its operation. See my blog post on this topic for more information.
In general, I would treat it similarly to using onConfigurationChanged
with an Activity
... don't use it as a bandaid just because you are too lazy to implement/handle an orientation change correctly. Only use it when you need to.
Here is another way as an alternative:
Write-Host (" {0} - {1} - {2}" -f $assoc.Id, $assoc.Name, $assoc.Owner)
few day ago I have the SAME problem with 1 table.
Firstly try:
echo json_encode($rows);
echo json_last_error(); // returns 5 ?
If last line returns 5, problem is with your data. I know, your tables are in UTF-8, but not entered data. For example the input was in txt file, but created on Win machine with stupid encoding (in my case Win-1250 = CP1250) and this data has been entered into the DB.
Solution? Look for new data (excel, web page), edit source txt file via PSPad (or whatever else), change encoding to UTF-8, delete all rows and now put data from original. Save. Enter into DB.
You can also only change encoding to utf-8 and then change all rows manually (give cols with special chars - desc, ...). Good for slaves...
Well you are trying to compare Date with Nvarchar which is wrong. Should be
Where dates between date1 And date2
-- both date1 & date2 should be date/datetime
If date1,date2 strings; server will convert them to date type before filtering.
EABI = Embedded Application Binary Interface. It is such specifications to which an executable must conform in order to execute in a specific execution environment. It also specifies various aspects of compilation and linkage required for interoperation between toolchains used for the ARM Architecture. In this context when we speak about armeabi we speak about ARM architecture and GNU/Linux OS. Android follows the little-endian ARM GNU/Linux ABI.
armeabi application will run on ARMv5 (e.g. ARM9) and ARMv6 (e.g. ARM11). You may use Floating Point hardware if you build your application using proper GCC options like -mfpu=vfpv3 -mfloat-abi=softfp which tells compiler to generate floating point instructions for VFP hardware and enables the soft-float calling conventions. armeabi doesn't support hard-float calling conventions (it means FP registers are not used to contain arguments for a function), but FP operations in HW are still supported.
armeabi-v7a application will run on Cortex A# devices like Cortex A8, A9, and A15. It supports multi-core processors and it supports -mfloat-abi=hard. So, if you build your application using -mfloat-abi=hard, many of your function calls will be faster.
With Postgres 9.3+, just use the ->
operator. For example,
SELECT data->'images'->'thumbnail'->'url' AS thumb FROM instagram;
see http://clarkdave.net/2013/06/what-can-you-do-with-postgresql-and-json/ for some nice examples and a tutorial.
For me, three steps solved this problem on windows 10:
I downloaded MySQL server community edition zip and extracted it in the D drive. After that I went to bin
folder and did cmd
on that folder. I followed the below steps and all works:
D:\tools\mysql-8.0.17-winx64\bin>mysqld -install
Service successfully installed.
D:\tools\mysql-8.0.17-winx64\bin>mysqld --initialize
D:\tools\mysql-8.0.17-winx64\bin>net start mysql
The MySQL service is starting...
The MySQL service was started successfully.
For me just worked iisreset (run cmd as administrator -> iisreset). Maybe somebody could give it a try.
Doubles are approximations of the decimal numbers in your Java source. You're seeing the consequence of the mismatch between the double (which is a binary-coded value) and your source (which is decimal-coded).
Java's producing the closest binary approximation. You can use the java.text.DecimalFormat to display a better-looking decimal value.
I would go with
i = np.min(np.where(V >= x))
where V
is vector (1d array), x
is the value and i
is the resulting index.
There is a function in scipy named scipy.signal.find_peaks_cwt
which sounds like is suitable for your needs, however I don't have experience with it so I cannot recommend..
http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks_cwt.html
That's because, it gets returned after validateView();;
Use this:
OnClientClick="var ret = validateView();ShowDiv1(); return ret;"
I always use:
Copy&paste
svn st | grep "^\?" | awk "{print \$2}" | xargs svn add $1
In C#, float
is an alias for System.Single
(a bit like int
is an alias for System.Int32
).
I think this is exactly what you were looking for
http://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html
http://code.google.com/p/flying-saucer
Flying Saucer's primary purpose is to render spec-compliant XHTML and CSS 2.1 to the screen as a Swing component. Though it was originally intended for embedding markup into desktop applications (things like the iTunes Music Store), Flying Saucer has been extended work with iText as well. This makes it very easy to render XHTML to PDFs, as well as to images and to the screen. Flying Saucer requires Java 1.4 or higher.
pixVals = list(pilImg.getdata())
output is a list of all RGB values from the picture:
[(248, 246, 247), (246, 248, 247), (244, 248, 247), (244, 248, 247), (246, 248, 247), (248, 246, 247), (250, 246, 247), (251, 245, 247), (253, 244, 247), (254, 243, 247)]
Short Answer:
Long Answer:
What is the purpose of a URL?
If pointing to an address is the answer, then a shortened URL is also doing a good job. If we don't make it easy to read and maintain, it won't help developers and maintainers alike. They represent an entity on the server, so they must be named logically.
Google recommends using hyphens
Consider using punctuation in your URLs. The URL http://www.example.com/green-dress.html is much more useful to us than http://www.example.com/greendress.html. We recommend that you use hyphens (-) instead of underscores (_) in your URLs.
Coming from a programming background, camelCase is a popular choice for naming joint words.
But RFC 3986 defines URLs as case-sensitive for different parts of the URL. Since URLs are case sensitive, keeping it low-key (lower cased) is always safe and considered a good standard. Now that takes a camel case out of the window.
Source: https://metamug.com/article/rest-api-naming-best-practices.html#word-delimiters
Here's an example with Alarm Manager using Kotlin:
class MainActivity : AppCompatActivity() {
val editText: EditText by bindView(R.id.edit_text)
val timePicker: TimePicker by bindView(R.id.time_picker)
val buttonSet: Button by bindView(R.id.button_set)
val buttonCancel: Button by bindView(R.id.button_cancel)
val relativeLayout: RelativeLayout by bindView(R.id.activity_main)
var notificationId = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
timePicker.setIs24HourView(true)
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
buttonSet.setOnClickListener {
if (editText.text.isBlank()) {
Toast.makeText(applicationContext, "Title is Required!!", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
alarmManager.set(
AlarmManager.RTC_WAKEUP,
Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, timePicker.hour)
set(Calendar.MINUTE, timePicker.minute)
set(Calendar.SECOND, 0)
}.timeInMillis,
PendingIntent.getBroadcast(
applicationContext,
0,
Intent(applicationContext, AlarmBroadcastReceiver::class.java).apply {
putExtra("notificationId", ++notificationId)
putExtra("reminder", editText.text)
},
PendingIntent.FLAG_CANCEL_CURRENT
)
)
Toast.makeText(applicationContext, "SET!! ${editText.text}", Toast.LENGTH_SHORT).show()
reset()
}
buttonCancel.setOnClickListener {
alarmManager.cancel(
PendingIntent.getBroadcast(
applicationContext, 0, Intent(applicationContext, AlarmBroadcastReceiver::class.java), 0))
Toast.makeText(applicationContext, "CANCEL!!", Toast.LENGTH_SHORT).show()
}
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
(getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
.hideSoftInputFromWindow(relativeLayout.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
relativeLayout.requestFocus()
return super.onTouchEvent(event)
}
override fun onResume() {
super.onResume()
reset()
}
private fun reset() {
timePicker.apply {
val now = Calendar.getInstance()
hour = now.get(Calendar.HOUR_OF_DAY)
minute = now.get(Calendar.MINUTE)
}
editText.setText("")
}
}
I found a way to do it (dont know if it is the best but it works)
string oldFile = "oldFile.pdf";
string newFile = "newFile.pdf";
// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
// the pdf content
PdfContentByte cb = writer.DirectContent;
// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252,BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);
// write the text in the pdf content
cb.BeginText();
string text = "Some random blablablabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 520, 640, 0);
cb.EndText();
cb.BeginText();
text = "Other random blabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(2, text, 100, 200, 0);
cb.EndText();
// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
// close the streams and voilá the file should be changed :)
document.Close();
fs.Close();
writer.Close();
reader.Close();
I hope this can be usefull for someone =) (and post here any errors)
I found a good solution that uses the maxlength attribute if the browser supports it, and falls back to an unobtrusive javascript pollyfill in unsupporting browsers.
Thanks to @Dan Tello's comment I fixed it up so it works in IE7+ as well:
HTML:
<textarea maxlength="50" id="text">This textarea has a character limit of 50.</textarea>
Javascript:
function maxLength(el) {
if (!('maxLength' in el)) {
var max = el.attributes.maxLength.value;
el.onkeypress = function () {
if (this.value.length >= max) return false;
};
}
}
maxLength(document.getElementById("text"));
There is no such thing as a minlength
attribute in HTML5.
For the following input types: number
, range
, date
, datetime
, datetime-local
, month
, time
, and week
(which aren't fully supported yet) use the min
and max
attributes.
Sometime floats brake the vertical align, is better to avoid them.
Here is the shortest solution (One Liner) ES6:
Math.max(...values.map(o => o.y));
If you frequently use a large number of exceptions, you can pre-define a tuple, so you don't have to re-type them many times.
#This example code is a technique I use in a library that connects with websites to gather data
ConnectErrs = (URLError, SSLError, SocketTimeoutError, BadStatusLine, ConnectionResetError)
def connect(url, data):
#do connection and return some data
return(received_data)
def some_function(var_a, var_b, ...):
try: o = connect(url, data)
except ConnectErrs as e:
#do the recovery stuff
blah #do normal stuff you would do if no exception occurred
NOTES:
If you, also, need to catch other exceptions than those in the pre-defined tuple, you will need to define another except block.
If you just cannot tolerate a global variable, define it in main() and pass it around where needed...
You need to install some packages such as Unlocker, GuestOSx, etc.
Why not just:
int plusIndex = s.indexOf("+");
if (plusIndex != -1) {
String before = s.substring(0, plusIndex);
// Use before
}
It's not really clear why your original version didn't work, but then you didn't say what actually happened. If you want to split not using regular expressions, I'd personally use Guava:
Iterable<String> bits = Splitter.on('+').split(s);
String firstPart = Iterables.getFirst(bits, "");
If you're going to use split
(either the built-in version or Guava) you don't need to check whether it contains +
first - if it doesn't there'll only be one result anyway. Obviously there's a question of efficiency, but it's simpler code:
// Calling split unconditionally
String[] parts = s.split("\\+");
s = parts[0];
Note that writing String[] parts
is preferred over String parts[]
- it's much more idiomatic Java code.
You can use as the following code;
cd /my_folder && \
rm *.jar && \
svn co path to repo && \
mvn compile package install
It works...
$file = '../image.jpg';
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
readfile($file);
The latter is preferred, because it will handle subclasses properly. In fact, your example can be written even more easily because isinstance()
's second parameter may be a tuple:
if isinstance(b, (str, unicode)):
do_something_else()
or, using the basestring
abstract class:
if isinstance(b, basestring):
do_something_else()
mysqldump --extended-insert=FALSE
Be aware that multiple inserts will be slower than one big insert.
Like this:
from c in db.Company
group c by c.Name into grp
where grp.Count() > 1
select grp.Key
Or, using the method syntax:
Company
.GroupBy(c => c.Name)
.Where(grp => grp.Count() > 1)
.Select(grp => grp.Key);
I have had this problem when I also recieved a TCP error in the event log...
Drop the DB with sql or right click on it in manager "delete" And restore again.
I have actually started doing this by default. Script the DB drop, recreate and then restore.
Demo: http://www.jqueryscript.net/demo/jQuery-Plugin-For-Fixed-Table-Header-Footer-Columns-TableHeadFixer/
HTML
<h2>TableHeadFixer Fix Left Column</h2>
<div id="parent">
<table id="fixTable" class="table">
<thead>
<tr>
<th>Ano</th>
<th>Jan</th>
<th>Fev</th>
<th>Mar</th>
<th>Abr</th>
<th>Maio</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
</tbody>
</table>
</div>
JS
$(document).ready(function() {
$("#fixTable").tableHeadFixer({"head" : false, "right" : 1});
});
CSS
#parent {
height: 300px;
}
#fixTable {
width: 1800px !important;
}
Java 8 added a new way of making Comparators that reduces the amount of code you have to write, Comparator.comparing. Also check out Comparator.reversed
Here's a sample
import org.junit.Test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import static org.junit.Assert.assertTrue;
public class ComparatorTest {
@Test
public void test() {
List<Person> peopleList = new ArrayList<>();
peopleList.add(new Person("A", 1000));
peopleList.add(new Person("B", 1));
peopleList.add(new Person("C", 50));
peopleList.add(new Person("Z", 500));
//sort by name, ascending
peopleList.sort(Comparator.comparing(Person::getName));
assertTrue(peopleList.get(0).getName().equals("A"));
assertTrue(peopleList.get(peopleList.size() - 1).getName().equals("Z"));
//sort by name, descending
peopleList.sort(Comparator.comparing(Person::getName).reversed());
assertTrue(peopleList.get(0).getName().equals("Z"));
assertTrue(peopleList.get(peopleList.size() - 1).getName().equals("A"));
//sort by age, ascending
peopleList.sort(Comparator.comparing(Person::getAge));
assertTrue(peopleList.get(0).getAge() == 1);
assertTrue(peopleList.get(peopleList.size() - 1).getAge() == 1000);
//sort by age, descending
peopleList.sort(Comparator.comparing(Person::getAge).reversed());
assertTrue(peopleList.get(0).getAge() == 1000);
assertTrue(peopleList.get(peopleList.size() - 1).getAge() == 1);
}
class Person {
String name;
int age;
Person(String n, int a) {
name = n;
age = a;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
}
Existing answers paraphrase the main point quite well.
The main point is that ECMAScript is the bare abstract language, without any domain specific extensions, it's useless in itself. The specification defines only the language and the core objects of it.
While JavaScript and ActionScript and other dialects add the domain specific library to it, so you can use it for something meaningful.
There are many ECMAScript engines, some of them are open source, others are proprietary. You can link them into your program then add your native functions to the global object so your program becomes scriptable. Although most often they are used in browsers.
Since ID is auto increment, you can also specify ID=NULL as,
LOAD XML LOCAL INFILE '/pathtofile/file.xml' INTO TABLE my_tablename SET ID=NULL;
If someone is here in 2020, after making all the pipes, if u pipe %>% na.exclude
will take away all the NAs in the pipe!
Even if there aren't much properties to change, but you can achieve following style only with css:
.options {
border: 1px solid #e5e5e5;
padding: 10px;
}
select {
font-size: 14px;
border: none;
width: 100%;
background: white;
}
_x000D_
<div class="options">
<select>
<option value="">Apple</option>
<option value="">Banana</option>
<option value="">Orange</option>
<option value="">Mango</option>
</select>
</div>
_x000D_
Sessions would be the only good way, you could also use GET/POST but that would be potentially insecure.
For me it worked:
df['id'].convert_dtypes()
see the documentation here:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.convert_dtypes.html
Delete these entries mentioned in this post: http://manfredlange.blogspot.ca/2008/03/visual-studio-unable-to-find-manifest.html.
Also remove the .snk or .pfx files from the project root.
Don't forget to push these changes to GitHub, for Jenkins only pulls source from GitHub.
List<T>.Add
adds a single element. Instead, use List<T>.AddRange
to add multiple values.
Additionally, List<T>.AddRange
takes an IEnumerable<T>
, so you don't need to convert tripDetails
into a List<TripDetails>
, you can pass it directly, e.g.:
tripDetailsCollection.AddRange(tripDetails);
Just doing like @Kjartan.
Steps are as follows:
Right click your C# project name in Visual Studio's "Solution Explorer";
Then, select "add -> Reference -> COM -> Type Libraries " in order;
Find the "Microsoft Office 16.0 Object Library", and add it to reference (Note: the version number may vary with the OFFICE you have installed);
After doing this, you will see "Microsoft.Office.Interop.Word" under the "Reference" item in your project.
I got this problem, and tried many ways to solve it. Finally, it turned out that make clean
and make
again solved it. The reason is:
I got the source code together with object files compiled previously with an old gcc version. When my newer gcc version wants to link that old object files, it can't resolve some function in there. It happens to me several times that the source code distributors do not clean up before packing, so a make clean
saved the day.
"FEB-2010" is not a Date, so it would not make a lot of sense to store it in a date column.
You can always extract the string part you need , in your case "MON-YYYY" using the TO_CHAR logic you showed above.
If this is for a DIMENSION table in a Data warehouse environment and you want to include these as separate columns in the Dimension table (as Data attributes), you will need to store the month and Year in two different columns, with appropriate Datatypes...
Example..
Month varchar2(3) --Month code in Alpha..
Year NUMBER -- Year in number
or
Month number(2) --Month Number in Year.
Year NUMBER -- Year in number
You will definitely want to start with a good web scraping framework. Later on you may decide that they are too limiting and you can put together your own stack of libraries but without a lot of scraping experience your design will be much worse than pjscrape or scrapy.
Note: I use the terms crawling and scraping basically interchangeable here. This is a copy of my answer to your Quora question, it's pretty long.
Tools
Get very familiar with either Firebug or Chrome dev tools depending on your preferred browser. This will be absolutely necessary as you browse the site you are pulling data from and map out which urls contain the data you are looking for and what data formats make up the responses.
You will need a good working knowledge of HTTP as well as HTML and will probably want to find a decent piece of man in the middle proxy software. You will need to be able to inspect HTTP requests and responses and understand how the cookies and session information and query parameters are being passed around. Fiddler (http://www.telerik.com/fiddler) and Charles Proxy (http://www.charlesproxy.com/) are popular tools. I use mitmproxy (http://mitmproxy.org/) a lot as I'm more of a keyboard guy than a mouse guy.
Some kind of console/shell/REPL type environment where you can try out various pieces of code with instant feedback will be invaluable. Reverse engineering tasks like this are a lot of trial and error so you will want a workflow that makes this easy.
Language
PHP is basically out, it's not well suited for this task and the library/framework support is poor in this area. Python (Scrapy is a great starting point) and Clojure/Clojurescript (incredibly powerful and productive but a big learning curve) are great languages for this problem. Since you would rather not learn a new language and you already know Javascript I would definitely suggest sticking with JS. I have not used pjscrape but it looks quite good from a quick read of their docs. It's well suited and implements an excellent solution to the problem I describe below.
A note on Regular expressions: DO NOT USE REGULAR EXPRESSIONS TO PARSE HTML. A lot of beginners do this because they are already familiar with regexes. It's a huge mistake, use xpath or css selectors to navigate html and only use regular expressions to extract data from actual text inside an html node. This might already be obvious to you, it becomes obvious quickly if you try it but a lot of people waste a lot of time going down this road for some reason. Don't be scared of xpath or css selectors, they are WAY easier to learn than regexes and they were designed to solve this exact problem.
Javascript-heavy sites
In the old days you just had to make an http request and parse the HTML reponse. Now you will almost certainly have to deal with sites that are a mix of standard HTML HTTP request/responses and asynchronous HTTP calls made by the javascript portion of the target site. This is where your proxy software and the network tab of firebug/devtools comes in very handy. The responses to these might be html or they might be json, in rare cases they will be xml or something else.
There are two approaches to this problem:
The low level approach:
You can figure out what ajax urls the site javascript is calling and what those responses look like and make those same requests yourself. So you might pull the html from http://example.com/foobar and extract one piece of data and then have to pull the json response from http://example.com/api/baz?foo=b... to get the other piece of data. You'll need to be aware of passing the correct cookies or session parameters. It's very rare, but occasionally some required parameters for an ajax call will be the result of some crazy calculation done in the site's javascript, reverse engineering this can be annoying.
The embedded browser approach:
Why do you need to work out what data is in html and what data comes in from an ajax call? Managing all that session and cookie data? You don't have to when you browse a site, the browser and the site javascript do that. That's the whole point.
If you just load the page into a headless browser engine like phantomjs it will load the page, run the javascript and tell you when all the ajax calls have completed. You can inject your own javascript if necessary to trigger the appropriate clicks or whatever is necessary to trigger the site javascript to load the appropriate data.
You now have two options, get it to spit out the finished html and parse it or inject some javascript into the page that does your parsing and data formatting and spits the data out (probably in json format). You can freely mix these two options as well.
Which approach is best?
That depends, you will need to be familiar and comfortable with the low level approach for sure. The embedded browser approach works for anything, it will be much easier to implement and will make some of the trickiest problems in scraping disappear. It's also quite a complex piece of machinery that you will need to understand. It's not just HTTP requests and responses, it's requests, embedded browser rendering, site javascript, injected javascript, your own code and 2-way interaction with the embedded browser process.
The embedded browser is also much slower at scale because of the rendering overhead but that will almost certainly not matter unless you are scraping a lot of different domains. Your need to rate limit your requests will make the rendering time completely negligible in the case of a single domain.
Rate Limiting/Bot behaviour
You need to be very aware of this. You need to make requests to your target domains at a reasonable rate. You need to write a well behaved bot when crawling websites, and that means respecting robots.txt and not hammering the server with requests. Mistakes or negligence here is very unethical since this can be considered a denial of service attack. The acceptable rate varies depending on who you ask, 1req/s is the max that the Google crawler runs at but you are not Google and you probably aren't as welcome as Google. Keep it as slow as reasonable. I would suggest 2-5 seconds between each page request.
Identify your requests with a user agent string that identifies your bot and have a webpage for your bot explaining it's purpose. This url goes in the agent string.
You will be easy to block if the site wants to block you. A smart engineer on their end can easily identify bots and a few minutes of work on their end can cause weeks of work changing your scraping code on your end or just make it impossible. If the relationship is antagonistic then a smart engineer at the target site can completely stymie a genius engineer writing a crawler. Scraping code is inherently fragile and this is easily exploited. Something that would provoke this response is almost certainly unethical anyway, so write a well behaved bot and don't worry about this.
Testing
Not a unit/integration test person? Too bad. You will now have to become one. Sites change frequently and you will be changing your code frequently. This is a large part of the challenge.
There are a lot of moving parts involved in scraping a modern website, good test practices will help a lot. Many of the bugs you will encounter while writing this type of code will be the type that just return corrupted data silently. Without good tests to check for regressions you will find out that you've been saving useless corrupted data to your database for a while without noticing. This project will make you very familiar with data validation (find some good libraries to use) and testing. There are not many other problems that combine requiring comprehensive tests and being very difficult to test.
The second part of your tests involve caching and change detection. While writing your code you don't want to be hammering the server for the same page over and over again for no reason. While running your unit tests you want to know if your tests are failing because you broke your code or because the website has been redesigned. Run your unit tests against a cached copy of the urls involved. A caching proxy is very useful here but tricky to configure and use properly.
You also do want to know if the site has changed. If they redesigned the site and your crawler is broken your unit tests will still pass because they are running against a cached copy! You will need either another, smaller set of integration tests that are run infrequently against the live site or good logging and error detection in your crawling code that logs the exact issues, alerts you to the problem and stops crawling. Now you can update your cache, run your unit tests and see what you need to change.
Legal Issues
The law here can be slightly dangerous if you do stupid things. If the law gets involved you are dealing with people who regularly refer to wget and curl as "hacking tools". You don't want this.
The ethical reality of the situation is that there is no difference between using browser software to request a url and look at some data and using your own software to request a url and look at some data. Google is the largest scraping company in the world and they are loved for it. Identifying your bots name in the user agent and being open about the goals and intentions of your web crawler will help here as the law understands what Google is. If you are doing anything shady, like creating fake user accounts or accessing areas of the site that you shouldn't (either "blocked" by robots.txt or because of some kind of authorization exploit) then be aware that you are doing something unethical and the law's ignorance of technology will be extraordinarily dangerous here. It's a ridiculous situation but it's a real one.
It's literally possible to try and build a new search engine on the up and up as an upstanding citizen, make a mistake or have a bug in your software and be seen as a hacker. Not something you want considering the current political reality.
Who am I to write this giant wall of text anyway?
I've written a lot of web crawling related code in my life. I've been doing web related software development for more than a decade as a consultant, employee and startup founder. The early days were writing perl crawlers/scrapers and php websites. When we were embedding hidden iframes loading csv data into webpages to do ajax before Jesse James Garrett named it ajax, before XMLHTTPRequest was an idea. Before jQuery, before json. I'm in my mid-30's, that's apparently considered ancient for this business.
I've written large scale crawling/scraping systems twice, once for a large team at a media company (in Perl) and recently for a small team as the CTO of a search engine startup (in Python/Javascript). I currently work as a consultant, mostly coding in Clojure/Clojurescript (a wonderful expert language in general and has libraries that make crawler/scraper problems a delight)
I've written successful anti-crawling software systems as well. It's remarkably easy to write nigh-unscrapable sites if you want to or to identify and sabotage bots you don't like.
I like writing crawlers, scrapers and parsers more than any other type of software. It's challenging, fun and can be used to create amazing things.
OK, first of all I'm not sure how it works when you create a div using (document.createElement('div'))
, so I might be wrong now, but wouldn't it be possible to use the :target pseudo class selector for this?
If you look at the code below, you can se I've used a link to target the div, but in your case it might be possible to target #new from the script instead and that way make the div fade in without user interaction, or am I thinking wrong?
Here's the code for my example:
HTML
<a href="#new">Click</a>
<div id="new">
Fade in ...
</div>
CSS
#new {
width: 100px;
height: 100px;
border: 1px solid #000000;
opacity: 0;
}
#new:target {
-webkit-transition: opacity 2.0s ease-in;
-moz-transition: opacity 2.0s ease-in;
-o-transition: opacity 2.0s ease-in;
opacity: 1;
}
... and here's a jsFiddle
This should give the location of the files that contain your pattern:
Get-ChildItem -Recurse | Select-String "dummy" -List | Select Path
better code that doesn't involve ping:
SET COUNTER=0
:loop
SET /a COUNTER=%COUNTER%+1
XCOPY "Server\*" "c:\minecraft\backups\server_backup_%COUNTER%" /i /s
timeout /t 600 /nobreak >nul
goto loop
600 seconds is 10 minutes, however you can set it whatever time you'd like
I think its too late to reply on this thread. But I would like to share my idea or way to resolve text size problem over difference resolution devices. Many android developer sites suggest that we have to use sp unit for text size which will handle text size for difference resolution devices. But I am always unable to get the desired result. So I have found one solution which I am using from my last 4-5 projects and its working fine. As per my suggestion, you have to place the text size for each resolution devices, which is bit tedious work, but it will fulfill your requirement. Each developer has must listen about the ratio like 4:6:8:12 (h:xh:xxh:xxxh respectively). Now inside your project res folder you have to create 4 folder with dimens file e.g.
Now inside dimens.xml file you have to place text sizes. I am showing you code for values-hdpi, similarly you have to place code for other resolution values/dimens.xml file.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="text_size">4px</dimen>
</resources>
For other resolutions it is like xhdpi : 6px, xxhdpi : 8px, xxxhdpi : 12px. This is calculated with the ratio (3:4:6:8:12) I have written above. Lets discuss other text size example with above ratio. If you want to take text size of 12px in hdpi, then in other resolution it would be
This is the simple solution to implement required text size for all resolutions. I am not considering values-mdpi resolution devices here. If any one want to include text size for this resolution then ration is like 3:4:6:8:12. In any query please let me know. Hope it will help you people out.
This works for me:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title> Fullscreen Div </title>
<style>
.test{
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
z-index: 10;
}
</style>
</head>
<body>
<div class='test'>Some text</div>
</body>
</html>
Define the expected and desired output for a normal case, with correct input.
Now, implement the test by declaring a class, name it anything (Usually something like TestAddingModule), and add the testAdd method to it (i.e. like the one below) :
assertEquals(expectedVal,calculatedVal)
.Test your method by running it (in Eclipse, right click, select Run as ? JUnit test).
//for normal addition
@Test
public void testAdd1Plus1()
{
int x = 1 ; int y = 1;
assertEquals(2, myClass.add(x,y));
}
Add other cases as desired.
Test that your method handles Null inputs gracefully (example below).
//if you are using 0 as default for null, make sure your class works in that case.
@Test
public void testAdd1Plus1()
{
int y = 1;
assertEquals(0, myClass.add(null,y));
}
In a shameless attempt to steal some votes, SecurityProtocol
is an Enum
with the [Flags]
attribute. So you can do this:
[Net.ServicePointManager]::SecurityProtocol =
[Net.SecurityProtocolType]::Tls12 -bor `
[Net.SecurityProtocolType]::Tls11 -bor `
[Net.SecurityProtocolType]::Tls
Or since this is PowerShell, you can let it parse a string for you:
[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
Then you don't technically need to know the TLS version.
I copied and pasted this from a script I created after reading this answer because I didn't want to cycle through all the available protocols to find one that worked. Of course, you could do that if you wanted to.
Final note - I have the original (minus SO edits) statement in my PowerShell profile so it's in every session I start now. It's not totally foolproof since there are still some sites that just fail but I surely see the message in question much less frequently.
Change your default controller which is in config file.
i.e : config/routes.php
$route['default_controller'] = "Your controller name";
Hope this will help.
If you want an alternative to ReflectionTestUtils from Spring in mockito, use
Whitebox.setInternalState(first, "second", sec);
I had the same issue. Not able to install neither using Marketplace nor Servers tab.
Following is the alternative.
1) Help -> Install New Software
2) Use url : http://download.oracle.com/otn_software/oepe/12.1.3.6/luna/repository Above is the OEPE tool provided by oracle for EE development.
3) From all the suggestions, select glassfish tools.
4) Install it.
5) Restart eclipse.
Eclipse 4.4.2 Luna JDK : 1.8
If you are a beginner, it is better you first go through some basic tutorials and after that learn about naming conventions. I have gone through the following to learn Angular, some of which are very effective.
Tutorials :
Details of application structure and naming conventions can be found in a variety of places. I've gone through 100's of sites and I think these are among the best:
The easy way to do this is to put the Date function you want to use in a Cell, and link to that cell from the textbox with the LinkedCell property.
From VBA you might try using:
textbox.Value = Format(Date(),"mm/dd/yy")
Following worked for me:
If you get the following error In order to install Windows Azure Active Directory Module for Windows PowerShell, you must have Microsoft Online Services Sign-In Assistant version 7.0 or greater installed on this computer, then install the Microsoft Online Services Sign-In Assistant for IT Professionals BETA: http://www.microsoft.com/en-us/download/details.aspx?id=39267
C:\Windows\System32\WindowsPowerShell\v1.0\Modules\
to the folder
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\
https://stackoverflow.com/a/16018733/5810078.
(But I have actually copied all the possible files from
C:\Windows\System32\WindowsPowerShell\v1.0\
to
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\
(For copying you need to alter the security permissions of that folder))
click WAMP icon -> Apache -> httpd.conf and find listen 80
new versions of WAMP uses
Listen 0.0.0.0:80
Listen [::0]:80ServerName localhost:80
Change Port Number as you want, like
Listen 0.0.0.0:81
Listen [::0]:81ServerName localhost:81
and now restart Wamp, thats it
and in web browser type as
Happy Coding..
Cross browser approach to hiding the scrollbar.
It was tested on Edge, Chrome, Firefox, and Safari
Hide scrollbar while still being able to scroll with mouse wheel!
/* Make parent invisible */
#parent {
visibility: hidden;
overflow: scroll;
}
/* Safari and Chrome specific style. Don't need to make parent invisible, because we can style WebKit scrollbars */
#parent:not(*:root) {
visibility: visible;
}
/* Make Safari and Chrome scrollbar invisible */
#parent::-webkit-scrollbar {
visibility: hidden;
}
/* Make the child visible */
#child {
visibility: visible;
}
With a button
bool _paused = false;
CupertinoButton(
child: _paused ? Text('Play') : Text('Pause'),
color: Colors.blue,
onPressed: () {
setState(() {
_paused = !_paused;
});
},
),
REST is just a software architecture style for exposing resources.
A typical REST call to return information about customer 34456 could look like:
http://example.com/customer/34456
Have a look at the IBM tutorial for REST web services
It is ugly and performs badly, but technically this works on any table with at least one unique field AND works in SQL 2000.
SELECT (SELECT COUNT(*) FROM myTable T1 WHERE T1.UniqueField<=T2.UniqueField) as RowNum, T2.OtherField
FROM myTable T2
ORDER By T2.UniqueField
Note: If you use this approach and add a WHERE clause to the outer SELECT, you have to added it to the inner SELECT also if you want the numbers to be continuous.
Active Directory isn't just an implementation of LDAP by Microsoft, that is only a small part of what AD is. Active Directory is (in an overly simplified way) a service that provides LDAP based authentication with Kerberos based Authorization.
Of course their LDAP and Kerberos implementations in AD are not exactly 100% interoperable with other LDAP/Kerberos implementations...
I know this is old and there are several good solutions already posted, but a simple solution that worked for me is the following CSS
<style>
.divider{
margin: 0cm 0cm .5cm 0cm;
}
</style>
and then create a div in your html
<div class="divider"></div>
massedit.py (http://github.com/elmotec/massedit) does the scaffolding for you leaving just the regex to write. It's still in beta but we are looking for feedback.
python -m massedit -e "re.sub(r'^# deb', 'deb', line)" /etc/apt/sources.list
will show the differences (before/after) in diff format.
Add the -w option to write the changes to the original file:
python -m massedit -e "re.sub(r'^# deb', 'deb', line)" -w /etc/apt/sources.list
Alternatively, you can now use the api:
>>> import massedit
>>> filenames = ['/etc/apt/sources.list']
>>> massedit.edit_files(filenames, ["re.sub(r'^# deb', 'deb', line)"], dry_run=True)
No, there is no difference. But I prefer using int[] array
as it is more readable.
Try UISegmentedControl. It behaves similarly to radio buttons -- presents an array of choices and lets the user pick 1.
In Java 8 you can use the Supplier
functional interface to achieve this pretty easily:
class SomeContainer<E> {
private Supplier<E> supplier;
SomeContainer(Supplier<E> supplier) {
this.supplier = supplier;
}
E createContents() {
return supplier.get();
}
}
You would construct this class like this:
SomeContainer<String> stringContainer = new SomeContainer<>(String::new);
The syntax String::new
on that line is a constructor reference.
If your constructor takes arguments you can use a lambda expression instead:
SomeContainer<BigInteger> bigIntegerContainer
= new SomeContainer<>(() -> new BigInteger(1));
I wouldn't even pay attention to the contents of the parens.
Just match any line that starts with for
and ends with semi-colon:
^\t*for.+;$
Unless you've got for
statements split over multiple lines, that will work fine?
On Mac IntelliJ Idea 12 has it's preferences/keymaps placed here: ./Users/viliuskraujutis/Library/Preferences/IdeaIC12/keymaps/
Subversion is still a much more used version control system, which means that it has better tool support. You'll find mature SVN plugins for almost any IDE, and there are good explorer extensions available (like TurtoiseSVN). Other than that, I'll have to agree with Michael: Git isn't better or worse than Subversion, it's different.
According to the issue DATAJPA-231 the feature is not implemented yet.
n = int(input()) #n is the number of items you want to enter
d ={}
for i in range(n):
text = input().split() #split the input text based on space & store in the list 'text'
d[text[0]] = text[1] #assign the 1st item to key and 2nd item to value of the dictionary
print(d)
INPUT:
3
A1023 CRT
A1029 Regulator
A1030 Therm
NOTE: I have added an extra line for each input for getting each input on individual lines on this site. As placing without an extra line creates a single line.
OUTPUT:
{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}
labelTV.setGravity(Gravity.CENTER | Gravity.BOTTOM);
Kotlin version (thanks to Thommy)
labelTV.gravity = Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM
Also, are you talking about gravity or about layout_gravity? The latter won't work in a RelativeLayout.
You can use @JsonIgnoreProperties at class level and put variables you want to igonre in json in "value" parameter.Worked for me fine.
@JsonIgnoreProperties(value = { "myVariable1","myVariable2" })
public class MyClass {
private int myVariable1;,
private int myVariable2;
}
It depends on what you mean:
As mentioned String.hashCode()
gives you a 32 bit hash code.
If you want (say) a 64-bit hashcode you can easily implement it yourself.
If you want a cryptographic hash of a String, the Java crypto libraries include implementations of MD5, SHA-1 and so on. You'll typically need to turn the String into a byte array, and then feed that to the hash generator / digest generator. For example, see @Bryan Kemp's answer.
If you want a guaranteed unique hash code, you are out of luck. Hashes and hash codes are non-unique.
A Java String of length N has 65536 ^ N
possible states, and requires an integer with 16 * N
bits to represent all possible values. If you write a hash function that produces integer with a smaller range (e.g. less than 16 * N
bits), you will eventually find cases where more than one String hashes to the same integer; i.e. the hash codes cannot be unique. This is called the Pigeonhole Principle, and there is a straight forward mathematical proof. (You can't fight math and win!)
But if "probably unique" with a very small chance of non-uniqueness is acceptable, then crypto hashes are a good answer. The math will tell you how big (i.e. how many bits) the hash has to be to achieve a given (low enough) probability of non-uniqueness.
Not is necesary destroy the chart. Try with this
function removeData(chart) {
let total = chart.data.labels.length;
while (total >= 0) {
chart.data.labels.pop();
chart.data.datasets[0].data.pop();
total--;
}
chart.update();
}
You could ignore SIGINTs after shutdown starts by calling signal.signal(signal.SIGINT, signal.SIG_IGN)
before you start your cleanup code.
By now, subscript(_:) is unavailable. As well as we can't do this
str[0]
with string.We have to provide "String.Index" But, how can we give our own index number in this way, instead we can use,
string[str.index(str.startIndex, offsetBy: 0)]
The memory must be configured in several places.
Set memory_limit
to 512M:
sudo vi /etc/php5/cgi/php.ini
sudo vi /etc/php5/cli/php.ini
sudo vi /etc/php5/apache2/php.ini Or /etc/php5/fpm/php.ini
Restart service:
sudo service service php5-fpm restart
sudo service service nginx restart
or
sudo service apache2 restart
Finally it should solve the problem of the memory_limit
just use this,
utf8_encode($string);
you've to replace your $arr
with $string
.
I think it will work...try this.
UltraID3Lib...
Be aware that UltraID3Lib is no longer officially available, and thus no longer maintained. See comments below for the link to a Github project that includes this library
//using HundredMilesSoftware.UltraID3Lib;
UltraID3 u = new UltraID3();
u.Read(@"C:\mp3\song.mp3");
//view
Console.WriteLine(u.Artist);
//edit
u.Artist = "New Artist";
u.Write();
You can also manually tag the column with a contrasts
attribute, which seems to be respected by the regression functions:
contrasts(df$factorcol) <- contr.treatment(levels(df$factorcol),
base=which(levels(df$factorcol) == 'RefLevel'))
Building on the answer from @fzzle - to achieve a circle from a rectangle without defining a fixed height or width, the following will work. The padding-top:100% keeps a 1:1 ratio for the circle-cropper div. Set an inline background image, center it, and use background-size:cover to hide any excess.
CSS
.circle-cropper {
background-repeat: no-repeat;
background-size: cover;
background-position: 50%;
border-radius: 50%;
width: 100%;
padding-top: 100%;
}
HTML
<div class="circle-cropper" role="img" style="background-image:url(myrectangle.jpg);"></div>
Try updating your buildToolVersion
to 27.0.2
instead of 27.0.3
The error probably occurring because of compatibility issue with build tools
Just for the reference, if you work in scripts (batch processing), not in stored procedure, flushing output is triggered by the GO command, e.g.
print 'test'
print 'test'
go
In general, my conclusion is following: output of mssql script execution, executing in SMS GUI or with sqlcmd.exe, is flushed to file, stdoutput, gui window on first GO statement or until the end of the script.
Flushing inside of stored procedure functions differently, since you can not place GO inside.
Reference: tsql Go statement
npm has a few packages, but none have reached 1.0 yet. Best picks from npm list mail
:
[email protected]
[email protected]
[email protected]
Using Process.Start:
using System.Diagnostics;
class Program
{
static void Main()
{
Process.Start("example.txt");
}
}
Edit: I'm using angular ^4.0.0 and Electron ^1.4.3
If you have issues with ElectronJS or similar and have a sort of 404 error, a possible workaround is to uedit your webpack.config.js
, by adding (and by assuming that you have the font-awesome node module installed through npm or in the package.json file):
new CopyWebpackPlugin([
{ from: 'node_modules/font-awesome/fonts', to: 'assets' },
{ from: 'src/assets', to: 'assets' }
]),
Note that the webpack configuration I'm using has src/app/dist
as output, and, in dist, an assets
folder is created by webpack:
// our angular app
entry: {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/app/app',
},
// Config for our build files
output: {
path: helpers.root('src/app/dist'),
filename: '[name].js',
sourceMapFilename: '[name].map',
chunkFilename: '[id].chunk.js'
},
So basically, what is currently happening is:
dist
assets folderNow, when the build process will be finished, the application will need to look for the .scss
file and the folder containing the icons, resolving them properly.
To resolve them, I've used this in my webpack config:
// support for fonts
{
test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
loader: 'file-loader?name=dist/[name]-[hash].[ext]'
},
Finally, in the .scss
file, I'm importing the font-awesome .scss and defining the path of the fonts, which is, again, dist/assets/font-awesome/fonts
. The path is dist
because in my webpack.config the output.path is set as helpers.root('src/app/dist');
So, in app.scss
:
$fa-font-path: "dist/assets/font-awesome/fonts";
@import "~font-awesome/scss/font-awesome.scss";
Note that, in this way, it will define the font path (used later in the .scss file) and import the .scss file using ~font-awesome
to resolve the font-awesome path in node_modules
.
This is quite tricky, but it's the only way I've found to get around the 404 error issue with Electron.js
I think a much easier way is to use ASIHTTPRequest. Three lines of code can accomplish this:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:@"/path/to/my_file.txt"];
[request startSynchronous];
UPDATE: I should mention that ASIHTTPRequest is no longer maintained. The author has specifically advised people to use other framework instead, like AFNetworking
In MySQL itself, you can specify CSV output like:
SELECT order_id,product_name,qty
FROM orders
INTO OUTFILE '/tmp/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
From http://www.tech-recipes.com/rx/1475/save-mysql-query-results-into-a-text-or-csv-file/
Finlay, I have faced same issue in my application. I have developed Phone Gap app for
android:minSdkVersion="7" & android:targetSdkVersion="18"
which is recent version of android platform.
I have found the issue using Google Docs
May be issue is that i have write some JS function which works on KEY-CODE
to validate only Alphabets & Number but key board has different key code specially for computer keyboard & Mobile keyboard. So that was my issue.
I am not sure whether my answer is correct or not and it might be possible that it could be smiler to above answer but i will try to list out some points which should be care while we are building the app.I hope you follow this to solve this kind of issue.
Use the android:minSdkVersion="?"
as per your requirement & android:targetSdkVersion="?"
should be latest in which your app will targeting. see more
Try to add only those permission which will be use in your application and remove all which are unnecessary .
Check out the supported screen by application
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:resizeable="true"
android:smallScreens="true"
android:xlargeScreens="true"/>
May be you have implement some costume code or costume widget which couldn't able to run in some device or tab late so before writing the long code first try to write some beta code and test it whether your code will run in all device or not.
And I hope Google will publish a tool which can validate your code before the upload the app and also says that due to some specific reason we are not allow to run your app in some device so we can easily solve it.
Liviu's answer was extremely helpful for me. Hope this is not bad form but i made a fiddle that may help someone else out in the future.
Two important pieces that are needed are:
$scope.entities = [{
"title": "foo",
"id": 1
}, {
"title": "bar",
"id": 2
}, {
"title": "baz",
"id": 3
}];
$scope.selected = [];
Think about what you need to do if you wish to implement:
The order is WHERE, GROUP BY and HAVING.
After uninstalling too much on my Win7-64bit machine I was stuck here too. I didn't want to reinstall the OS and none of the tricks worked expect for this registry hack below. Most of this trick I found in an old pchelpforum port but I had to adapt it to my 64-bit installation:
(For a 32-bit repair, probably skip the Wow6432Node path)
Now right click in the empty window on the right and add this data (there will probably be at least a Default string value located here, just leave it):
New->Binary Value
Name: InstalledVersion
Type: REG_BINARY
Data: 00 00 00 09 00 00 00 00
New->DWORD (32-bit) Value
Name: InstallMDX
Type: REG_DWORD
Data: 0x00000001
New->String Value
Name: SDKVersion
Type: REG_SZ
Data: 9.26.1590.0
New->String Value
Name: Version
Type: REG_SZ
Data: 4.09.00.0904
Reinstall using latest DXSDK installer. Runtime only option may work too but I didn't test it.
In Code behind you can achieve it only by doing this.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
txtIndex.Focusable = true;
txtIndex.Focus();
}
Note: It wont work before window is loaded
For bootstrap 4, to expand on @helloroy's answer I used the following;-
var modal_lv = 0 ;
$('body').on('shown.bs.modal', function(e) {
if ( modal_lv > 0 )
{
$('.modal-backdrop:last').css('zIndex',1050+modal_lv) ;
$(e.target).css('zIndex',1051+modal_lv) ;
}
modal_lv++ ;
}).on('hidden.bs.modal', function() {
if ( modal_lv > 0 )
modal_lv-- ;
});
The advantage of the above is that it won't have any effect when there is only one modal, it only kicks in for multiples. Secondly, it delegates the handling to the body to ensure future modals which are not currently generated are still catered for.
Update
Moving to a js/css combined solution improves the look - the fade animation continues to work on the backdrop;-
var modal_lv = 0 ;
$('body').on('show.bs.modal', function(e) {
if ( modal_lv > 0 )
$(e.target).css('zIndex',1051+modal_lv) ;
modal_lv++ ;
}).on('hidden.bs.modal', function() {
if ( modal_lv > 0 )
modal_lv-- ;
});
combined with the following css;-
.modal-backdrop ~ .modal-backdrop
{
z-index : 1051 ;
}
.modal-backdrop ~ .modal-backdrop ~ .modal-backdrop
{
z-index : 1052 ;
}
.modal-backdrop ~ .modal-backdrop ~ .modal-backdrop ~ .modal-backdrop
{
z-index : 1053 ;
}
This will handle modals nested up to 4 deep which is more than I need.
For my fellow Googlers out there, here's a very simple plug-and-play solution that worked for me after struggling with the more complex solutions for a while:
SELECT
distinct empName,
NewColumnName=STUFF((SELECT ','+ CONVERT(VARCHAR(10), projID )
FROM returns
WHERE empName=t.empName FOR XML PATH('')) , 1 , 1 , '' )
FROM
returns t
Notice that I had to convert the ID into a VARCHAR in order to concatenate it as a string. If you don't have to do that, here's an even simpler version:
SELECT
distinct empName,
NewColumnName=STUFF((SELECT ','+ projID
FROM returns
WHERE empName=t.empName FOR XML PATH('')) , 1 , 1 , '' )
FROM
returns t
All credit for this goes to here: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/9508abc2-46e7-4186-b57f-7f368374e084/replicating-groupconcat-function-of-mysql-in-sql-server?forum=transactsql
Let's not forget the switch statement, where colon is used after each "case".
I think this is all a matter of convenience/preference.
I prefer double quote because it matches what C# has and this is my environment that I normally work in: C# + JavaScript.
Also one possible reason for double quotes over single quotes is this (which I have found in my projects code): French or some other languages use single quotes a lot (like English actually), so if by some reason you end up rendering strings from the server side (which I know is bad practice), then a single quote will render wrongly.
The probability of using double quotes in a regular language is low, and therefore I think it has a better chance of not breaking something.
Also check any jar files in your project that have been compiled for a higher version of Java. If these are your own libraries, you can fix this by changing the target version attribute to javac
<javac destdir="${classes.dir}"
debug="on" classpathref="project.classpath" target="1.6">
Add the following line on the top of your file
require 'json'
Then you can use:
car = {:make => "bmw", :year => "2003"}
car.to_json
Alternatively, you can use:
JSON.generate({:make => "bmw", :year => "2003"})
https://github.com/dualface/cocos2d-x-extensions/blob/master/TODO.tasks , he is developing nice features on cocos2d-x
The primary key class must define equals and hashCode methods
Subscript out of Range error occurs when you try to reference an Index for a collection that is invalid.
Most likely, the index in Windows does not actually include .xls. The index for the window should be the same as the name of the workbook displayed in the title bar of Excel.
As a guess, I would try using this:
Windows("Data Sheet - " & ComboBox_Month.Value & " " & TextBox_Year.Value).Activate
Define the query method with signatures as follows.
@Query(select p from Person p where p.forename = :forename and p.surname = :surname)
User findByForenameAndSurname(@Param("surname") String lastname,
@Param("forename") String firstname);
}
For further details, check the Spring Data JPA reference
It does work by just taking the argument 'rb' read binary instead of 'r' read
Try to use this with single quotes in data:
insert into table test_hive values ('1','puneet');
you can also try
git show <filename>
For commits, git show will show the log message and textual diff (between your file and the commited version of the file).
You can check git show Documentation for more info.
Try any of these
valof = moment().valueOf(); // xxxxxxxxxxxxx
getTime = moment().toDate().getTime(); // xxxxxxxxxxxxx
unixTime = moment().unix(); // xxxxxxxxxx
formatTimex = moment().format('x'); // xxxxxxxxxx
unixFormatX = moment().format('X'); // xxxxxxxxxx
This article explains in detail how to find the reason for last startup/shutdown. In my case, this was due to windows SCCM pushing updates even though I had it disabled locally. Visit the article for full details with pictures. For reference, here are the steps copy/pasted from the website:
Press the Windows + R keys to open the Run dialog, type
eventvwr.msc
, and press Enter.If prompted by UAC, then click/tap on Yes (Windows 7/8) or Continue (Vista).
In the left pane of Event Viewer, double click/tap on Windows Logs to expand it, click on System to select it, then right click on System, and click/tap on Filter Current Log.
Do either step 5 or 6 below for what shutdown events you would like to see.
To See the Dates and Times of All User Shut Downs of the Computer
A) In Event sources, click/tap on the drop down arrow and check the
USER32
box.B) In the All Event IDs field, type
1074
, then click/tap on OK.C) This will give you a list of power off (shutdown) and restart Shutdown Type of events at the top of the middle pane in Event Viewer.
D) You can scroll through these listed events to find the events with power off as the Shutdown Type. You will notice the date and time, and what user was responsible for shutting down the computer per power off event listed.
E) Go to step 7.
To See the Dates and Times of All Unexpected Shut Downs of the Computer
A) In the All Event IDs field, type
6008
, then click/tap on OK.B) This will give you a list of unexpected shutdown events at the top of the middle pane in Event Viewer. You can scroll through these listed events to see the date and time of each one.
The user
parameter of your callback is an array with find
. Use findOne
instead of find
when querying for a single instance.
User.findOne({username: oldUsername}, function (err, user) {
user.username = newUser.username;
user.password = newUser.password;
user.rights = newUser.rights;
user.save(function (err) {
if(err) {
console.error('ERROR!');
}
});
});
I just updated AngularJs to 1.1.2 and have no problem with it. I guess this bug was fixed.
http://ci.angularjs.org/job/angular.js-pete/57/artifact/build/angular.js
If you need a function try this.
First we'll create a type:
CREATE OR REPLACE TYPE T_TABLE IS OBJECT
(
Field1 int
, Field2 VARCHAR(25)
);
CREATE TYPE T_TABLE_COLL IS TABLE OF T_TABLE;
/
Then we'll create the function:
CREATE OR REPLACE FUNCTION TEST_RETURN_TABLE
RETURN T_TABLE_COLL
IS
l_res_coll T_TABLE_COLL;
l_index number;
BEGIN
l_res_coll := T_TABLE_COLL();
FOR i IN (
WITH TAB AS
(SELECT '1001' ID, 'A,B,C,D,E,F' STR FROM DUAL
UNION
SELECT '1002' ID, 'D,E,F' STR FROM DUAL
UNION
SELECT '1003' ID, 'C,E,G' STR FROM DUAL
)
SELECT id,
SUBSTR(STR, instr(STR, ',', 1, lvl) + 1, instr(STR, ',', 1, lvl + 1) - instr(STR, ',', 1, lvl) - 1) name
FROM
( SELECT ',' || STR || ',' AS STR, id FROM TAB
),
( SELECT level AS lvl FROM dual CONNECT BY level <= 100
)
WHERE lvl <= LENGTH(STR) - LENGTH(REPLACE(STR, ',')) - 1
ORDER BY ID, NAME)
LOOP
IF i.ID = 1001 THEN
l_res_coll.extend;
l_index := l_res_coll.count;
l_res_coll(l_index):= T_TABLE(i.ID, i.name);
END IF;
END LOOP;
RETURN l_res_coll;
END;
/
Now we can select from it:
select * from table(TEST_RETURN_TABLE());
Output:
SQL> select * from table(TEST_RETURN_TABLE());
FIELD1 FIELD2
---------- -------------------------
1001 A
1001 B
1001 C
1001 D
1001 E
1001 F
6 rows selected.
Obviously you'd need to replace the WITH TAB AS...
bit with where you would be getting your actual data from.
Credit Credit
If you are refering to res strings, use CDATA with \n.
<string name="about">
<![CDATA[
Author: Sergio Abreu\n
http://sites.sitesbr.net
]]>
</string>
The following enables all errors:
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
Also see the following links
This is how I accomplished reading a table in javascript. Basically I drilled down into the rows and then I was able to drill down into the individual cells for each row. This should give you an idea
//gets table
var oTable = document.getElementById('myTable');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++){
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
//gets amount of cells of current row
var cellLength = oCells.length;
//loops through each cell in current row
for(var j = 0; j < cellLength; j++){
/* get your cell info here */
/* var cellVal = oCells.item(j).innerHTML; */
}
}
UPDATED - TESTED SCRIPT
<table id="myTable">
<tr>
<td>A1</td>
<td>A2</td>
<td>A3</td>
</tr>
<tr>
<td>B1</td>
<td>B2</td>
<td>B3</td>
</tr>
</table>
<script>
//gets table
var oTable = document.getElementById('myTable');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++){
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
//gets amount of cells of current row
var cellLength = oCells.length;
//loops through each cell in current row
for(var j = 0; j < cellLength; j++){
// get your cell info here
var cellVal = oCells.item(j).innerHTML;
alert(cellVal);
}
}
</script>
The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.
For example:
var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}
//that will not work.
delete myObj.test.keyToDelete
instead you would need to use:
delete myObj.test[keyToDelete];
Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.
//in linux
// in your home folder .android hidden folder is there go to that there you can find the avd folder open that and check your avd name that you created open that and you can see the sdcard.img
that is your sdcard file.
//To install apk in linux
$adb install ./yourfolder/myapkfile.apk
FluentSharp has the lowerCaseFirstLetter
method which does this
In Socket.IO 0.7 you have a clients
method on the namespaces, this returns a array of all connected sockets.
API for no namespace:
var clients = io.sockets.clients();
var clients = io.sockets.clients('room'); // all users from room `room`
For a namespace
var clients = io.of('/chat').clients();
var clients = io.of('/chat').clients('room'); // all users from room `room`
Hopes this helps someone in the future
NOTE: This Solution ONLY works with version prior to 1.0
UPDATED 2020 Mar 06
From 1.x and above, please refer to this link: getting how many people are in a chat room in socket.io
Since we have a virtual address space of 2^32 and each page size is 2^12, we can store (2^32/2^12) = 2^20 pages. Since each entry into this page table has an address of size 4 bytes, then we have 2^20*4 = 4MB. So the page table takes up 4MB in memory.
Simply add an attribute to your popover! See my JSFiddle if you're in a hurry.
We want to add an ID or a class to a particular popover so that we may customize it the way we want via CSS.
Please note that we don't want to customize all popovers! This is terrible idea.
Here is a simple example - display the popover like this:
// We add the id 'my-popover'_x000D_
$("#my-button").popover({_x000D_
html : true,_x000D_
placement: 'bottom'_x000D_
}).data('bs.popover').tip().attr('id', 'my-popover');
_x000D_
#my-popover {_x000D_
left: -169px!important;_x000D_
}_x000D_
#my-popover .arrow {_x000D_
left: 90%_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
<button id="my-button" data-toggle="popover">My Button</button>
_x000D_
better use quoted `data`
and `date`
. AFAIR these may be reserved words
my version is:
INSERT INTO `table` ( `data` , `date` ) VALUES('".$date."',NOW()+INTERVAL 1 DAY);
Set autoindex option to on
. It is off by default.
Your configuration file ( vi /etc/nginx/sites-available/default
) should be like this
location /{
... ( some other lines )
autoindex on;
... ( some other lines )
}
Set autoindex option to on
. It is off by default.
Your configuration file ( vi /etc/nginx/sites-available/default
)
should be like this.
change path_of_your_directory
to your directory path
location /path_of_your_directory{
... ( some other lines )
autoindex on;
... ( some other lines )
}
Hope it helps..
To scrolldown from any position in the recyclerview to bottom
edittext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
rv.postDelayed(new Runnable() {
@Override
public void run() {
rv.scrollToPosition(rv.getAdapter().getItemCount() - 1);
}
}, 1000);
}
});
Try setting the checkbox's opacity to 0. If you want the checkbox to be out of flow try position:absolute
and offset the checkbox by a large number.
HTML
<label class="checkbox"><input type="checkbox" value="valueofcheckbox" checked="checked" style="opacity:0; position:absolute; left:9999px;">Option Text</label>
The following was rejected as an edit to tvanfosson's answer. I was asked to contribute it as my own answer. I used his suggestion and finished the implementation of a ConfigurationManager
wrapper. In principle I simply filled out the ...
in tvanfosson's answer.
No. Extension methods require an instance of an object. You can however, write a static wrapper around the ConfigurationManager interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.
public static class ConfigurationManagerWrapper
{
public static NameValueCollection AppSettings
{
get { return ConfigurationManager.AppSettings; }
}
public static ConnectionStringSettingsCollection ConnectionStrings
{
get { return ConfigurationManager.ConnectionStrings; }
}
public static object GetSection(string sectionName)
{
return ConfigurationManager.GetSection(sectionName);
}
public static Configuration OpenExeConfiguration(string exePath)
{
return ConfigurationManager.OpenExeConfiguration(exePath);
}
public static Configuration OpenMachineConfiguration()
{
return ConfigurationManager.OpenMachineConfiguration();
}
public static Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel)
{
return ConfigurationManager.OpenMappedExeConfiguration(fileMap, userLevel);
}
public static Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap)
{
return ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
}
public static void RefreshSection(string sectionName)
{
ConfigurationManager.RefreshSection(sectionName);
}
}
You don't need a CTE for this
UPDATE PEDI_InvoiceDetail
SET
DocTotal = v.DocTotal
FROM
PEDI_InvoiceDetail
inner join
(
SELECT InvoiceNumber, SUM(Sale + VAT) AS DocTotal
FROM PEDI_InvoiceDetail
GROUP BY InvoiceNumber
) v
ON PEDI_InvoiceDetail.InvoiceNumber = v.InvoiceNumber
lookup only works on localhost. If you want to retrieve variables from a variables file you made remotely use include_vars: {{ varfile }}
. Contents of {{ varfile }}
should be a dictionary of the form {"key":"value"}
, you will find ansible gives you trouble if you include a space after the colon.
From Wikipedia:
In computer programming, boilerplate is the term used to describe sections of code that have to be included in many places with little or no alteration. It is more often used when referring to languages that are considered verbose, i.e. the programmer must write a lot of code to do minimal jobs.
So basically you can consider boilerplate code as a text that is needed by a programming language very often all around the programs you write in that language.
Modern languages are trying to reduce it, but also the older language which has specific type-checkers (for example OCaml has a type-inferrer that allows you to avoid so many declarations that would be boilerplate code in a more verbose language like Java)
UUID schemes generally use not only a pseudo-random element, but also the current system time, and some sort of often-unique hardware ID if available, such as a network MAC address.
The whole point of using UUID is that you trust it to do a better job of providing a unique ID than you yourself would be able to do. This is the same rationale behind using a 3rd party cryptography library rather than rolling your own. Doing it yourself may be more fun, but it's typically less responsible to do so.
Current responses are great but a more comprehensive answer is needed for beginners. There are 3 different ways to start a new activity in Android, and they all use the Intent
class; Intent | Android Developers.
onClick
attribute of the Button. (Beginner)OnClickListener()
via an anonymous class. (Intermediate) switch
statement. (Pro)Here's the link to my example if you want to follow along:
onClick
attribute of the Button. (Beginner)Buttons have an onClick
attribute that is found within the .xml file:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="goToAnActivity"
android:text="to an activity" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="goToAnotherActivity"
android:text="to another activity" />
In Java class:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
public void goToAnActivity(View view) {
Intent intent = new Intent(this, AnActivity.class);
startActivity(intent);
}
public void goToAnotherActivity(View view) {
Intent intent = new Intent(this, AnotherActivity.class);
startActivity(intent);
}
Advantage: Easy to make on the fly, modular, and can easily set multiple onClick
s to the same intent.
Disadvantage: Difficult readability when reviewing.
OnClickListener()
via an anonymous class. (Intermediate)This is when you set a separate setOnClickListener()
to each button
and override each onClick()
with its own intent.
In Java class:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), AnActivity.class);
view.getContext().startActivity(intent);}
});
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), AnotherActivity.class);
view.getContext().startActivity(intent);}
});
Advantage: Easy to make on the fly.
Disadvantage: There will be a lot of anonymous classes which will make readability difficult when reviewing.
switch
statement. (Pro)This is when you use a switch
statement for your buttons within the onClick()
method to manage all the Activity's buttons.
In Java class:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button1:
Intent intent1 = new Intent(this, AnActivity.class);
startActivity(intent1);
break;
case R.id.button2:
Intent intent2 = new Intent(this, AnotherActivity.class);
startActivity(intent2);
break;
default:
break;
}
Advantage: Easy button management because all button intents are registered in a single onClick()
method
For the second part of the question, passing data, please see How do I pass data between Activities in Android application?
array = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
col1 = [val[1] for val in array]
col2 = [val[2] for val in array]
col3 = [val[3] for val in array]
col4 = [val[4] for val in array]
print(col1)
print(col2)
print(col3)
print(col4)
Output:
[1, 5, 9, 13]
[2, 6, 10, 14]
[3, 7, 11, 15]
[4, 8, 12, 16]
The error message fatal: Unable to write new index file
means that we could not write the new content to the git index file .git\index
(See here for more information about git index). After reviewing all the answers to this question, I summarize the following root causes:
.git\index
is locked by other users or processes. (Solution: Unlock the file)The link Find out which process is locking a file or folder in Windows specifies the following approach to find out the process which is locking a specific file:
SysInternals Process Explorer - Go to Find > Find Handle or DLL. In the "Handle or DLL substring:" text box, type the path to the file (e.g. "C:\path\to\file.txt") and click "Search". All processes which have an open handle to that file should be listed.
Use the above approach to find which process locked .git\index
and then stop the locking executable. This unlocks .git\index
.
For example, Process Explorer Search shows that .git\index
is locked by vmware-vmx.exe
. Suspending the VMWare Player virtual machine (which accessed the git repo via a shared folder) solved the issue.
<input type="date" id="myDate" />
Then in js :
_today: function () {
var myDate = document.querySelector(myDate);
var today = new Date();
myDate.value = today.toISOString().substr(0, 10);
},
string::c.str()
returns a string of type const char *
as seen here
A quick fix: try casting printfunc(num,addr,(char *)data.str().c_str())
;
While the above may work, it is undefined behaviour, and unsafe.
Here's a nicer solution using templates:
char * my_argument = const_cast<char*> ( ...c_str() );
display
syntax instead, for clarityThe display
CSS property in fact sets two things at once: the outer display type, and the inner display type. The outer display type affects how the element (which acts as a container) is displayed in its context. The inner display type affects how the children of the element (or the children of the container) are laid out.
If you use the two-value display
syntax, which is only supported in some browsers like Firefox, the difference between the two is much more obvious:
display: block
is equivalent to display: block flow
display: inline
is equivalent to display: inline flow
display: flex
is equivalent to display: block flex
display: inline-flex
is equivalent to display: inline flex
display: grid
is equivalent to display: block grid
display: inline-grid
is equivalent to display: inline grid
block
or inline
:An element with the outer display type of block
will take up the whole width available to it, like <div>
does. An element with the outer display type of inline
will only take up the width that it needs, with wrapping, like <span>
does.
flow
, flex
or grid
:The inner display type flow
is the default inner display type when flex
or grid
is not specified. It is the way of laying out children elements that we are used to in a <p>
for instance. flex
and grid
are new ways of laying out children that each deserve their own post.
The difference between display: flex
and display: inline-flex
is the outer display type, the first's outer display type is block
, and the second's outer display type is inline
. Both of them have the inner display type of flex
.
Get "adbd insecure" from google play store, it helps give write access to custom roms that have it secured my the manufacturers.
I had this problem when I try to write a very long url, the following works.
image_url = %w(
http://minio.127.0.0.1.xip.io:9000/
bucket29/docs/b7cfab0e-0119-452c-b262-1b78e3fccf38/
28ed3774-b234-4de2-9a11-7d657707f79c?
X-Amz-Algorithm=AWS4-HMAC-SHA256&
X-Amz-Credential=ABABABABABABABABA
%2Fus-east-1%2Fs3%2Faws4_request&
X-Amz-Date=20170702T000940Z&
X-Amz-Expires=3600&X-Amz-SignedHeaders=host&
X-Amz-Signature=ABABABABABABABABABABAB
ABABABABABABABABABABABABABABABABABABA
).join
Note, there must not be any newlines, white spaces when the url string is formed. If you want newlines, then use HEREDOC.
Here you have indentation for readability, ease of modification, without the fiddly quotes and backslashes on every line. The cost of joining the strings should be negligible.
In my case, two leading '\\' working fine for me.
For example : if your word contains the '#' character (e.g. aa#100, you can escape it with two leading '\\'
key= aa\\#100
_x000D_
As an alternative:
If you have a table with schema
CREATE TABLE person(
id INTEGER PRIMARY KEY,
first_name TEXT,
last_name TEXT,
age INTEGER,
height INTEGER
);
you can use a CREATE TABLE...AS
statement like CREATE TABLE person2 AS SELECT id, first_name, last_name, age FROM person;
, i.e. leave out the columns you don't want. Then drop the original person
table and rename the new one.
Note this method produces a table has no PRIMARY KEY and no constraints. To preserve those, utilize the methods others described to create a new table, or use a temporary table as an intermediate.
Let me to recommend you a jQuery plugin for nice modal alers. It doesn't requires jquery UI.
Demo: http://www.webmasters.by/images/articles/jquery.alerts/index.html
As I recall, the only portable way to do it, is to cast the result to "unsigned long int" and use %lu
.
printf("sizeof(int) = %lu", (unsigned long) sizeof(int));
An O(n) way would be as below:
List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 4, 4);
Set<Integer> duplicatedNumbersRemovedSet = new HashSet<>();
Set<Integer> duplicatedNumbersSet = numbers.stream().filter(n -> !duplicatedNumbersRemovedSet.add(n)).collect(Collectors.toSet());
The space complexity would go double in this approach, but that space is not a waste; in-fact, we now have the duplicated alone only as a Set as well as another Set with all the duplicates removed too.
Yes, it is universal.
Although '\n'
is the universal newline characters, you have to keep in mind that, depending on your input, new line characters might be preceded by carriage return characters ('\r'
).
Here is code for Multiple Client to one Server Working Fine .. Give it a try :)
Server.java:
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
class Multi extends Thread{
private Socket s=null;
DataInputStream infromClient;
Multi() throws IOException{
}
Multi(Socket s) throws IOException{
this.s=s;
infromClient = new DataInputStream(s.getInputStream());
}
public void run(){
String SQL=new String();
try {
SQL = infromClient.readUTF();
} catch (IOException ex) {
Logger.getLogger(Multi.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Query: " + SQL);
try {
System.out.println("Socket Closing");
s.close();
} catch (IOException ex) {
Logger.getLogger(Multi.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class Server {
public static void main(String args[]) throws IOException,
InterruptedException{
while(true){
ServerSocket ss=new ServerSocket(11111);
System.out.println("Server is Awaiting");
Socket s=ss.accept();
Multi t=new Multi(s);
t.start();
Thread.sleep(2000);
ss.close();
}
}
}
Client1.java:
import java.io.DataOutputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
public class client1 {
public static void main(String[] arg) {
try {
Socket socketConnection = new Socket("127.0.0.1", 11111);
//QUERY PASSING
DataOutputStream outToServer = new DataOutputStream(socketConnection.getOutputStream());
String SQL="I am client 1";
outToServer.writeUTF(SQL);
} catch (Exception e) {System.out.println(e); }
}
}
Client2.java
import java.io.DataOutputStream;
import java.net.Socket;
public class client2 {
public static void main(String[] arg) {
try {
Socket socketConnection = new Socket("127.0.0.1", 11111);
//QUERY PASSING
DataOutputStream outToServer = new DataOutputStream(socketConnection.getOutputStream());
String SQL="I am Client 2";
outToServer.writeUTF(SQL);
} catch (Exception e) {System.out.println(e); }
}
}
There are two approaches:
Using aliases; in this method you give new unique names (ALIAS) to the various columns and then use them in the PHP retrieval. e.g.
SELECT student_id AS FEES_LINK, student_class AS CLASS_LINK
FROM students_fee_tbl
LEFT JOIN student_class_tbl ON students_fee_tbl.student_id = student_class_tbl.student_id
and then fetch the results in PHP:
$query = $PDO_stmt->fetchAll();
foreach($query as $q) {
echo $q['FEES_LINK'];
}
Using place position or resultset column index; in this, the array positions are used to reference the duplicated column names. Since they appear at different positions, the index numbers that will be used is always unique. However, the index positioning numbers begins at 0. e.g.
SELECT student_id, student_class
FROM students_fee_tbl
LEFT JOIN student_class_tbl ON students_fee_tbl.student_id = student_class_tbl.student_id
and then fetch the results in PHP:
$query = $PDO_stmt->fetchAll();
foreach($query as $q) {
echo $q[0];
}
You can use +
if you know all the values are strings. Jinja also provides the ~
operator, which will ensure all values are converted to string first.
{% set my_string = my_string ~ stuff ~ ', '%}
file_name=test.log
# set first K lines:
K=1000
# line count (N):
N=$(wc -l < $file_name)
# length of the bottom file:
L=$(( $N - $K ))
# create the top of file:
head -n $K $file_name > top_$file_name
# create bottom of file:
tail -n $L $file_name > bottom_$file_name
Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so
split -l 300000 file_name
will output xaa
with 300k lines and xab
with 100k lines, for an input with 400k lines.
I don't know how my solution compares performance wise to previous answers.
I understand that the initial question was: What is the fastest way to get min and max values in a DataTable object, this may be one way of doing it:
DataView view = table.DefaultView;
view.Sort = "AccountLevel";
DataTable sortedTable = view.ToTable();
int min = sortedTable.Rows[0].Field<int>("AccountLevel");
int max = sortedTable.Rows[sortedTable.Rows.Count-1].Field<int>("AccountLevel");
It's an easy way of achieving the same result without looping. But performance will need to be compared with previous answers. Thought I love Cylon Cats answer most.
My fix for getting SVN commands was to copy .exe and .dll files from the TortoiseSVN directory and pasting them into system32 folder.
You could also perform the command from the TortoiseSVN directory and add the path of the working directory to each command. For example:
C:\Program Files\TortoiseSVN\bin> svn st -v C:\checkout
Adding the bin to the path should make it work without duplicating the files, but it didn't work for me.
I used something like this to type only values in my SQL request. There are too much columns in my case, and im lazy.
insert into my_table select max(id)+1, valueA, valueB, valueC.... from my_table;
To do that you need to leverage the "Collections" feature of Postman. This link could help you: https://learning.getpostman.com/docs/postman/collections/creating_collections/
Here is the way to do it:
Yes, this happens when manipulating an element which doesn't exist yet (a few contributors here also made a good point with the unique ID). I ran into a similar issue. I also need to pass an argument to the function manipulating the element soon to be rendered.
The solution checked off here didn't help me. Finally I found one that worked right out of the box. And it's very pretty, too - a callback.
Instead of:
$( '#header' ).focus();
or the tempting:
setTimeout( $( '#header' ).focus(), 500 );
Try this:
setTimeout( function() { $( '#header' ).focus() }, 500 );
In my code, testing passing the argument, this didn't work, the timeout was ignored:
setTimeout( alert( 'Hello, '+name ), 1000 );
This works, the timeout ticks:
setTimeout( function() { alert( 'Hello, '+name ) }, 1000 );
It sucks that w3schools doesn't mention it.
Credits go to: makemineatriple.com.
Hopefully, this helps somebody who comes here.
Maybe you can try to add android:layout_marginTop = "15dp" and android:layout_marginBottom = "15dp" in the outermost Layout
You can also use the sc
tool to set it.
You can also call it from PowerShell and add additional checks if needed.
The advantage of this tool vs. PowerShell is that the sc
tool can also set the start type to auto delayed.
# Get Service status
$Service = "Wecsvc"
sc.exe qc $Service
# Set Service status
$Service = "Wecsvc"
sc.exe config $Service start= delayed-auto
You can use the Pattern
class for this. If you want to match only word characters inside the {}
then you can use the following regex. \w
is a shorthand for [a-zA-Z0-9_]
. If you are ok with _
then use \w
or else use [a-zA-Z0-9]
.
String URL = "https://localhost:8080/sbs/01.00/sip/dreamworks/v/01.00/cui/print/$fwVer/{$fwVer}/$lang/en/$model/{$model}/$region/us/$imageBg/{$imageBg}/$imageH/{$imageH}/$imageSz/{$imageSz}/$imageW/{$imageW}/movie/Kung_Fu_Panda_two/categories/3D_Pix/item/{item}/_back/2?$uniqueID={$uniqueID}";
Pattern pattern = Pattern.compile("/\\{\\w+\\}/");
Matcher matcher = pattern.matcher(URL);
if (matcher.find()) {
System.out.println(matcher.group(0)); //prints /{item}/
} else {
System.out.println("Match not found");
}
Try using jQuery
<script type="text/javascript">
$("form").submit(function() {
$("form").attr('target', '_blank');
return true;
});
</script>
Here is a full answer - http://ftutorials.com/open-html-form-in-new-tab/
firstly I don't think there is just one solution to your problem....
As you know each browser is vastly differant.
But lets see if we can get any closer to the answer you need....
I think IE Might be easy...
Check this link http://support.microsoft.com/kb/181050
For Firefox try this:
Open Firefox, and in the address bar, type "about:config" (without quotes). From there, scroll down to the Network.http.keep-alive and make sure that is set to "true". If it is not, double click it, and it will go from false to true. Now, go one below that to network.http.keep-alive.timeout -- and change that number by double clicking it. if you put in, say, 500 there, you should be good. let us know if this helps at all
Begin by installing this package through Composer. Run the following from the terminal:
composer require "laravelcollective/html":"^5.3.0"
Next, add your new provider to the providers array of config/app.php:
'providers' => [
// ...
Collective\Html\HtmlServiceProvider::class,
// ...
],
Finally, add two class aliases to the aliases array of config/app.php:
'aliases' => [
// ...
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
// ...
],
SRC:
The details in the comments section above did not work for me (VS 2013) when trying to copy the output dll from one C++ project to the release and debug folder of another C# project within the same solution.
I had to add the following post build-action (right click on the project that has a .dll output) then properties -> configuration properties -> build events -> post-build event -> command line
now I added these two lines to copy the output dll into the two folders:
xcopy /y $(TargetPath) $(SolutionDir)aeiscontroller\bin\Release
xcopy /y $(TargetPath) $(SolutionDir)aeiscontroller\bin\Debug
I'm a beginner in Android, but got it working like this:
in AndroidManifest.xml, make sure you, inside <application>
, have something like this:
<service android:name="com.some.package.name.YourServiceSubClassName" android:permission="com.some.package.name.YourServiceSubClassName">
<intent-filter>
<action android:name="com.some.package.name.YourServiceSubClassName"/>
</intent-filter>
</service>
where YourServiceSubClassName
extend android.app.Service
is your java class that is the service. Where com.some.package
is the package name, for me both in AndroidManifest.xml and in Java.
Used a javabeat.net article as help, look for <service>
Note also, supposedly between the package name and the class name there should be .service.
in the text, I guess this is some convention, but for me this caused ClassNotFoundException
that I'm yet to solve.
Then, install your apk. I did from eclipse but also adb install -r yourApkHere.apk
should work. Uninstall is adb uninstall com.some.package.name
, btw.
You can start it from host system like this, thanks Just a Tim and MrRoy:
adb shell am startservice com.some.package.name/.YourServiceSubClassName
interestingly, I didn't need -n
.
To stop, I use
adb shell am force-stop com.some.package.name
Hope it helps.
As I'm a beginner, please feel freet to edit/comment to fix any misconceptions (eg. probably regarding .service.
in the component (?) name).
checkout the example here
style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
The calls that you need to make against Nexus are REST api calls.
The maven-nexus-plugin is a Maven plugin that you can use to make these calls. You could create a dummy pom with the necessary properties and make those calls through the Maven plugin.
Something like:
mvn -DserverAuthId=sonatype-nexus-staging -Dauto=true nexus:staging-close
Assumed things:
Ultimately, all this is doing is creating REST calls into Nexus. There is a full Nexus REST api but I have had little luck finding documentation for it that's not behind a paywall. You can turn on the debug mode for the plugin above and figure it out however by using -Dnexus.verboseDebug=true -X
.
You could also theoretically go into the UI, turn on the Firebug Net panel, and watch for /service POSTs and deduce a path there as well.
Better way:
encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )
To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type "Thyme &time=again" for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair. So instead of having a POST comment key equal to "Thyme &time=again", you have two POST keys, one equal to "Thyme " and another (time) equal to again.
For application/x-www-form-urlencoded (POST), per http://www.w3.org/TR/html401/interac...m-content-type, spaces are to be replaced by '+', so one may wish to follow a encodeURIComponent replacement with an additional replacement of "%20" with "+".
If one wishes to be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
function fixedEncodeURIComponent (str) {
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}
You need to parse the string you are sending from javascript object to the JSON object
var json=$.parseJSON(data);
DO NOT run php artisan migrate:fresh
that's gonna drop all the tables
Removing a file from pull request but not from your local repository.
git checkout -- c:\temp..... next git checkout origin/master -- c:\temp... u replace origin/master with any other branch. Next git commit -m c:\temp..... Next git push origin
Note : no single quote or double quotes for the filepath
For normal select option
<script>
$(document).ready(function() {
$("#id").val('select value here');
});
</script>
For select 2 option trigger option need to use
<script>
$(document).ready(function() {
$("#id").val('select value here').trigger('change');
});
</script>
I faced this problem today and I was able to solve it using this Gradle plugin
It's github url is this
IF you, like me, have no idea what Gradle is but need to run a backend to do your front end work, what you need to do is find the build.gradle file that is being called to start your BE server and add this to the top:
plugins {
id "ua.eshepelyuk.ManifestClasspath" version "1.0.0"
}
As an alternative to rendering a raster image, you can embed a SVG:
https://gist.github.com/CyberShadow/95621a949b07db295000
Unfortunately, even though you can select and copy text when you open the .svg file, the text is not selectable when the SVG image is embedded.
I got this problem today while installing SugarCRM (a free CRM).
The system was not able to connect to the database using the root user. I could definitively log in as root from the console... so what was the problem?
I found out that in my situation, I was getting exactly the same error, but that was because the password was sent to mysql directly from the $_POST
data, in other words, the <
character from my password was sent to mysql as <
which means the password was wrong.
Everything else did not help a bit. The list of users in mysql were correct, including the anonymous user (which appears after the root entries.)
I just modified your code. It works fine in my system. See if this helps
class round{
public static void main(String args[]){
double a = 123.13698;
double roundOff = Math.round(a*100)/100.00;
System.out.println(roundOff);
}
}
Use the "not" selector.
For example, instead of:
$(".thumbs").hover()
try:
$(".thumbs:not(.selected)").hover()