This works in my case. I hope you can extract meaning out of it.
//div[text()='building1' and @class='wrap']/ancestor::tr/td/div/div[@class='x-grid-row-checker']
As pointed out in this comment How do you check in python whether a string contains only numbers? the isdigit()
method is not totally accurate for this use case, because it returns True for some digit-like characters:
>>> "\u2070".isdigit() # unicode escaped 'superscript zero'
True
If this needs to be avoided, the following simple function checks, if all characters in a string are a digit between "0" and "9":
import string
def contains_only_digits(s):
# True for "", "0", "123"
# False for "1.2", "1,2", "-1", "a", "a1"
for ch in s:
if not ch in string.digits:
return False
return True
Used in the example from the question:
if len(isbn) == 10 and contains_only_digits(isbn):
print ("Works")
For Python 3 above, use:
sudo apt-get install python3-dateutil
You need either
A foreign key needs to uniquely identify the parent row: you currently have no way to do that because Title is not unique.
Suppress the @JoinColumn(name="categoria")
on the ID field of the Categoria
class and I think it will work.
Adding the GridView1.DataBind() to the button click event did not work for me. However, adding it to the SqlDataSource1_Updated event did though.
Protected Sub SqlDataSource1_Updated(sender As Object, e As SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Updated
GridView1.DataBind()
End Sub
You can use IN operator as below
select * from dbo.books where isbn IN
(select isbn from dbo.lending where lended_date between @fdate and @tdate)
The linefeed character \n
is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n
instead, then it'll both see the line-break with only \n
and \r\n
, I've never had any problems using it.
Also, you should look into using a StringBuilder
instead of concatenating the String
in the while-loop at BookCatalog.toString()
, it is a lot more effective. For instance:
public String toString() {
BookNode current = front;
StringBuilder sb = new StringBuilder();
while (current!=null){
sb.append(current.getData().toString()+"\r\n ");
current = current.getNext();
}
return sb.toString();
}
I had the same problem and I had solved it with:
1.Right click to solution and click 'Clean Solution'
2.Click 'References'
folder in solution explorer and select the problem reference (in your case it seems System.Web.Mvc) and then right click and click 'Properties'
.
3.In the properties window, make sure that the 'Copy Local'
property is set to 'True'
This worked for me. Hope it works for someone else
Helpful Note: As it has mentioned in comments by @Vlad:
If it is already set to True:
You can use a Spring-EL expression, for eg on JDK 1.7:
@Cacheable(value="bookCache", key="T(java.util.Objects).hash(#p0,#p1, #p2)")
if you want to pass multiple parameters then you can create model instead of passing multiple parameters.
in case you dont want to pass any parameter then you can skip as well in it, and your code will look neat and clean.
Almost there. In your predicate, you want a relative path, so change
./book[/author/name = 'John']
to either
./book[author/name = 'John']
or
./book[./author/name = 'John']
and you will match your element. Your current predicate goes back to the root of the document to look for an author
.
SELECT
B.Title, B.Edition, B.Year, B.Pages, B.Rating --from Books
, C.Category --from Categories
, P.Publisher --from Publishers
, W.LastName --from Writers
FROM Books B
JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID
with git 1.7, there's a really easy way using git rebase
:
stage your files:
git add $files
create a new commit and re-use commit message of your "broken" commit
git commit -c master~4
prepend fixup!
in the subject line (or squash!
if you want to edit commit (message)):
fixup! Factored out some common XPath Operations
use git rebase -i --autosquash
to fixup your commit
At first you need to add semi colon (;) after quantity INT NOT NULL)
then remove ** from ,genre,quantity)**
.
to insert a value with numeric data type like int, decimal, float, etc you don't need to add single quote.
Answer: 165
Method: brute-force! Here is a tiny bit of Python (version 2.7) code to count'em all.
from math import sqrt, floor
is_ps = lambda x: floor(sqrt(x)) ** 2 == x
count = 0
for n in range(1002, 10000, 3):
if n % 11 and is_ps(sum(map(int, str(n)))):
count += 1
print "#%i: %s" % (count, n)
Consider using the Builder pattern. It allows for you to set default values on your parameters and initialize in a clear and concise way. For example:
Book b = new Book.Builder("Catcher in the Rye").Isbn("12345")
.Weight("5 pounds").build();
Edit: It also removes the need for multiple constructors with different signatures and is way more readable.
Haskell:
O'Reilly Book:
My favorite general, less academic online tutorials:
Books on Functional Programming with Haskell:
If you're doing this in Drupal and use the Form API to change the #type from text to 'hidden' in hook_form_alter (for example), be advised that the output HTML will have different (or omitted) DIV wrappers, IDs and class names.
public static void main(String[] args) {
String test = "something hear - to - find some to or tows";
System.out.println("1.result: " + contains("- to -( \\w+) som", test, null));
System.out.println("2.result: " + contains("- to -( \\w+) som", test, 5));
}
static boolean contains(String pattern, String text, Integer fromIndex){
if(fromIndex != null && fromIndex < text.length())
return Pattern.compile(pattern).matcher(text).find();
return Pattern.compile(pattern).matcher(text).find();
}
1.result: true
2.result: true
This is a good way of collecting performance information for the specific operation.
start = new Date().getTime();
for (var n = 0; n < maxCount; n++) {
/* perform the operation to be measured *//
}
elapsed = new Date().getTime() - start;
assert(true,"Measured time: " + elapsed);
With LINQ:
List<string> l = new List<string> { "1", "2", "3" ,"4","5"};
List<string> l2 = l.Skip(1).Take(2).ToList();
If you need foreach, then no need for ToList:
foreach (string s in l.Skip(1).Take(2)){}
Advantage of LINQ is that if you want to just skip some leading element,you can :
List<string> l2 = l.Skip(1).ToList();
foreach (string s in l.Skip(1)){}
i.e. no need to take care of count/length, etc.
You can also use this trick: replace
$("#topbar").click(function(){
by
$(document).on("click", "#topbar", function(){
This will bind an event on a not loaded yet object... ;)
You've declared the class Thing
as a non-static inner class. That means it must be associated with an instance of the Hello
class.
In your code, you're trying to create an instance of Thing
from a static context. That is what the compiler is complaining about.
There are a few possible solutions. Which solution to use depends on what you want to achieve.
Move Thing
out of the Hello
class.
Change Thing
to be a static
nested class.
static class Thing
Create an instance of Hello
before creating an instance of Thing
.
public static void main(String[] args)
{
Hello h = new Hello();
Thing thing1 = h.new Thing(); // hope this syntax is right, typing on the fly :P
}
The last solution (a non-static nested class) would be mandatory if any instance of Thing
depended on an instance of Hello
to be meaningful. For example, if we had:
public class Hello {
public int enormous;
public Hello(int n) {
enormous = n;
}
public class Thing {
public int size;
public Thing(int m) {
if (m > enormous)
size = enormous;
else
size = m;
}
}
...
}
any raw attempt to create an object of class Thing
, as in:
Thing t = new Thing(31);
would be problematic, since there wouldn't be an obvious enormous
value to test 31 against it. An instance h
of the Hello
outer class is necessary to provide this h.enormous
value:
...
Hello h = new Hello(30);
...
Thing t = h.new Thing(31);
...
Because it doesn't mean a Thing
if it doesn't have a Hello
.
For more information on nested/inner classes: Nested Classes (The Java Tutorials)
Try:
java -cp . Echo "hello"
Assuming that you compiled with:
javac Echo.java
Then there is a chance that the "current" directory is not in your classpath ( where java looks for .class definitions )
If that's the case and listing the contents of your dir displays:
Echo.java
Echo.class
Then any of this may work:
java -cp . Echo "hello"
or
SET CLASSPATH=%CLASSPATH;.
java Echo "hello"
And later as Fredrik points out you'll get another error message like.
Exception in thread "main" java.lang.NoSuchMethodError: main
When that happens, go and read his answer :)
Try changing the box-sizing
to border-box
. The padding
is adding to width
of your input
elements.
CSS
input[type=text],
input[type=password] {
width: 100%;
margin-top: 5px;
height: 25px;
...
}
input {
box-sizing: border-box;
}
To fully overload it you also need to implement the __setitem__
and __delitem__
methods.
edit
I almost forgot... if you want to completely emulate a list, you also need __getslice__, __setslice__ and __delslice__
.
There are all documented in http://docs.python.org/reference/datamodel.html
DIVs inherently lack any useful meaning, other than to divide, of course.
Best course of action would be to add a meaningful class name to them, and style their individual margins in CSS.
<h1>Important Title</h1>
<div class="testimonials">...</div>
<div class="footer">...</div>
h1 {margin-bottom: 0.1em;}
div.testimonials {margin-bottom: 0.2em;}
div.footer {margin-bottom: 0;}
Type IF /? to get help about if, it clearly explains how to use IF EXIST.
To delete a complete tree except some folders, see the answer of this question: Windows batch script to delete everything in a folder except one
Finally copying just means calling COPY and calling another bat file can be done like this:
MYOTHERBATFILE.BAT sync.bat myprogram.ini
You can simply assign it a new value as follows,
window.location.hash
In my case, the culprit was found in the logfiles:
$ tail /usr/local/var/mysql/<hostname>.lan.err
2019-09-19 7:32:21 0 [ERROR] InnoDB: redo log file './ib_logfile0' exists. Creating system tablespace with existing redo log files is not recommended. Please delete all redo log files before creating new system tablespace.
2019-09-19 7:32:21 0 [ERROR] InnoDB: Database creation was aborted with error Generic error. You may need to delete the ibdata1 file before trying to start up again.
So I renamed ib_logfile0
to get rid of the error (I had to do the same with ib_logfile1
afterwards).
mv /usr/local/var/mysql/ib_logfile0 /usr/local/var/mysql/ib_logfile0_bak
mv /usr/local/var/mysql/ib_logfile1 /usr/local/var/mysql/ib_logfile1_bak
brew services restart mariadb
It appears you could use a list
instead of a tuple
.
This becomes more important I think when you are grabbing attributes instead of 'magic indexes' of a list/tuple.
In my case I wanted to sort by multiple attributes of a class, where the incoming keys were strings. I needed different sorting in different places, and I wanted a common default sort for the parent class that clients were interacting with; only having to override the 'sorting keys' when I really 'needed to', but also in a way that I could store them as lists that the class could share
So first I defined a helper method
def attr_sort(self, attrs=['someAttributeString']:
'''helper to sort by the attributes named by strings of attrs in order'''
return lambda k: [ getattr(k, attr) for attr in attrs ]
then to use it
# would defined elsewhere but showing here for consiseness
self.SortListA = ['attrA', 'attrB']
self.SortListB = ['attrC', 'attrA']
records = .... #list of my objects to sort
records.sort(key=self.attr_sort(attrs=self.SortListA))
# perhaps later nearby or in another function
more_records = .... #another list
more_records.sort(key=self.attr_sort(attrs=self.SortListB))
This will use the generated lambda function sort the list by object.attrA
and then object.attrB
assuming object
has a getter corresponding to the string names provided. And the second case would sort by object.attrC
then object.attrA
.
This also allows you to potentially expose outward sorting choices to be shared alike by a consumer, a unit test, or for them to perhaps tell you how they want sorting done for some operation in your api by only have to give you a list and not coupling them to your back end implementation.
Case Insensitive Substring Example
This is an extension of Eugene's answer, which converts the strings to lower case before checking for the substring:
if (index(lc($str), lc($substr)) != -1) {
print "$str contains $substr\n";
}
Sometime this error also occur when you change the order of Component Function while passing to connect.
Incorrect Order:
export default connect(mapDispatchToProps, mapStateToProps)(TodoList);
Correct Order:
export default connect(mapStateToProps,mapDispatchToProps)(TodoList);
You could also use GDAL to do this. I realize that it is a geospatial toolkit, but nothing requires you to have a cartographic product.
Link to precompiled GDAL binaries for windows (assuming windows here) http://www.gisinternals.com/sdk/
To access the array:
from osgeo import gdal
dataset = gdal.Open("path/to/dataset.tiff", gdal.GA_ReadOnly)
for x in range(1, dataset.RasterCount + 1):
band = dataset.GetRasterBand(x)
array = band.ReadAsArray()
There is one nice workaround at http://taskjs.org/
It uses generators which are new to javascript. So it's currently not implemented by most browsers. I tested it in firefox, and for me it is nice way to wrap asynchronous function.
Here is example code from project GitHub
var { Deferred } = task;
spawn(function() {
out.innerHTML = "reading...\n";
try {
var d = yield read("read.html");
alert(d.responseText.length);
} catch (e) {
e.stack.split(/\n/).forEach(function(line) { console.log(line) });
console.log("");
out.innerHTML = "error: " + e;
}
});
function read(url, method) {
method = method || "GET";
var xhr = new XMLHttpRequest();
var deferred = new Deferred();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 400) {
var e = new Error(xhr.statusText);
e.status = xhr.status;
deferred.reject(e);
} else {
deferred.resolve({
responseText: xhr.responseText
});
}
}
};
xhr.open(method, url, true);
xhr.send();
return deferred.promise;
}
it's in <algorithm>
and called std::find
.
import sys
import timeit
start = timeit.default_timer()
#do some nice things...
stop = timeit.default_timer()
total_time = stop - start
# output running time in a nice format.
mins, secs = divmod(total_time, 60)
hours, mins = divmod(mins, 60)
sys.stdout.write("Total running time: %d:%d:%d.\n" % (hours, mins, secs))
It's printing out the actual, exact value of the double
.
Double.toString()
, which converts double
s to String
s, does not print the exact decimal value of the input -- if x
is your double value, it prints out exactly enough digits that x
is the closest double
to the value it printed.
The point is that there is no such double
as 47.48 exactly. Doubles store values as binary fractions, not as decimals, so it can't store exact decimal values. (That's what BigDecimal
is for!)
See the docs from django: https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest
You need to specify a field in latest(). eg.
obj= Model.objects.filter(testfield=12).latest('testfield')
Or if your model’s Meta specifies get_latest_by, you can leave off the field_name
argument to earliest() or latest()
. Django will use the field specified in get_latest_by
by default.
Working Fiddle on <body onload="myFunction()">
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myFunction(){
alert("Page is loaded");
}
</script>
</head>
<body onload="myFunction()">
<h1>Hello World!</h1>
</body>
</html>
I had the same problem, also in my XCTestCase
files, but not in the regular project files.
To get rid of the:
Use of unresolved identifier 'PrimeNumberModel'
I needed to import
the base module in the test file. In my case, my target is called 'myproject' and I added import myproject
and the class was recognised.
As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship. You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.
For instance, the implementation code of the extra class should look like that:
@Entity
@Table(name = "USER_SERVICES")
public class UserService{
// example of auto-generated ID
@Id
@Column(name = "USER_SERVICES_ID", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long userServiceID;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ID")
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SERVICE_ID")
private Service service;
// example of extra column
@Column(name="VISIBILITY")
private boolean visibility;
public long getUserServiceID() {
return userServiceID;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
public boolean getVisibility() {
return visibility;
}
public void setVisibility(boolean visibility) {
this.visibility = visibility;
}
}
If you define the ListView
in XAML:
<ListView x:Name="listView"/>
Then you can add columns and populate it in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Add columns
var gridView = new GridView();
this.listView.View = gridView;
gridView.Columns.Add(new GridViewColumn {
Header = "Id", DisplayMemberBinding = new Binding("Id") });
gridView.Columns.Add(new GridViewColumn {
Header = "Name", DisplayMemberBinding = new Binding("Name") });
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
However, it's easier to define the columns in XAML (inside the ListView
definition):
<ListView x:Name="listView">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
</GridView>
</ListView.View>
</ListView>
And then just populate the list in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
MyItem
DefinitionMyItem
is defined like this:
public class MyItem
{
public int Id { get; set; }
public string Name { get; set; }
}
In my case, I want to duplicate the object, but change the id, so I use this
Common.DataContext.Detach(object);
Work like a charm
For anyone else who did all the advice but the problem still persists.
Check for stored procedure and view DEFINERS. Those definers may no longer exists.
My problem showed up when we changed the wildcard host (%) to IP specific, making the database more secure. Unfortunately there are some views that are still using 'user'@'%' even though 'user'@'172....' is technically correct.
By invoking its toString()
method.
Returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence.
Clustered Index
A clustered index determine the physical order of DATA in a table.For this reason a table have only 1 clustered index.
"dictionary" No need of any other Index, its already Index according to words
Nonclustered Index
A non clustered index is analogous to an index in a Book.The data is stored in one place. The index is storing in another place and the index have pointers to the storage location of the data.For this reason a table have more than 1 Nonclustered index.
Not only HTML5 but a bit of JavaScript
Click [here]https://codepen.io/diegoleme/pen/surIK
HTML
<form class="pure-form">
<fieldset>
<legend>Confirm password with HTML5</legend>
<input type="password" placeholder="Password" id="password" required>
<input type="password" placeholder="Confirm Password" id="confirm_password" required>
<button type="submit" class="pure-button pure-button-primary">Confirm</button>
</fieldset>
</form>
JAVASCRIPT
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
This should do it:
//Returns the index of the first occurence of char c in char* string. If not found -1 is returned.
int get_index(char* string, char c) {
char *e = strchr(string, c);
if (e == NULL) {
return -1;
}
return (int)(e - string);
}
I wrote small function for myself that works recursively in Postgres 9.4. I had same problem (good they did solve some of this headache in Postgres 9.5). Anyway here is the function (I hope it works well for you):
CREATE OR REPLACE FUNCTION jsonb_update(val1 JSONB,val2 JSONB)
RETURNS JSONB AS $$
DECLARE
result JSONB;
v RECORD;
BEGIN
IF jsonb_typeof(val2) = 'null'
THEN
RETURN val1;
END IF;
result = val1;
FOR v IN SELECT key, value FROM jsonb_each(val2) LOOP
IF jsonb_typeof(val2->v.key) = 'object'
THEN
result = result || jsonb_build_object(v.key, jsonb_update(val1->v.key, val2->v.key));
ELSE
result = result || jsonb_build_object(v.key, v.value);
END IF;
END LOOP;
RETURN result;
END;
$$ LANGUAGE plpgsql;
Here is sample use:
select jsonb_update('{"a":{"b":{"c":{"d":5,"dd":6},"cc":1}},"aaa":5}'::jsonb, '{"a":{"b":{"c":{"d":15}}},"aa":9}'::jsonb);
jsonb_update
---------------------------------------------------------------------
{"a": {"b": {"c": {"d": 15, "dd": 6}, "cc": 1}}, "aa": 9, "aaa": 5}
(1 row)
As you can see it analyze deep down and update/add values where needed.
I think you are getting confused about what the a:active
CSS selector does. This will only change the colour of your link when you click it (and only for the duration of the click i.e. how long your mouse button stays down). What you need to do is introduce a new class e.g. .selected
into your CSS and when you select a link, update the selected menu item with new class e.g.
<div class="menuBar">
<ul>
<li class="selected"><a href="index.php">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
....
</ul>
</div>
// specific CSS for your menu
div.menuBar li.selected a { color: #FF0000; }
// more general CSS
li.selected a { color: #FF0000; }
You will need to update your template page to take in a selectedPage
parameter.
Loose coupling is and answer to to old style hardcoded dependencies and related issues issues like frequent recompilation when anything changes and code reuse. It stresses on implementing the worker logic in components and avoiding solution specific wire up code there.
We need to remember that the {% endif %}
comes after the {% else %}
.
So this is an example:
{% if someTest %}
<p> Something is True </p>
{% else %}
<p> Something is False </p>
{% endif %}
Just for the sake of completeness, since I noticed no one suggested this simple approach:
>>> print("%.0f%%" % (100 * 1.0/3))
33%
Details:
%.0f
stands for "print a float with 0 decimal places", so %.2f
would print 33.33
%%
prints a literal %
. A bit cleaner than your original +'%'
1.0
instead of 1
takes care of coercing the division to float, so no more 0.0
ByteArrayInputStream also does the trick:
InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );
Then convert to reader:
InputStreamReader reader = new InputStreamReader(is);
You can also look in the registry.
using System.IO;
using Microsoft.Win32;
string GetMimeType(FileInfo fileInfo)
{
string mimeType = "application/unknown";
RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(
fileInfo.Extension.ToLower()
);
if(regKey != null)
{
object contentType = regKey.GetValue("Content Type");
if(contentType != null)
mimeType = contentType.ToString();
}
return mimeType;
}
One way or another you're going to have to tap into a database of MIMEs - whether they're mapped from extensions or magic numbers is somewhat trivial - windows registry is one such place. For a platform independent solution though one would have to ship this DB with the code (or as a standalone library).
Yes, you must open php.ini
and remove the semicolon to:
;extension=php_openssl.dll
If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext
) and add this to php.ini
in the "Dynamic Extensions" section:
extension=php_openssl.dll
Things have changed for PHP > 7. This is what i had to do for PHP 7.2.
Step: 1: Uncomment extension=openssl
Step: 2: Uncomment extension_dir = "ext"
Step: 3: Restart xampp.
Done.
Explanation: ( From php.ini )
If you wish to have an extension loaded automatically, use the following syntax:
extension=modulename
Note : The syntax used in previous PHP versions (extension=<ext>.so
and extension='php_<ext>.dll
) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>
) syntax.
Special Note: Be sure to appropriately set the extension_dir
directive.
There's two ways to say "don't match": character ranges, and zero-width negative lookahead/lookbehind.
The former: don't match a
, b
, c
or 0
: [^a-c0]
The latter: match any three-letter string except foo
and bar
:
(?!foo|bar).{3}
or
.{3}(?<!foo|bar)
Also, a correction for you: *
, ?
and +
do not actually match anything. They are repetition operators, and always follow a matching operator. Thus, a+
means match one or more of a
, [a-c0]+
means match one or more of a
, b
, c
or 0
, while [^a-c0]+
would match one or more of anything that wasn't a
, b
, c
or 0
.
You can do something like this,
Dim lstOfStrings As New List(Of String) From {"Value1", "Value2", "Value3"}
The canonical way to get the current location object is window.location
(see this MSDN page from 1996 and the W3C draft from 2006).
Compare this to document.location
, which originally only returned the current URL as a string (see this page on MSDN). Probably to avoid confusion, document.location
was replaced with document.URL
(see here on MSDN), which is also part of DOM Level 1.
As far as I know, all modern browsers map document.location
to window.location
, but I still prefer window.location
as that's what I've used since I wrote my first DHTML.
Visual Studio 2010 SP1 and 2012 added support for IIS Express eliminating the need to edit angle brackets.
I believe this solution is superior to the vikomall's options.
The UI-based solution above uses site-specific location elements in IIS Express's applicationHost.config leaving the app untouched.
More information here: http://msdn.microsoft.com/en-us/magazine/hh288080.aspx
Since you're only dealing with a 3x3 matrix of possible locations, it'd be pretty easy to just write a search through all possibilities without taxing you computing power. For each open space, compute through all the possible outcomes after that marking that space (recursively, I'd say), then use the move with the most possibilities of winning.
Optimizing this would be a waste of effort, really. Though some easy ones might be:
Simple
function isInteger(num) {
return (num ^ 0) === num;
}
console.log(isInteger(1));
You can also extend Number and assign the function to it via prototype.
ArrayList<String> list = new ArrayList<String>();
list.add("blah");
list.add("bleh");
JSONArray jsArray = new JSONArray(list);
This is only an example using a string arraylist
Finally this worked for me
private String buildBasicAuthorizationString(String username, String password) {
String credentials = username + ":" + password;
return "Basic " + new String(Base64.encode(credentials.getBytes(), Base64.NO_WRAP));
}
try this:
header('Content-type: audio/mp3');
header('Content-disposition: attachment;
filename=“'.$trackname'”');
readfile('folder name /'.$trackname);
exit();
I believe it's more useful to think of mod
as it's defined in abstract arithmetic; not as an operation, but as a whole different class of arithmetic, with different elements, and different operators. That means addition in mod 3
is not the same as the "normal" addition; that is; integer addition.
So when you do:
5 % -3
You are trying to map the integer 5 to an element in the set of mod -3
. These are the elements of mod -3
:
{ 0, -2, -1 }
So:
0 => 0, 1 => -2, 2 => -1, 3 => 0, 4 => -2, 5 => -1
Say you have to stay up for some reason 30 hours, how many hours will you have left of that day? 30 mod -24
.
But what C implements is not mod
, it's a remainder. Anyway, the point is that it does make sense to return negatives.
$.each(top_brands, function(index, el) {
for (var key in el) {
if (el.hasOwnProperty(key)) {
brand_options.append($("<option />").val(key).text(key+ " " + el[key]));
}
}
});
But if your data structure is var top_brands = {'Adidas': 100, 'Nike': 50};
, then thing will be much more simple.
for (var key in top_brands) {
if (top_brands.hasOwnProperty(key)) {
brand_options.append($("<option />").val(key).text(key+ " " + el[key]));
}
}
Or use the jquery each:
$.each(top_brands, function(key, value) {
brand_options.append($("<option />").val(key).text(key + " " + value));
});
Code to check whether two elements exist in array whose product equals k:
n = len(arr1)
for i in arr1:
if k%i==0:
print(i)
try this;
webView.loadData("<iframe src='http://www.google.com' style='border: 0; width: 100%; height: 100%'></iframe>", "text/html; charset=utf-8", "UTF-8");
Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.
If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.
I have searched for a solution that will visualize process steps in my web application. I have found the following excellent write-up by Stephen A Thomas:
Tracking Progress in Pure CSS (Original Link now dead)
In his approach Thomas even gets away with just using CSS - no Javascript! In an essence the following CSS code from his article does the trick for me:
<style>
<!-- Progress with steps -->
ol.progtrckr {
margin: 0;
padding: 0;
list-style-type: none;
}
ol.progtrckr li {
display: inline-block;
text-align: center;
line-height: 3em;
}
ol.progtrckr[data-progtrckr-steps="2"] li { width: 49%; }
ol.progtrckr[data-progtrckr-steps="3"] li { width: 33%; }
ol.progtrckr[data-progtrckr-steps="4"] li { width: 24%; }
ol.progtrckr[data-progtrckr-steps="5"] li { width: 19%; }
ol.progtrckr[data-progtrckr-steps="6"] li { width: 16%; }
ol.progtrckr[data-progtrckr-steps="7"] li { width: 14%; }
ol.progtrckr[data-progtrckr-steps="8"] li { width: 12%; }
ol.progtrckr[data-progtrckr-steps="9"] li { width: 11%; }
ol.progtrckr li.progtrckr-done {
color: black;
border-bottom: 4px solid yellowgreen;
}
ol.progtrckr li.progtrckr-todo {
color: silver;
border-bottom: 4px solid silver;
}
ol.progtrckr li:after {
content: "\00a0\00a0";
}
ol.progtrckr li:before {
position: relative;
bottom: -2.5em;
float: left;
left: 50%;
line-height: 1em;
}
ol.progtrckr li.progtrckr-done:before {
content: "\2713";
color: white;
background-color: yellowgreen;
height: 1.2em;
width: 1.2em;
line-height: 1.2em;
border: none;
border-radius: 1.2em;
}
ol.progtrckr li.progtrckr-todo:before {
content: "\039F";
color: silver;
background-color: white;
font-size: 1.5em;
bottom: -1.6em;
}
</style>
As well as HTML tags from his example (I use Grails GSP pages to generate tags and 'done/todo' class dynamically):
<ol class="progtrckr" data-progtrckr-steps="5">
<li class="progtrckr-done">Order Processing</li>
<li class="progtrckr-done">Pre-Production</li>
<li class="progtrckr-done">In Production</li>
<li class="progtrckr-done">Shipped</li>
<li class="progtrckr-todo">Delivered</li>
</ol>
Hope it helps. Works pretty well for me.
UPDATE: The following (shortened) version also works well.
ol.progtrckr {
display: table;
list-style-type: none;
margin: 0;
padding: 0;
table-layout: fixed;
width: 100%;
}
ol.progtrckr li {
display: table-cell;
text-align: center;
line-height: 3em;
}
... and the rest of the CSS ...
<ol class="progtrckr">
...
</ol>
display: table; table-layout: fixed; width: 100%
ensure that the list items are automatically sized equally as long as the content does not overflow. There is no need to use data-progtrckr-steps
and its associated CSS.
Use CryptoJS
Here's the code: https://github.com/odedhb/AES-encrypt
And here's an online working example: https://odedhb.github.io/AES-encrypt/
A similar approach to https://stackoverflow.com/a/15385080/337172 but hopefully more understandable and easy to tweak:
diff \
--new-line-format="%L" \
--old-line-format="" \
--unchanged-line-format="" \
A1 A2
It sounds like you want to use a transparent background, in which case you could try using the rgba()
function:
rgba(R, G, B, A)
R (red), G (green), and B (blue) can be either
<integer>
s or<percentage>
s, where the number 255 corresponds to 100%. A (alpha) can be a<number>
between 0 and 1, or a<percentage>
, where the number 1 corresponds to 100% (full opacity).RGBa example
rgba(51, 170, 51, .1) /* 10% opaque green */ rgba(51, 170, 51, .4) /* 40% opaque green */ rgba(51, 170, 51, .7) /* 70% opaque green */ rgba(51, 170, 51, 1) /* full opaque green */
A small example showing how rgba
can be used.
As of 2018, practically every browser supports the rgba
syntax.
Excel ColumnWidth from dataGridView:
foreach (DataGridViewColumn co in dataGridView1.Columns)
{ worksheet.Columns[co.Index + 1].ColumnWidth = co.Width/8; }
Ran into the same bug here. This worked for me.
.navbar {
position: static;
}
By setting the position to static, it means the navbar will fall into the flow of the document as it normally would.
I use TINYINT(1) in order to store boolean values in Mysql.
I don't know if there is any advantage to use this... But if i'm not wrong, mysql can store boolean (BOOL) and it store it as a tinyint(1)
http://dev.mysql.com/doc/refman/5.0/en/other-vendor-data-types.html
You can also get it from post_meta like this:
echo get_post_meta($post->ID, 'featured_image', true);
One thing I didn't try was editing /etc/udev/rules.d/70-android.rules. Is that likely to be the issue?
Any particular reason why you didn't do that? To answer the question - YES! The udev rules are what informs Ubuntu what your device is and allows user-space tools to therefore access it.
You will not be able to use adb without correctly following the instructions.
With that in mind however, you don't say what version of Ubuntu you're using but I had issues with 10.10 - let me know if you need me to post the contents of my rules file.
Don't worry about running adb via sudo, you don't need it. The MODE="0666"
from the udev rule allows you to access the device as any user.
EDIT:
Don't forget to reload the rules:
sudo udevadm control --reload-rules
EDIT #2:
As @Jesse Glick correctly points out, if adb is already running in daemon mode, you'll also need to restart it for this to work:
sudo adb kill-server
I've used sudo here, since that will guarantee that adb will be killed , and it's the officially supported method to stop the server. It will be automatically restarted the next time adb is used, but this time with the correct environment.
Use target="_top"
attribute in anchor tag that will really work.
Prolog program actually is big condition for "if" with "then" which prints "Goal is reached" and "else" which prints "No sloutions was found". A, B
means "A is true and B is true", most of prolog systems will not try to satisfy "B" if "A" is not reachable (i.e. X=3, write('X is 3'),nl
will print 'X is 3' when X=3, and will do nothing if X=2).
You should use hash (#) tables, That you actually looking for because variables value will remain till that execution only. e.g. -
declare @TEMP table (ID int, Name varchar(max))
insert into @temp SELECT ID, Name FROM Table
When above two and below two statements execute separately.
SELECT * FROM @TEMP
WHERE @TEMP.ID = 1
The error will show because the value of variable lost when you execute the batch of query second time. It definitely gives o/p when you run an entire block of code.
The hash table is the best possible option for storing and retrieving the temporary value. It last long till the parent session is alive.
I had the same error when multiline string included new line (\n
) characters. Merging all lines into one (thus removing all new line characters) and sending it to a browser used to solve. But was very inconvenient to code.
Often could not understand why this was an issue in Chrome until I came across to a statement which said that the current version of JavaScript engine in Chrome doesn't support multiline strings which are wrapped in single quotes and have new line (\n
) characters in them. To make it work, multiline string need to be wrapped in double quotes. Changing my code to this, resolved this issue.
I will try to find a reference to a standard or Chrome doc which proves this. Until then, try this solution and see if works for you as well.
the Demo from Apple document. https://developer.apple.com/documentation/swift/using_objective-c_runtime_features_in_swift
import UIKit
class MyViewController: UIViewController {
let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// without parameter style
let action = #selector(MyViewController.tappedButton)
// with parameter style
// #selector(MyViewController.tappedButton(_:))
myButton.addTarget(self, action: action, forControlEvents: .touchUpInside)
}
@objc func tappedButton(_ sender: UIButton?) {
print("tapped button")
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
Use
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return shouldOverrideUrlLoading(view, request.getUrl().toString());
}
Default working of EditText
:
On first click it focuses and on second click it handles onClickListener
so you need to disable focus. Then on first click the onClickListener
will handle.
To do that you need to add this android:focusableInTouchMode="false"
attribute to your EditText
. That's it!
Something like this:
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="false"
android:inputType="text" />
iOS Status bar has only 2 options (black and white). You can try this in AppDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleLightContent];
}
You can use reflection to iterate over the object's field, and set them. You'd obviously need some sort of mapping between types or even field names and required default values but this can be done quite easily in a loop. For example:
for (Field f : obj.getClass().getFields()) {
f.setAccessible(true);
if (f.get(obj) == null) {
f.set(obj, getDefaultValueForType(f.getType()));
}
}
[Update]
With modern Java, you can use annotations to set the default values for fields on a per class basis. A complete implementation might look like this:
// DefaultString.java:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface DefaultString {
String value();
}
// DefaultInteger.java:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface DefaultInteger {
int value();
}
// DefaultPojo.java:
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
public class DefaultPojo {
public void setDefaults() {
for (Field f : getClass().getFields()) {
f.setAccessible(true);
try {
if (f.get(this) == null) {
f.set(this, getDefaultValueFromAnnotation(f.getAnnotations()));
}
} catch (IllegalAccessException e) { // shouldn't happen because I used setAccessible
}
}
}
private Object getDefaultValueFromAnnotation(Annotation[] annotations) {
for (Annotation a : annotations) {
if (a instanceof DefaultString)
return ((DefaultString)a).value();
if (a instanceof DefaultInteger)
return ((DefaultInteger)a).value();
}
return null;
}
}
// Test Pojo
public class TestPojo extends DefaultPojo {
@DefaultString("Hello world!")
public String stringValue;
@DefaultInteger(42);
public int integerValue;
}
Then default values for a TestPojo
can be set just by running test.setDetaults()
Make sure of the conflict origin: if it is the result of a git merge
, see Brian Campbell's answer.
But if is the result of a git rebase
, in order to discard remote (their) changes and use local changes, you would have to do a:
git checkout --theirs -- .
See "Why is the meaning of “ours
” and “theirs
” reversed"" to see how ours
and theirs
are swapped during a rebase (because the upstream branch is checked out).
I met the same challenge while trying to install [email protected].
And after looking at the current official documentation, and having read the answers above, i noticed that you might not necessarily have to install node-gyp nor install windows-build tools. This is what it says, here about installing node-gyp on windows. Remember node-gyp is involved in the installation process of node-sass. And you don't really have to re-install another python version.
This is the savior, configure the python path that "npm" should look for while installing any packages that require build-tools.
C:\> npm config set python /Python36/python
I had installed python3.6.3, on windows-7, there.
Use 'a'
, 'a'
means append
. Anything written to a file opened with 'a'
attribute is written at the end of the file.
with open('file.txt', 'a') as file:
file.write('input')
Here is another, more general solution assuming you don't have a list of rows (maybe they don't fit in memory) or a copy of the headers (maybe the write_csv
function is generic):
def gen_rows():
yield OrderedDict(name='bob', age=25, weight=200)
yield OrderedDict(name='jim', age=31, weight=180)
def write_csv():
it = genrows()
first_row = it.next() # __next__ in py3
with open("people.csv", "w") as outfile:
wr = csv.DictWriter(outfile, fieldnames=list(first_row))
wr.writeheader()
wr.writerow(first_row)
wr.writerows(it)
Note: the OrderedDict constructor used here only preserves order in python >3.4. If order is important, use the OrderedDict([('name', 'bob'),('age',25)])
form.
I was having same issue when I was receiving array of objects in django sent by ajax. JSONStringyfy worked for me. You can have a look for this.
First I stringify the data as
var myData = [];
allData.forEach((x, index) => {
// console.log(index);
myData.push(JSON.stringify({
"product_id" : x.product_id,
"product" : x.product,
"url" : x.url,
"image_url" : x.image_url,
"price" : x.price,
"source": x.source
}))
})
Then I sent it like
$.ajax({
url: '{% url "url_name" %}',
method: "POST",
data: {
'csrfmiddlewaretoken': '{{ csrf_token }}',
'queryset[]': myData
},
success: (res) => {
// success post work here.
}
})
And received as :
list_of_json = request.POST.getlist("queryset[]", [])
list_of_json = [ json.loads(item) for item in list_of_json ]
Pretty much the same as already suggested but a bit different. About as much code as jQuery in Vanilla JS:
selected = Array.prototype.filter.apply(
select.options, [
function(o) {
return o.selected;
}
]
);
It seems to be faster than a loop in IE, FF and Safari. I find it interesting that it's slower in Chrome and Opera.
Another approach would be using selectors:
selected = Array.prototype.map.apply(
select.querySelectorAll('option[selected="selected"]'),
[function (o) { return o.value; }]
);
In case you'd like to do it with async:
const request = async <T>(param1: string, param2: number) => {
const res = await func();
return res.response() as T;
}
And a more complex pattern, in case you'd like to wrap your function inside a generic counterpart, such as memoization (Example uses fast-memoize):
const request = memoize(
async <T>(
url: string,
token?: string
) => {
// Perform your code here
}
);
See how you define the generic after the memoizing function.
imagesLoaded Plugin is way to go ,if you need a crossbrowser solution
$("<img>", {src: 'image.jpg'}).imagesLoaded( function( $images, $proper, $broken ){
if($broken.length > 0){
//Error CallBack
console.log('Error');
}
else{
// Load CallBack
console.log('Load');
}
});
If You Just Need a IE WorkAround,This Will Do
var img = $("<img>", {
error: function() {console.log('error'); },
load: function() {console.log('load');}
});
img.attr('src','image.jpg');
Sublime 3 for Windows:
Add comment tags -> CTRL + SHIFT + ;
The whole line becomes a comment line -> CTRL + ;
If you only need the number of rows in a query and don't need the actual row data, use count_all_results
echo $this->db
->where('active',1)
->count_all_results('table_name');
And what about it?:
ImageIcon imageIcon = new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
label.setIcon(imageIcon);
StringBuffer is used to store character strings that will be changed (String objects cannot be changed). It automatically expands as needed. Related classes: String, CharSequence.
StringBuilder was added in Java 5. It is identical in all respects to StringBuffer except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble. For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster.
In the Unix world, there were a few possible arrangements for the sizes of integers and pointers for 64-bit platforms. The two mostly widely used were ILP64 (actually, only a very few examples of this; Cray was one such) and LP64 (for almost everything else). The acronynms come from 'int, long, pointers are 64-bit' and 'long, pointers are 64-bit'.
Type ILP64 LP64 LLP64
char 8 8 8
short 16 16 16
int 64 32 32
long 64 64 32
long long 64 64 64
pointer 64 64 64
The ILP64 system was abandoned in favour of LP64 (that is, almost all later entrants used LP64, based on the recommendations of the Aspen group; only systems with a long heritage of 64-bit operation use a different scheme). All modern 64-bit Unix systems use LP64. MacOS X and Linux are both modern 64-bit systems.
Microsoft uses a different scheme for transitioning to 64-bit: LLP64 ('long long, pointers are 64-bit'). This has the merit of meaning that 32-bit software can be recompiled without change. It has the demerit of being different from what everyone else does, and also requires code to be revised to exploit 64-bit capacities. There always was revision necessary; it was just a different set of revisions from the ones needed on Unix platforms.
If you design your software around platform-neutral integer type names, probably using the C99 <inttypes.h>
header, which, when the types are available on the platform, provides, in signed (listed) and unsigned (not listed; prefix with 'u'):
int8_t
- 8-bit integersint16_t
- 16-bit integersint32_t
- 32-bit integersint64_t
- 64-bit integersuintptr_t
- unsigned integers big enough to hold pointersintmax_t
- biggest size of integer on the platform (might be larger than int64_t
)You can then code your application using these types where it matters, and being very careful with system types (which might be different). There is an intptr_t
type - a signed integer type for holding pointers; you should plan on not using it, or only using it as the result of a subtraction of two uintptr_t
values (ptrdiff_t
).
But, as the question points out (in disbelief), there are different systems for the sizes of the integer data types on 64-bit machines. Get used to it; the world isn't going to change.
PermGen space is replaced by MetaSpace in Java 8. The PermSize and MaxPermSize JVM arguments are ignored and a warning is issued if present at start-up.
Most allocations for the class metadata are now allocated out of native memory. * The classes that were used to describe class metadata have been removed.
Main difference between old PermGen and new MetaSpace is, you don't have to mandatory define upper limit of memory usage. You can keep MetaSpace space limit unbounded. Thus when memory usage increases you will not get OutOfMemoryError error. Instead the reserved native memory is increased to full-fill the increase memory usage.
You can define the max limit of space for MetaSpace, and then it will throw OutOfMemoryError : Metadata space. Thus it is important to define this limit cautiously, so that we can avoid memory waste.
I guess there is no white list in whatsapp, as I found a solution that worked for me. Do as follows. insert 3 meta tags:
<meta property="og:image" content="http://yourimage_with_complete_URL.png"/>
<meta property="og:title" content="Your Title"/>
<meta property="og:description" content="Your description."/>
Your image must be in .png format and 600x600px dimension and must be named 'logo-yoursite.png' (once it worked for me JUST LIKE THAT)
Dont forget to insert the link to whatsapp in your website:
<a href='whatsapp://send?text=Text to send withe message: http://www.yoursite.com'>whatsApp</a>
Do this and you'll be well done!
Thread
Thread represents an actual OS-level thread, with its own stack and kernel resources. (technically, a CLR implementation could use fibers instead, but no existing CLR does this) Thread allows the highest degree of control; you can Abort() or Suspend() or Resume() a thread (though this is a very bad idea), you can observe its state, and you can set thread-level properties like the stack size, apartment state, or culture.
The problem with Thread is that OS threads are costly. Each thread you have consumes a non-trivial amount of memory for its stack, and adds additional CPU overhead as the processor context-switch between threads. Instead, it is better to have a small pool of threads execute your code as work becomes available.
There are times when there is no alternative Thread. If you need to specify the name (for debugging purposes) or the apartment state (to show a UI), you must create your own Thread (note that having multiple UI threads is generally a bad idea). Also, if you want to maintain an object that is owned by a single thread and can only be used by that thread, it is much easier to explicitly create a Thread instance for it so you can easily check whether code trying to use it is running on the correct thread.
ThreadPool
ThreadPool is a wrapper around a pool of threads maintained by the CLR. ThreadPool gives you no control at all; you can submit work to execute at some point, and you can control the size of the pool, but you can't set anything else. You can't even tell when the pool will start running the work you submit to it.
Using ThreadPool avoids the overhead of creating too many threads. However, if you submit too many long-running tasks to the threadpool, it can get full, and later work that you submit can end up waiting for the earlier long-running items to finish. In addition, the ThreadPool offers no way to find out when a work item has been completed (unlike Thread.Join()), nor a way to get the result. Therefore, ThreadPool is best used for short operations where the caller does not need the result.
Task
Finally, the Task class from the Task Parallel Library offers the best of both worlds. Like the ThreadPool, a task does not create its own OS thread. Instead, tasks are executed by a TaskScheduler; the default scheduler simply runs on the ThreadPool.
Unlike the ThreadPool, Task also allows you to find out when it finishes, and (via the generic Task) to return a result. You can call ContinueWith() on an existing Task to make it run more code once the task finishes (if it's already finished, it will run the callback immediately). If the task is generic, ContinueWith() will pass you the task's result, allowing you to run more code that uses it.
You can also synchronously wait for a task to finish by calling Wait() (or, for a generic task, by getting the Result property). Like Thread.Join(), this will block the calling thread until the task finishes. Synchronously waiting for a task is usually bad idea; it prevents the calling thread from doing any other work, and can also lead to deadlocks if the task ends up waiting (even asynchronously) for the current thread.
Since tasks still run on the ThreadPool, they should not be used for long-running operations, since they can still fill up the thread pool and block new work. Instead, Task provides a LongRunning option, which will tell the TaskScheduler to spin up a new thread rather than running on the ThreadPool.
All newer high-level concurrency APIs, including the Parallel.For*() methods, PLINQ, C# 5 await, and modern async methods in the BCL, are all built on Task.
Conclusion
The bottom line is that Task is almost always the best option; it provides a much more powerful API and avoids wasting OS threads.
The only reasons to explicitly create your own Threads in modern code are setting per-thread options, or maintaining a persistent thread that needs to maintain its own identity.
Try this:
body {
min-height:100%;
background:red;
}
#some_div {
min-height:100%;
background:black;
}
IE6 and earlier versions do not support the min-height property.
I think the problem is that when you tell the body to have a height of 100%, it's background can only be as tall as the hieght of one browser "viewport" (the viewing area that excludes the browsers toolbars & statusbars & menubars and the window edges). If the content is taller than one viewport, it will overflow the height devoted to the background.
This min-height property on the body should FORCE the background to be at least as tall as one viewport if your content does not fill one whole page down to the bottom, yet it should also let it grow downwards to encompass more interior content.
When it comes to Muhammad Mehdi's answer, it is better to do:
private void salary_texbox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex ( "[^0-9]+" );
if(regex.IsMatch(e.Text))
{
MessageBox.Show("Error");
}
}
Because when comparing with the TextCompositionEventArgs it gets also the last character, while with the textbox.Text it does not. With textbox, the error will show after next inserted character.
First install pillow
pip install pillow
Example
from PIL import Image, ImageDraw, ImageFont
image = Image.open('Focal.png')
width, height = image.size
draw = ImageDraw.Draw(image)
text = 'https://devnote.in'
textwidth, textheight = draw.textsize(text)
margin = 10
x = width - textwidth - margin
y = height - textheight - margin
draw.text((x, y), text)
image.save('devnote.png')
# optional parameters like optimize and quality
image.save('optimized.png', optimize=True, quality=50)
If you're just using a vanilla form (not a ModelForm), you can set a Field initial value ( https://docs.djangoproject.com/en/2.2/ref/forms/fields/#django.forms.Field.initial ) like
class MyForm(forms.Form):
my_field = forms.BooleanField(initial=True)
If you're using a ModelForm, you can set a default value on the model field ( https://docs.djangoproject.com/en/2.2/ref/models/fields/#default ), which will apply to the resulting ModelForm, like
class MyModel(models.Model):
my_field = models.BooleanField(default=True)
Finally, if you want to dynamically choose at runtime whether or not your field will be selected by default, you can use the initial parameter to the form when you initialize it:
form = MyForm(initial={'my_field':True})
Why do you want to use multiple [ng-app] ? Since Angular is resumed by using modules, you can use an app that use multiple dependencies.
Javascript:
// setter syntax -> initializing other module for demonstration
angular.module('otherModule', []);
angular.module('app', ['otherModule'])
.controller('AppController', function () {
// ...do something
});
// getter syntax
angular.module('otherModule')
.controller('OtherController', function () {
// ...do something
});
HTML:
<div ng-app="app">
<div ng-controller="AppController">...</div>
<div ng-controller="OtherController">...</div>
</div>
EDIT
Keep in mind that if you want to use controller inside controller you have to use the controllerAs syntax, like so:
<div ng-app="app">
<div ng-controller="AppController as app">
<div ng-controller="OtherController as other">...</div>
</div>
</div>
Show Processlist fetches the information from another table. Here is how you can pull the data and look at 'INFO' column which contains the whole query :
select * from INFORMATION_SCHEMA.PROCESSLIST where db = 'somedb';
You can add any condition or ignore based on your requirement.
The output of the query is resulted as :
+-------+------+-----------------+--------+---------+------+-----------+----------------------------------------------------------+
| ID | USER | HOST | DB | COMMAND | TIME | STATE | INFO |
+-------+------+-----------------+--------+---------+------+-----------+----------------------------------------------------------+
| 5 | ssss | localhost:41060 | somedb | Sleep | 3 | | NULL |
| 58169 | root | localhost | somedb | Query | 0 | executing | select * from sometable where tblColumnName = 'someName' |
It is quite easy to solve your task. You should create and use a new variable for summing values of the "Doctor Payment" column.
In your case the variable can be declared like this:
<variable name="total" class="java.lang.Integer" calculation="Sum">
<variableExpression><![CDATA[$F{payment}]]></variableExpression>
</variable>
The working example.
CSV datasource:
doctor_id,payment A1,123 B1,223 C2,234 D3,678 D1,343
The template:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport ...>
<queryString>
<![CDATA[]]>
</queryString>
<field name="doctor_id" class="java.lang.String"/>
<field name="payment" class="java.lang.Integer"/>
<variable name="total" class="java.lang.Integer" calculation="Sum">
<variableExpression><![CDATA[$F{payment}]]></variableExpression>
</variable>
<columnHeader>
<band height="20" splitType="Stretch">
<staticText>
<reportElement x="0" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement textAlignment="Center" verticalAlignment="Middle">
<font size="10" isBold="true" isItalic="true"/>
</textElement>
<text><![CDATA[Doctor ID]]></text>
</staticText>
<staticText>
<reportElement x="100" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement textAlignment="Center" verticalAlignment="Middle">
<font size="10" isBold="true" isItalic="true"/>
</textElement>
<text><![CDATA[Doctor Payment]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="20" splitType="Stretch">
<textField>
<reportElement x="0" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement/>
<textFieldExpression><![CDATA[$F{doctor_id}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="100" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement/>
<textFieldExpression><![CDATA[$F{payment}]]></textFieldExpression>
</textField>
</band>
</detail>
<summary>
<band height="20">
<staticText>
<reportElement x="0" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement>
<font isBold="true"/>
</textElement>
<text><![CDATA[Total]]></text>
</staticText>
<textField>
<reportElement x="100" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement>
<font isBold="true" isItalic="true"/>
</textElement>
<textFieldExpression><![CDATA[$V{total}]]></textFieldExpression>
</textField>
</band>
</summary>
</jasperReport>
The result will be:
You can find a lot of info in the JasperReports Ultimate Guide.
Your tomcat-users.xml
looks good.
Make sure you have the manager/
application inside your $CATALINA_BASE/webapps/
You have to install tomcat-admin package: sudo apt-get install tomcat8-admin
(for version 8)
I am using Eclipse. I had to copy the manager/
folder from C:\Program Files\apache-tomcat-8.5.20\webapps
to my Eclipse workspace (~\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\webapps\
).
To use the least amount of space you should use a CHAR field constrained to 'Y' or 'N'. Oracle doesn't support BOOLEAN, BIT, or TINYINT data types, so CHAR's one byte is as small as you can get.
I had the same error when I tried to open a CSV file by pandas.read_csv
method.
The solution was change the encoding to latin-1
:
pd.read_csv('ml-100k/u.item', sep='|', names=m_cols , encoding='latin-1')
With Java 8
DateTime
/LocalDateTime
:
String dateString = "01/13/2012";
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US);
LocalDate date = LocalDate.parse(dateString, dateFormat);
ValueRange range = date.range(ChronoField.DAY_OF_MONTH);
Long max = range.getMaximum();
LocalDate newDate = date.withDayOfMonth(max.intValue());
System.out.println(newDate);
OR
String dateString = "01/13/2012";
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US);
LocalDate date = LocalDate.parse(dateString, dateFormat);
LocalDate newDate = date.withDayOfMonth(date.getMonth().length(date.isLeapYear()));
System.out.println(newDate);
Output:
2012-01-31
LocalDateTime
should be used instead ofLocalDate
if you have time information in your date string . I.E.2015/07/22 16:49
Also not directly relevant to the OP, but failing to restart a PyCharm Python console, after adding a new object to a module, is also a great way to get a very confusing ImportError: Cannot import name ...
The confusing part is that PyCharm will autocomplete the import in the console, but the import then fails.
Yeah it's possible.
Button myBtn = (Button)findViewById(R.id.myButtonId);
myBtn.requestFocus();
or in XML
<Button ...><requestFocus /></Button>
Important Note: The button widget needs to be focusable
and focusableInTouchMode
. Most widgets are focusable
but not focusableInTouchMode
by default. So make sure to either set it in code
myBtn.setFocusableInTouchMode(true);
or in XML
android:focusableInTouchMode="true"
There is an easier way to avoid the Strong Parameters at all, you just need to convert the parameters to a regular hash, as:
unlocked_params = ActiveSupport::HashWithIndifferentAccess.new(params)
model.create!(unlocked_params)
This defeats the purpose of strong parameters of course, but if you are in a situation like mine (I'm doing my own management of allowed params in another part of my system) this will get the job done.
In MacOS, a simple way is to use Sublime settings and bindings.
Navigate to VS Code.
Click on Help -> Welcome
On the top right, you can find Customise section and in that click on Sublime.
Bingo. Done.
Reload VS Code and you are free to use Command
+ [
and Command
+ ]
Summary:
The curl_exec
command in PHP is a bridge to use curl
from console. curl_exec makes it easy to quickly and easily do GET/POST requests, receive responses from other servers like JSON and download files.
Warning, Danger:
curl
is evil and dangerous if used improperly because it is all about getting data from out there in the internet. Someone can get between your curl and the other server and inject a rm -rf /
into your response, and then why am I dropped to a console and ls -l
doesn't even work anymore? Because you mis underestimated the dangerous power of curl. Don't trust anything that comes back from curl to be safe, even if you are talking to your own servers. You could be pulling back malware to relieve fools of their wealth.
These were done on Ubuntu 12.10
Basic curl from the commandline:
el@apollo:/home/el$ curl http://i.imgur.com/4rBHtSm.gif > mycat.gif
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 492k 100 492k 0 0 1077k 0 --:--:-- --:--:-- --:--:-- 1240k
Then you can open up your gif in firefox:
firefox mycat.gif
Glorious cats evolving Toxoplasma gondii to cause women to keep cats around and men likewise to keep the women around.
cURL example get request to hit google.com, echo to the commandline:
This is done through the phpsh terminal:
php> $ch = curl_init();
php> curl_setopt($ch, CURLOPT_URL, 'http://www.google.com');
php> curl_exec($ch);
Which prints and dumps a mess of condensed html and javascript (from google) to the console.
cURL example put the response text into a variable:
This is done through the phpsh terminal:
php> $ch = curl_init();
php> curl_setopt($ch, CURLOPT_URL, 'http://i.imgur.com/wtQ6yZR.gif');
php> curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
php> $contents = curl_exec($ch);
php> echo $contents;
The variable now contains the binary which is an animated gif of a cat, possibilities are infinite.
Do a curl from within a PHP file:
Put this code in a file called myphp.php:
<?php
$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,'http://www.google.com');
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
if (empty($buffer)){
print "Nothing returned from url.<p>";
}
else{
print $buffer;
}
?>
Then run it via commandline:
php < myphp.php
You ran myphp.php and executed those commands through the php interpreter and dumped a ton of messy html and javascript to screen.
You can do GET
and POST
requests with curl, all you do is specify the parameters as defined here: Using curl to automate HTTP jobs
Reminder of danger:
Be careful dumping curl output around, if any of it gets interpreted and executed, your box is owned and your credit card info will be sold to third parties and you'll get a mysterious $900 charge from an Alabama one-man flooring company that's a front for overseas credit card fraud crime ring.
A good explanation of how BFS computes shortest paths, accompanied by the most efficient simple BFS algorithm of which I'm aware and also by working code, is provided in the following peer-reviewed paper:
https://queue.acm.org/detail.cfm?id=3424304
The paper explains how BFS computes a shortest-paths tree represented by per-vertex parent pointers, and how to recover a particular shortest path between any two vertices from the parent pointers. The explanation of BFS takes three forms: prose, pseudocode, and a working C program.
The paper also describes "Efficient BFS" (E-BFS), a simple variant of classic textbook BFS that improves its efficiency. In the asymptotic analysis, running time improves from Theta(V+E) to Omega(V). In words: classic BFS always runs in time proportional to the number of vertices plus the number of edges, whereas E-BFS sometimes runs in time proportional to the number of vertices alone, which can be much smaller. In practice E-BFS can be much faster, depending on the input graph. E-BFS sometimes offers no advantage over classic BFS but it's never much slower.
Remarkably, despites its simplicity E-BFS appears not to be widely known.
One thing to note, if you have a log4j.properties file on your classpath you do not need to call BasicConfigurator. A description of how to configure the properties file is here.
You could pinpoint whether your IDE is causing the issue by trying to run this class from the command line with log4j.jar and log4j.properties on your classpath.
There are two possible reasons for that error:
try to put your jquery code in document.ready, like this:
$(document).ready(function(){
....your code....
});
cheers
I had a similar problem and the solution was to do this:
#cloud-container{
position:absolute;
top:0;
bottom:0;
}
I wanted a page-centered div with height 100% of page height, so my total solution was:
#cloud-container{
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
width: XXXpx; /*otherwise div defaults to page width*/
margin: 0 auto; /*horizontally centers div*/
}
You might need to make a parent element (or simply 'body') have position: relative;
I use it like this in asp.net core 3.1
var url =Request.Scheme+"://"+ Request.Host.Value;
The problem is you typed the wrong file extension for excel file. you used .xsl instead of xls.
I know i came in late but it can help future readers of this post.
You need to add a new service for DBcontext
in the startup
Default
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
Add this
services.AddDbContext<NewDBContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("NewConnection")));
Voilà:
body {
background-color: #000; /*Default bg, similar to the background's base color*/
background-image: url("bg.png");
background-position: right bottom; /*Positioning*/
background-repeat: no-repeat; /*Prevent showing multiple background images*/
}
The background properties can be combined together, in one background property. See also: https://developer.mozilla.org/en/CSS/background-position
Anybody facing the same issues, follow the simple steps:
Import the project android
from downloaded zxing-master
zip file using option Import project (Eclipse ADT, Gradle, etc.)
and add the dollowing 2 lines of codes in your app level build.gradle
file and and you are ready to run.
So simple, yahh...
dependencies {
// https://mvnrepository.com/artifact/com.google.zxing/core
compile group: 'com.google.zxing', name: 'core', version: '3.2.1'
// https://mvnrepository.com/artifact/com.google.zxing/android-core
compile group: 'com.google.zxing', name: 'android-core', version: '3.2.0'
}
You can always find latest version core
and android core
from below links:
https://mvnrepository.com/artifact/com.google.zxing/core/3.2.1 https://mvnrepository.com/artifact/com.google.zxing/android-core/3.2.0
UPDATE (29.05.2019)
Add these dependencies instead:
dependencies {
implementation 'com.google.zxing:core:3.4.0'
implementation 'com.google.zxing:android-core:3.3.0'
}
Java EE is actually a collection of technologies and APIs for the Java platform designed to support "Enterprise" Applications which can generally be classed as large-scale, distributed, transactional and highly-available applications designed to support mission-critical business requirements.
In terms of what an employee is looking for in specific techs, it is quite hard to say, because the playing field has kept changing over the last five years. It really is about the class of problems that are being solved more than anything else. Transactions and distribution are key.
If anyone like me likes chainable data manipulation using the pandas dot notation (like piping), then the following may be useful:
df3 = df3.query('~index.duplicated()')
This enables chaining statements like this:
df3.assign(C=2).query('~index.duplicated()').mean()
Try this if you wan't to use SSL certificates:
import subprocess
try:
# Set scp and ssh data.
connUser = 'john'
connHost = 'my.host.com'
connPath = '/home/john/'
connPrivateKey = '/home/user/myKey.pem'
# Use scp to send file from local to host.
scp = subprocess.Popen(['scp', '-i', connPrivateKey, 'myFile.txt', '{}@{}:{}'.format(connUser, connHost, connPath)])
except CalledProcessError:
print('ERROR: Connection to host failed!')
You have to set Connection property of Command object and use parametersized query instead of hardcoded SQL to avoid SQL Injection.
using(SqlConnection openCon=new SqlConnection("your_connection_String"))
{
string saveStaff = "INSERT into tbl_staff (staffName,userID,idDepartment) VALUES (@staffName,@userID,@idDepartment)";
using(SqlCommand querySaveStaff = new SqlCommand(saveStaff))
{
querySaveStaff.Connection=openCon;
querySaveStaff.Parameters.Add("@staffName",SqlDbType.VarChar,30).Value=name;
.....
openCon.Open();
querySaveStaff.ExecuteNonQuery();
}
}
The specificity is calculated based on the amount of id, class and tag selectors in your rule. Id has the highest specificity, then class, then tag. Your first rule is now more specific than the second one, since they both have a class selector, but the first one also has two tag selectors.
To make the second one override the first one, you can make more specific by adding information of it's parents:
table.rule1 tr td.rule2 {
background-color: #ffff00;
}
Here is a nice article for more information on selector precedence.
check out System.Enum.Parse:
enum Colors {Red, Green, Blue}
// your code:
Colors color = (Colors)System.Enum.Parse(typeof(Colors), "Green");
I was having same problem.
Use @javax.persistence.Entity
instead of org.hibernate.annotations.Entity
The following will check whether an IP is valid or not: If the IP is within 0.0.0.0 to 255.255.255.255, then the output will be true, otherwise it will be false:
[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
Example:
your_ip = "10.10.10.10"
[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
Output:
>>> your_ip = "10.10.10.10"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
True
>>> your_ip = "10.10.10.256"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
False
>>>
From http://www.gnu.org/s/bash/manual/bash.html#Special-Parameters
?
Expands to the exit status of the most recently executed foreground pipeline.
I have started Activity A->B->C->D. When the back button is pressed on Activity D I want to go to Activity A. Since A is my starting point and therefore already on the stack all the activities in top of A is cleared and you can't go back to any other Activity from A.
This actually works in my code:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent a = new Intent(this,A.class);
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(a);
return true;
}
return super.onKeyDown(keyCode, event);
}
The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr)
instead of 1fr
as your track size.
Global variables are bad, if they allow you to manipulate aspects of a program that should be only modified locally. In OOP globals often conflict with the encapsulation-idea.
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.
Another alternative that only affects the current connection:
SET SESSION query_cache_type=0;
Use the below:
var regEx = new RegExp(pattern1+'|'+pattern2, 'gi');
str.match(regEx);
One solution you could use is to assign a more generalized class to any div you want the click event handler bound to.
For example:
HTML:
<body>
<div id="dog" class="selected" data-selected="false">dog</div>
<div id="cat" class="selected" data-selected="true">cat</div>
<div id="mouse" class="selected" data-selected="false">mouse</div>
<div class="dog"><img/></div>
<div class="cat"><img/></div>
<div class="mouse"><img/></div>
</body>
JS:
$( ".selected" ).each(function(index) {
$(this).on("click", function(){
// For the boolean value
var boolKey = $(this).data('selected');
// For the mammal value
var mammalKey = $(this).attr('id');
});
});
You can get the id of clicked one by this code
$("span").on("click",function(e){
console.log(e.target.Id);
});
Use .on()
event for future compatibility
I installed it by using a wheel file that can be found at this location: https://pypi.org/project/XlsxWriter/#files
I then ran pip install "XlsxWriter-1.2.8-py2.py3-none-any.whl"
Processing ./XlsxWriter-1.2.8-py2.py3-none-any.whl
Installing collected packages: XlsxWriter
Successfully installed XlsxWriter-1.2.8
For JEST users
if you use Jest for testing and this error happen just wrap your component with <BrowserRouter>
describe('Test suits for MyComponentWithLink', () => {
it('should match with snapshot', () => {
const tree = renderer
.create(
<BrowserRouter>
<MyComponentWithLink/>
</BrowserRouter>
)
.toJSON();
expect(tree).toMatchSnapshot();
});
});
For the best effect you have to use a custom (stretchable) background image. This is also how the UITextField
's rounded border is drawn.
a one line solution is to use the Z
symbol like:
new SimpleDateFormat(pattern, Locale.getDefault()).format(System.currentTimeMillis());
where pattern
could be:
full reference here:
http://developer.android.com/reference/java/text/SimpleDateFormat.html
The API can't be loaded after the document has finished loading by default, you'll need to load it asynchronous.
modify the page with the map:
<div id="map_canvas" style="height: 354px; width:713px;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
<script>
var directionsDisplay,
directionsService,
map;
function initialize() {
var directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = { zoom:7, mapTypeId: google.maps.MapTypeId.ROADMAP, center: chicago }
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
}
</script>
For more details take a look at: https://stackoverflow.com/questions/14184956/async-google-maps-api-v3-undefined-is-not-a-function/14185834#14185834
I recommend using glob to accomplish that task.
var glob = require( 'glob' )
, path = require( 'path' );
glob.sync( './routes/**/*.js' ).forEach( function( file ) {
require( path.resolve( file ) );
});
This always works fine for me:
for url in list_of_urls:
urls.setdefault(url, 0)
urls[url] += 1
For What its worth, this is what I did and maybe it can help others even though the article is old.
PHP:
session_start();
$_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR'];
if(isset($_SESSION['userID'])){
if(!strpos($_SESSION['activeID'], '-')){
$_SESSION['activeID'] = $_SESSION['userID'].'-'.$_SESSION['activeID'];
}
}elseif(!isset($_SESSION['activeID'])){
$_SESSION['activeID'] = time();
}
JS
window.setInterval(function(){
var userid = '<?php echo $_SESSION['activeID']; ?>';
var ipaddress = '<?php echo $_SESSION['ipaddress']; ?>';
var action = 'data';
$.ajax({
url:'activeUser.php',
method:'POST',
data:{action:action,userid:userid,ipaddress:ipaddress},
success:function(response){
//alert(response);
}
});
}, 5000);
Ajax call to activeUser.php
if(isset($_POST['action'])){
if(isset($_POST['userid'])){
$stamp = time();
$activeid = $_POST['userid'];
$ip = $_POST['ipaddress'];
$query = "SELECT stamp FROM activeusers WHERE activeid = '".$activeid."' LIMIT 1";
$results = RUNSIMPLEDB($query);
if($results->num_rows > 0){
$query = "UPDATE activeusers SET stamp = '$stamp' WHERE activeid = '".$activeid."' AND ip = '$ip' LIMIT 1";
RUNSIMPLEDB($query);
}else{
$query = "INSERT INTO activeusers (activeid,stamp,ip)
VALUES ('".$activeid."','$stamp','$ip')";
RUNSIMPLEDB($query);
}
}
}
Database:
CREATE TABLE `activeusers` (
`id` int(11) NOT NULL,
`activeid` varchar(20) NOT NULL,
`stamp` int(11) NOT NULL,
`ip` text
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Basically every 5 seconds the js will post to a php file that will track the user and the users ip address. Active users are simply a database record that have an update to the database time stamp within 5 seconds. Old users stop updating to the database. The ip address is used just to ensure that a user is unique so 2 people on the site at the same time don't register as 1 user.
Probably not the most efficient solution but it does the job.
You can use clip-path
, as Stewartside and Sviatoslav Oleksiv mentioned. To make things easy, I created a sass mixin:
@mixin cut-corners ($left-top, $right-top: 0px, $right-bottom: 0px, $left-bottom: 0px) {
clip-path: polygon($left-top 0%, calc(100% - #{$right-top}) 0%, 100% $right-top, 100% calc(100% - #{$right-bottom}), calc(100% - #{$right-bottom}) 100%, $left-bottom 100%, 0% calc(100% - #{$left-bottom}), 0% $left-top);
}
.cut-corners {
@include cut-corners(10px, 0, 25px, 50px);
}
A simple quick-and-dirty implementation of @Aaron answer:
document.body.innerHTML += '<form id="dynForm" action="http://example.com/" method="post"><input type="hidden" name="q" value="a"></form>';
document.getElementById("dynForm").submit();
Of course, you should rather use a JavaScript framework such as Prototype or jQuery...
In Swift 5 and Xcode 10.2
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: {
//Set status bar background colour
let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView
statusBar?.backgroundColor = UIColor.red
//Set navigation bar subView background colour
for view in controller.navigationController?.navigationBar.subviews ?? [] {
view.tintColor = UIColor.white
view.backgroundColor = UIColor.red
}
})
Here i fixed status bar background colour and navigation bar background colour. If you don't want navigation bar colour comment it.
Making it a primary key should also automatically create an index for it.
To get all the records where record created date is today's date Use the code after WHERE clause
WHERE CAST(Submission_date AS DATE) = CAST( curdate() AS DATE)
Aside: attempt to amend Tomasz Nurkiewicz's answer was rejected:
This edit does not make the post even a little bit easier to read, easier to find, more accurate or more accessible. Changes are either completely superfluous or actively harm readability.
Correct and permanent link to the relevant section of documentation about integration testing.
To enable support for transactions, you must configure a
PlatformTransactionManager
bean in theApplicationContext
that is loaded via@ContextConfiguration
semantics.
@Configuration @PropertySource("application.properties") public class Persistence { @Autowired Environment env; @Bean DataSource dataSource() { return new DriverManagerDataSource( env.getProperty("datasource.url"), env.getProperty("datasource.user"), env.getProperty("datasource.password") ); } @Bean PlatformTransactionManager transactionManager() { return new DataSourceTransactionManager(dataSource()); } }
In addition, you must declare Spring’s
@Transactional
annotation either at the class or method level for your tests.
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {Persistence.class, SomeRepository.class}) @Transactional public class SomeRepositoryTest { ... }
Annotating a test method with
@Transactional
causes the test to be run within a transaction that will, by default, be automatically rolled back after completion of the test. If a test class is annotated with@Transactional
, each test method within that class hierarchy will be run within a transaction.
You can simply return
if you want to skip the current iteration.
Since you're in a function, if you return
before doing anything else, then you have effectively skipped execution of the code below the return
statement.
Funny enough, a same problem I just met, and I get this work in following way:
combining with linux command ln
, we can make thing a lot simper:
1. cd Proj/Client
2. ln -s ../Common ./
3. cd Proj/Server
4. ln -s ../Common ./
And, now if you want to import some_stuff
from file: Proj/Common/Common.py
into your file: Proj/Client/Client.py
, just like this:
# in Proj/Client/Client.py
from Common.Common import some_stuff
And, the same applies to Proj/Server
, Also works for setup.py
process,
a same question discussed here, hope it helps !
This problem usually occurs when some process such as loading huge data to memory stream and your system memory is not capable of storing so much of data. Try clearing temp folder by giving the command
start -> run -> %temp%
Listview derives from listbox control. One most important difference is listview uses the extended selection mode by default . listview also adds a property called view which enables you to customize the view in a richer way than a custom itemspanel. One real life example of listview with gridview is file explorer's details view. Listview with grid view is a less powerful data grid. After the introduction of datagrid control listview lost its importance.
Python decorators add extra functionality to another function
An italics decorator could be like
def makeitalic(fn):
def newFunc():
return "<i>" + fn() + "</i>"
return newFunc
Note that a function is defined inside a function. What it basically does is replace a function with the newly defined one. For example, I have this class
class foo:
def bar(self):
print "hi"
def foobar(self):
print "hi again"
Now say, I want both functions to print "---" after and before they are done. I could add a print "---" before and after each print statement. But because I don't like repeating myself, I will make a decorator
def addDashes(fn): # notice it takes a function as an argument
def newFunction(self): # define a new function
print "---"
fn(self) # call the original function
print "---"
return newFunction
# Return the newly defined function - it will "replace" the original
So now I can change my class to
class foo:
@addDashes
def bar(self):
print "hi"
@addDashes
def foobar(self):
print "hi again"
For more on decorators, check http://www.ibm.com/developerworks/linux/library/l-cpdecor.html
In templates/admin/includes_grappelli/header.html, line 12, you forgot to put admin:password_change
between '
.
The url Django tag syntax should always be like:
{% url 'your_url_name' %}
If you want to kill the process that's listening on port 8080, you could use PowerShell. Just combine Get-NetTCPConnection
cmdlet with Stop-Process
.
Tested and should work with PowerShell 5 on Windows 10 or Windows Server 2016. However, I guess that it should also work on older Windows versions that have PowerShell 5 installed.
Here is an example:
PS C:\> Stop-Process -Id (Get-NetTCPConnection -LocalPort 8080).OwningProcess
Confirm
Are you sure you want to perform the Stop-Process operation on the following item: MyTestServer(9408)?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):
Here's generally how to select multiple columns from a subquery:
SELECT
A.SalesOrderID,
A.OrderDate,
SQ.Max_Foo,
SQ.Max_Foo2
FROM
A
LEFT OUTER JOIN
(
SELECT
B.SalesOrderID,
MAX(B.Foo) AS Max_Foo,
MAX(B.Foo2) AS Max_Foo2
FROM
B
GROUP BY
B.SalesOrderID
) AS SQ ON SQ.SalesOrderID = A.SalesOrderID
If what you're ultimately trying to do is get the values from the row with the highest value for Foo (rather than the max of Foo and the max of Foo2 - which is NOT the same thing) then the following will usually work better than a subquery:
SELECT
A.SalesOrderID,
A.OrderDate,
B1.Foo,
B1.Foo2
FROM
A
LEFT OUTER JOIN B AS B1 ON
B1.SalesOrderID = A.SalesOrderID
LEFT OUTER JOIN B AS B2 ON
B2.SalesOrderID = A.SalesOrderID AND
B2.Foo > B1.Foo
WHERE
B2.SalesOrderID IS NULL
You're basically saying, give me the row from B where I can't find any other row from B with the same SalesOrderID and a greater Foo.
Not surprisingly, this error can arise when another process is listening on the desired port. This happened today when I started an instance of the Apache Web server, listening on its default port (80), having forgotten that I already had IIS 7 running, and listening on that port. This is well explained in Port 80 is being used by SYSTEM (PID 4), what is that? Better yet, that article points to Stop http.sys from listening on port 80 in Windows, which explains a very simple way to resolve it, with just a tad of help from an elevated command prompt and a one-line edit of my hosts file.
I strongly recommend you learn how to use layout managers to get the layout you want to see. null
layouts are fragile, and cause no end of trouble.
Try this source & check the comments.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class VolumeCalculator extends JFrame implements ActionListener {
private JTabbedPane jtabbedPane;
private JPanel options;
JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
myTitle;
JTextArea labelTubStatus;
public VolumeCalculator(){
setSize(400, 250);
setVisible(true);
setSize(400, 250);
setVisible(true);
setTitle("Volume Calculator");
setSize(300, 200);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
createOptions();
jtabbedPane = new JTabbedPane();
jtabbedPane.addTab("Options", options);
topPanel.add(jtabbedPane, BorderLayout.CENTER);
}
/* CREATE OPTIONS */
public void createOptions(){
options = new JPanel();
//options.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
options.add(labelOptions);
JTextField newTitle = new JTextField("Some Title");
//newTitle.setBounds(80, 40, 225, 20);
options.add(newTitle);
myTitle = new JTextField(20);
// myTitle WAS NEVER ADDED to the GUI!
options.add(myTitle);
//myTitle.setBounds(80, 40, 225, 20);
//myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
//newName.setBounds(60, 80, 150, 20);
newName.addActionListener(this);
options.add(newName);
JButton Exit = new JButton("Exit");
//Exit.setBounds(250, 80, 80, 20);
Exit.addActionListener(this);
options.add(Exit);
}
public void actionPerformed(ActionEvent event){
JButton button = (JButton) event.getSource();
String buttonLabel = button.getText();
if ("Exit".equalsIgnoreCase(buttonLabel)){
Exit_pressed();
return;
}
if ("Set New Name".equalsIgnoreCase(buttonLabel)){
New_Name();
return;
}
}
private void Exit_pressed(){
System.exit(0);
}
private void New_Name(){
System.out.println("'" + myTitle.getText() + "'");
this.setTitle(myTitle.getText());
}
private void Options(){
}
public static void main(String[] args){
JFrame frame = new VolumeCalculator();
frame.pack();
frame.setSize(380, 350);
frame.setVisible(true);
}
}
I don't endorse this solution in any way, shape or form. But if you add a variable to the __builtin__
module, it will be accessible as if a global from any other module that includes __builtin__
-- which is all of them, by default.
a.py contains
print foo
b.py contains
import __builtin__
__builtin__.foo = 1
import a
The result is that "1" is printed.
Edit: The __builtin__
module is available as the local symbol __builtins__
-- that's the reason for the discrepancy between two of these answers. Also note that __builtin__
has been renamed to builtins
in python3.
Don't over complicate.
document.addEventListener('keydown', logKey);
function logKey(e) {
if (`${e.code}` == "ArrowRight") {
//code here
}
if (`${e.code}` == "ArrowLeft") {
//code here
}
if (`${e.code}` == "ArrowDown") {
//code here
}
if (`${e.code}` == "ArrowUp") {
//code here
}
}
Note: Posted this answer because OP later stated in comments that they need to select the last two elements, not just the second to last one.
The :nth-child
CSS3 selector is in fact more capable than you ever imagined!
For example, this will select the last 2 elements of #container
:
#container :nth-last-child(-n+2) {}
But this is just the beginning of a beautiful friendship.
#container :nth-last-child(-n+2) {
background-color: cyan;
}
_x000D_
<div id="container">
<div>a</div>
<div>b</div>
<div>SELECT THIS</div>
<div>SELECT THIS</div>
</div>
_x000D_
\t
in a string marks an escape sequence for a tab character. For a literal \
, use \\
.
Original from Sept. 13, 2015:
Quick and easy.
$.each(yourArray, function(index, value){
$('.element').html( $('.element').html() + '<span>' + value +'</span>')
});
Update Sept 9, 2019: No jQuery is needed to iterate the array.
yourArray.forEach((value) => {
$(".element").html(`${$(".element").html()}<span>${value}</span>`);
});
/* --- Or without jQuery at all --- */
yourArray.forEach((value) => {
document.querySelector(".element").innerHTML += `<span>${value}</span>`;
});
In very simple terms, I like to think about it like this:
real
is the actual amount of time it took to run the command (as if you had timed it with a stopwatch)
user
and sys
are how much 'work' the CPU
had to do to execute the command. This 'work' is expressed in units of time.
Generally speaking:
user
is how much work the CPU
did to run to run the command's codesys
is how much work the CPU
had to do to handle 'system overhead' type tasks (such as allocating memory, file I/O, ect.) in order to support the running commandSince these last two times are counting 'work' done, they don't include time a thread might have spent waiting (such as waiting on another process or for disk I/O to finish).
real
, however, is a measure of actual runtime and not 'work', so it does include any time spent waiting.
As the solutions above do not consider the possible overflow of doing max-min
when min
is negative, here another solution (similar to the one of kerouac)
public static int getRandom(int min, int max) {
if (min > max) {
throw new IllegalArgumentException("Min " + min + " greater than max " + max);
}
return (int) ( (long) min + Math.random() * ((long)max - min + 1));
}
this works even if you call it with:
getRandom(Integer.MIN_VALUE, Integer.MAX_VALUE)
Set specific tab index as active:
$(this).tabs({ active: # }); /* Where # is the tab index. The index count starts at 0 */
Set last tab as active
$(this).tabs({ active: -1 });
Set specific tab by ID:
$(this).tabs({ active: $('a[href="#tab-101"]').parent().index() });
The documentation on split()
says:
Splits this string around matches of the given regular expression.
(Emphasis mine.)
A dot is a special character in regular expression syntax. Use Pattern.quote()
on the parameter to split() if you want the split to be on a literal string pattern:
String[] words = temp.split(Pattern.quote("."));
If the logic parsing this knows that {"key": "slide0001.html", "value": "Looking Ahead"}
is a key/value pair, then you could transform it in an array and hold a few constants specifying which index maps to which key.
For example:
var data = ["slide0001.html", "Looking Ahead"];
var C_KEY = 0;
var C_VALUE = 1;
var value = data[C_VALUE];
So, now, your data can be:
[
["slide0001.html", "Looking Ahead"],
["slide0008.html", "Forecast"],
["slide0021.html", "Summary"]
]
If your parsing logic doesn't know ahead of time about the structure of the data, you can add some metadata to describe it. For example:
{ meta: { keys: [ "key", "value" ] },
data: [
["slide0001.html", "Looking Ahead"],
["slide0008.html", "Forecast"],
["slide0021.html", "Summary"]
]
}
... which would then be handled by the parser.
I was working on a program that required me to check if the user correctly answered how many digits were in a number, so i had to develop a way to check the amount of digits in an integer. It ended up being a relatively easy thing to solve.
double check=0, exponent=1000;
while(check<=1)
{
check=number/pow(10, exponent);
exponent--;
}
exponent=exponent+2;
cout<<exponent<<endl;
This ended up being my answer which currently works with numbers with less than 10^1000 digits (can be changed by changing the value of exponent).
P.S. I know this answer is ten years late but I got here on 2020 so other people might use it.
If you download the jquery easing plugin (check it out),then you just have to add this to your main.js file:
$('a.smooth-scroll').on('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top + 20
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
and also dont forget to add the smooth-scroll class to your a tags like this:
<li><a href="#about" class="smooth-scroll">About Us</a></li>
if you need to call a controller from a view, maybe to load a partial view, you thinking as modular programming, and you should implement HMVC structure in lieu of plane MVC. CodeIgniter didnt implement HMVC natively, but you can use this useful library in order to implement HMVC. https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc
after setup remember:that all your controllers should extends from MX_Controller in order to using this feature.
To install 32-bit Java on Windows 7 (64-bit OS + Machine). You can do:
1) Download JDK: http://javadl.sun.com/webapps/download/AutoDL?BundleId=58124
2) Download JRE: http://www.java.com/en/download/installed.jsp?jre_version=1.6.0_22&vendor=Sun+Microsystems+Inc.&os=Linux&os_version=2.6.41.4-1.fc15.i686
3) System variable create: C:\program files (x86)\java\jre6\bin\
4) Anywhere you type java -version
it use 32-bit on (64-bit). I have to use this because lots of third party libraries do not work with 64-bit. Java wake up from the hell, give us peach :P. Go-language is killer.
$(this).parents('div').attr('id');
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
I made an implementation based on @hister's one for my personal purposes, but using inheritance.
I hide the implementation details mechanisms (like add 1 to itemCount
, subtract 1 from position
) in an abstract super class HeadingableRecycleAdapter
, by
implementing required methods from Adapter like onBindViewHolder
, getItemViewType
and getItemCount
, making that methods final, and providing new methods with hidden logic to client:
onAddViewHolder(RecyclerView.ViewHolder holder, int position)
, onCreateViewHolder(ViewGroup parent)
,itemCount()
Here are the HeadingableRecycleAdapter
class and a client. I left the header layout a bit hard-coded because it fits my needs.
public abstract class HeadingableRecycleAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int HEADER_VIEW_TYPE = 0;
@LayoutRes
private int headerLayoutResource;
private String headerTitle;
private Context context;
public HeadingableRecycleAdapter(@LayoutRes int headerLayoutResourceId, String headerTitle, Context context) {
this.headerLayoutResource = headerLayoutResourceId;
this.headerTitle = headerTitle;
this.context = context;
}
public Context context() {
return context;
}
@Override
public final RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == HEADER_VIEW_TYPE) {
return new HeaderViewHolder(LayoutInflater.from(context).inflate(headerLayoutResource, parent, false));
}
return onCreateViewHolder(parent);
}
@Override
public final void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int viewType = getItemViewType(position);
if (viewType == HEADER_VIEW_TYPE) {
HeaderViewHolder vh = (HeaderViewHolder) holder;
vh.bind(headerTitle);
} else {
onAddViewHolder(holder, position - 1);
}
}
@Override
public final int getItemViewType(int position) {
return position == 0 ? 0 : 1;
}
@Override
public final int getItemCount() {
return itemCount() + 1;
}
public abstract int itemCount();
public abstract RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent);
public abstract void onAddViewHolder(RecyclerView.ViewHolder holder, int position);
}
@PerActivity
public class IngredientsAdapter extends HeadingableRecycleAdapter {
public static final String TITLE = "Ingredients";
private List<Ingredient> itemList;
@Inject
public IngredientsAdapter(Context context) {
super(R.layout.layout_generic_recyclerview_cardified_header, TITLE, context);
}
public void setItemList(List<Ingredient> itemList) {
this.itemList = itemList;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {
return new ViewHolder(LayoutInflater.from(context()).inflate(R.layout.item_ingredient, parent, false));
}
@Override
public void onAddViewHolder(RecyclerView.ViewHolder holder, int position) {
ViewHolder vh = (ViewHolder) holder;
vh.bind(itemList.get(position));
}
@Override
public int itemCount() {
return itemList == null ? 0 : itemList.size();
}
private String getQuantityFormated(double quantity, String measure) {
if (quantity == (long) quantity) {
return String.format(Locale.US, "%s %s", String.valueOf(quantity), measure);
} else {
return String.format(Locale.US, "%.1f %s", quantity, measure);
}
}
class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.text_ingredient)
TextView txtIngredient;
ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
void bind(Ingredient ingredient) {
String ingredientText = ingredient.getIngredient();
txtIngredient.setText(String.format(Locale.US, "%s %s ", getQuantityFormated(ingredient.getQuantity(),
ingredient.getMeasure()), Character.toUpperCase(ingredientText.charAt(0)) +
ingredientText
.substring(1)));
}
}
}
Not sure why these answers all dance around what I believe to be the right solution but for what it's worth here is what I use:
git config --global alias.coa "!git add -A && git commit -m"
git coa "A bunch of horrible changes"
NOTE: coa
is short for commit all and can be replaced with anything your heart desires
function invertSign($value)
{
return -$value;
}
Use the .css()
jQuery manipulators, or better yet just call .show()
/.hide()
on the image once you've obtained a handle to it (e.g. $('#img' + id)
).
BTW, you should not write javascript handlers with the "javascript:" prefix.
my working code to go back screen.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Toast.makeText(getApplicationContext(), "Home Clicked",
Toast.LENGTH_LONG).show();
// go to previous activity
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
The latest verion (I'm using 1.9.5) solve this problem by adding an option of "Break locks" on the clean up menu. Just make sure this check box is selected when doing clean up.
After struggling a bit with some of the answers here, I found a library called backoff that worked better for my situation. A basic example:
import backoff
@backoff.on_exception(
backoff.expo,
requests.exceptions.RequestException,
max_tries=5,
giveup=lambda e: e.response is not None and e.response.status_code < 500
)
def publish(self, data):
r = requests.post(url, timeout=10, json=data)
r.raise_for_status()
I'd still recommend giving the library's native functionality a shot, but if you run into any problems or need broader control, backoff is an option.
While the solution provided by @jmfenoll works, it updates to the latest packages. In my case, having installed beta2 (prerelease) it updated all of the libs to RC1 (which had a bug). Thus the above solution does only half of the job.
If you are in the same situation as I am and you would like to synchronize your project with the exact version of the NuGet packages you have/or specified in your packages.config
, then, then this script might help you. Simply copy&paste it into your Package Manager Console
function Sync-References([string]$PackageId) {
get-project -all | %{
$proj = $_ ;
Write-Host $proj.name;
get-package -project $proj.name | ? { $_.id -match $PackageId } | % {
Write-Host $_.id;
uninstall-package -projectname $proj.name -id $_.id -version $_.version -RemoveDependencies -force ;
install-package -projectname $proj.name -id $_.id -version $_.version
}
}
}
And then execute it either with a sepific package name like
Sync-References AutoMapper
or for all packages like
Sync-References
Credits go to Dan Haywood and his blog post.
I was facing the same issue. Run Windows PowerShell as Administrator. It resolved my issue.
Here's how you can do it in C#:
class Program
{
static void Main(string[] args)
{
if (File.Exists("test.db3"))
{
File.Delete("test.db3");
}
using (var connection = new SQLiteConnection("Data Source=test.db3;Version=3"))
using (var command = new SQLiteCommand("CREATE TABLE PHOTOS(ID INTEGER PRIMARY KEY AUTOINCREMENT, PHOTO BLOB)", connection))
{
connection.Open();
command.ExecuteNonQuery();
byte[] photo = new byte[] { 1, 2, 3, 4, 5 };
command.CommandText = "INSERT INTO PHOTOS (PHOTO) VALUES (@photo)";
command.Parameters.Add("@photo", DbType.Binary, 20).Value = photo;
command.ExecuteNonQuery();
command.CommandText = "SELECT PHOTO FROM PHOTOS WHERE ID = 1";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
byte[] buffer = GetBytes(reader);
}
}
}
}
static byte[] GetBytes(SQLiteDataReader reader)
{
const int CHUNK_SIZE = 2 * 1024;
byte[] buffer = new byte[CHUNK_SIZE];
long bytesRead;
long fieldOffset = 0;
using (MemoryStream stream = new MemoryStream())
{
while ((bytesRead = reader.GetBytes(0, fieldOffset, buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, (int)bytesRead);
fieldOffset += bytesRead;
}
return stream.ToArray();
}
}
}
you can use autocomplete="off" on parent form, so if you reload your page, checkboxes will not be checked automatically
Processing is always fun to play with and it creates things that are impressive to all types of people. For instance, a Brownian tree:
int xf = (int) random(width);
int yf = (int) random(height);
int x = (int) random(width);
int y = (int) random(height);
background(0xFF);
while(x != xf || y != yf) {
set(x,y,color(0,0,0));
x = max(0, min(x + -1 + (int) random(3), width - 1) );
y = max(0, min(y + -1 + (int) random(3), height - 1) );
}
This will add an image to another.
using (Graphics grfx = Graphics.FromImage(image))
{
grfx.DrawImage(newImage, x, y)
}
Graphics is in the namespace System.Drawing
You can also use ng-pattern ,[7-9] = > mobile number must start with 7 or 8 or 9 ,[0-9] = mobile number accepts digits ,{9} mobile number should be 10 digits.
function form($scope){_x000D_
$scope.onSubmit = function(){_x000D_
alert("form submitted");_x000D_
}_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>_x000D_
<div ng-app ng-controller="form">_x000D_
<form name="myForm" ng-submit="onSubmit()">_x000D_
<input type="number" ng-model="mobile_number" name="mobile_number" ng-pattern="/^[7-9][0-9]{9}$/" required>_x000D_
<span ng-show="myForm.mobile_number.$error.pattern">Please enter valid number!</span>_x000D_
<input type="submit" value="submit"/>_x000D_
</form>_x000D_
</div>
_x000D_
This gives a signed angle for any angles:
a = targetA - sourceA
a = (a + 180) % 360 - 180
Beware in many languages the modulo
operation returns a value with the same sign as the dividend (like C, C++, C#, JavaScript, full list here). This requires a custom mod
function like so:
mod = (a, n) -> a - floor(a/n) * n
Or so:
mod = (a, n) -> (a % n + n) % n
If angles are within [-180, 180] this also works:
a = targetA - sourceA
a += (a>180) ? -360 : (a<-180) ? 360 : 0
In a more verbose way:
a = targetA - sourceA
a -= 360 if a > 180
a += 360 if a < -180
Just in case...in r52 the method is called setEulerFromRotationMatrix
instead of getRotationFromMatrix
Some differences:
For Serialization there is no need of default constructor of that class because Object because JVM construct the same with help of Reflection API. In case of Externalization contructor with no arg is required, because the control is in hand of programmar and later on assign the deserialized data to object via setters.
In serialization if user want to skip certain properties to be serialized then has to mark that properties as transient, vice versa is not required for Externalization.
When backward compatiblity support is expected for any class then it is recommended to go with Externalizable. Serialization supports defaultObject persisting and if object structure is broken then it will cause issue while deserializing.
To get class name without mangling stuff you can use func macro in constructor:
class MyClass {
const char* name;
MyClass() {
name = __func__;
}
}
Use Except
:
var firstNotSecond = list1.Except(list2).ToList();
var secondNotFirst = list2.Except(list1).ToList();
I suspect there are approaches which would actually be marginally faster than this, but even this will be vastly faster than your O(N * M) approach.
If you want to combine these, you could create a method with the above and then a return statement:
return !firstNotSecond.Any() && !secondNotFirst.Any();
One point to note is that there is a difference in results between the original code in the question and the solution here: any duplicate elements which are only in one list will only be reported once with my code, whereas they'd be reported as many times as they occur in the original code.
For example, with lists of [1, 2, 2, 2, 3]
and [1]
, the "elements in list1 but not list2" result in the original code would be [2, 2, 2, 3]
. With my code it would just be [2, 3]
. In many cases that won't be an issue, but it's worth being aware of.
In my case, I'm using an AppBarLayout with a CollapsingToolbarLayout and the menu was always being scrolled out of the screen, I solved my problem by switching android:actionLayout in menu's XML to the toolbar's id. I hope it can help people in the same situation!
activity_main.xml
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:fab="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.MainScreenActivity"
android:screenOrientation="portrait">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="300dp"
app:elevation="0dp"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsingBar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="exitUntilCollapsed|scroll"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginStart="48dp"
app:expandedTitleMarginEnd="48dp"
>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:elevation="0dp"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:layout_collapseMode="pin"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
main_menu.xml
<?xml version="1.0" encoding="utf-8"?> <menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/logoutMenu"
android:orderInCategory="100"
android:title="@string/log_out"
app:showAsAction="never"
android:actionLayout="@id/toolbar"/>
<item
android:id="@+id/sortMenu"
android:orderInCategory="100"
android:title="@string/sort"
app:showAsAction="never"/> </menu>
For those like me who are brand new to this, here is code with const and an actual way to compare the byte[]'s. I got all of this code from stackoverflow but defined consts so values could be changed and also
// 24 = 192 bits
private const int SaltByteSize = 24;
private const int HashByteSize = 24;
private const int HasingIterationsCount = 10101;
public static string HashPassword(string password)
{
// http://stackoverflow.com/questions/19957176/asp-net-identity-password-hashing
byte[] salt;
byte[] buffer2;
if (password == null)
{
throw new ArgumentNullException("password");
}
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, SaltByteSize, HasingIterationsCount))
{
salt = bytes.Salt;
buffer2 = bytes.GetBytes(HashByteSize);
}
byte[] dst = new byte[(SaltByteSize + HashByteSize) + 1];
Buffer.BlockCopy(salt, 0, dst, 1, SaltByteSize);
Buffer.BlockCopy(buffer2, 0, dst, SaltByteSize + 1, HashByteSize);
return Convert.ToBase64String(dst);
}
public static bool VerifyHashedPassword(string hashedPassword, string password)
{
byte[] _passwordHashBytes;
int _arrayLen = (SaltByteSize + HashByteSize) + 1;
if (hashedPassword == null)
{
return false;
}
if (password == null)
{
throw new ArgumentNullException("password");
}
byte[] src = Convert.FromBase64String(hashedPassword);
if ((src.Length != _arrayLen) || (src[0] != 0))
{
return false;
}
byte[] _currentSaltBytes = new byte[SaltByteSize];
Buffer.BlockCopy(src, 1, _currentSaltBytes, 0, SaltByteSize);
byte[] _currentHashBytes = new byte[HashByteSize];
Buffer.BlockCopy(src, SaltByteSize + 1, _currentHashBytes, 0, HashByteSize);
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, _currentSaltBytes, HasingIterationsCount))
{
_passwordHashBytes = bytes.GetBytes(SaltByteSize);
}
return AreHashesEqual(_currentHashBytes, _passwordHashBytes);
}
private static bool AreHashesEqual(byte[] firstHash, byte[] secondHash)
{
int _minHashLength = firstHash.Length <= secondHash.Length ? firstHash.Length : secondHash.Length;
var xor = firstHash.Length ^ secondHash.Length;
for (int i = 0; i < _minHashLength; i++)
xor |= firstHash[i] ^ secondHash[i];
return 0 == xor;
}
In in your custom ApplicationUserManager, you set the PasswordHasher property the name of the class which contains the above code.
select name, games, goals
from tblMadrid where name = 'ronaldo'
union
select name, games, goals
from tblBarcelona where name = 'messi'
ORDER BY goals
You can of course format the result of current_timestamp()
.
Please have a look at the various formatting functions in the official documentation.
As others have answered, the mysqli API can execute multi-queries with the msyqli_multi_query() function.
For what it's worth, PDO supports multi-query by default, and you can iterate over the multiple result sets of your multiple queries:
$stmt = $dbh->prepare("
select sql_calc_found_rows * from foo limit 1 ;
select found_rows()");
$stmt->execute();
do {
while ($row = $stmt->fetch()) {
print_r($row);
}
} while ($stmt->nextRowset());
However, multi-query is pretty widely considered a bad idea for security reasons. If you aren't careful about how you construct your query strings, you can actually get the exact type of SQL injection vulnerability shown in the classic "Little Bobby Tables" XKCD cartoon. When using an API that restrict you to single-query, that can't happen.