You can use iterators:
Mat matrix = ...;
std::vector<float> vec(matrix.begin<float>(), matrix.end<float>());
I figured out that this behaves like a mousedown event:
button:active:hover {}
You can do this by adding a div i.e. centerBlock. And give this property in CSS to center the image or any content. Here is the code:
<div class="container">
<div class="row">
<div class="col-sm-4 col-md-4 col-lg-4">
<div class="centerBlock">
<img class="img-responsive" src="img/some-image.png" title="This image needs to be centered">
</div>
</div>
<div class="col-sm-8 col-md-8 col-lg-8">
Some content not important at this moment
</div>
</div>
</div>
// CSS
.centerBlock {
display: table;
margin: auto;
}
The easiest way is to redirect the output of the echo
by >>
:
echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile
try this
$directory = "mytheme/images/myimages";
$images = glob($directory . "/*.jpg");
foreach($images as $image)
{
echo $image;
}
Here is a simple answer in basically one line of code.
var value = 35 // the numerical value
var x = 5 // the minimum length of the string
var padded = ("00000" + value).substr(-x);
Make sure the number of characters in you padding, zeros here, is at least as many as your intended minimum length. So really, to put it into one line, to get a result of "00035" in this case is:
var padded = ("00000" + 35).substr(-5);
Use column-width property of css like below
<ul style="column-width:135px">
This error happen to me when push big amount of sources (Nearly 700Mb), then I try to push it partially and it was successfully pushed.
Strictly speaking, a unique nullable column (or set of columns) can be NULL (or a record of NULLs) only once, since having the same value (and this includes NULL) more than once obviously violates the unique constraint.
However, that doesn't mean the concept of "unique nullable columns" is valid; to actually implement it in any relational database we just have to bear in mind that this kind of databases are meant to be normalized to properly work, and normalization usually involves the addition of several (non-entity) extra tables to establish relationships between the entities.
Let's work a basic example considering only one "unique nullable column", it's easy to expand it to more such columns.
Suppose we the information represented by a table like this:
create table the_entity_incorrect
(
id integer,
uniqnull integer null, /* we want this to be "unique and nullable" */
primary key (id)
);
We can do it by putting uniqnull apart and adding a second table to establish a relationship between uniqnull values and the_entity (rather than having uniqnull "inside" the_entity):
create table the_entity
(
id integer,
primary key(id)
);
create table the_relation
(
the_entity_id integer not null,
uniqnull integer not null,
unique(the_entity_id),
unique(uniqnull),
/* primary key can be both or either of the_entity_id or uniqnull */
primary key (the_entity_id, uniqnull),
foreign key (the_entity_id) references the_entity(id)
);
To associate a value of uniqnull to a row in the_entity we need to also add a row in the_relation.
For rows in the_entity were no uniqnull values are associated (i.e. for the ones we would put NULL in the_entity_incorrect) we simply do not add a row in the_relation.
Note that values for uniqnull will be unique for all the_relation, and also notice that for each value in the_entity there can be at most one value in the_relation, since the primary and foreign keys on it enforce this.
Then, if a value of 5 for uniqnull is to be associated with an the_entity id of 3, we need to:
start transaction;
insert into the_entity (id) values (3);
insert into the_relation (the_entity_id, uniqnull) values (3, 5);
commit;
And, if an id value of 10 for the_entity has no uniqnull counterpart, we only do:
start transaction;
insert into the_entity (id) values (10);
commit;
To denormalize this information and obtain the data a table like the_entity_incorrect would hold, we need to:
select
id, uniqnull
from
the_entity left outer join the_relation
on
the_entity.id = the_relation.the_entity_id
;
The "left outer join" operator ensures all rows from the_entity will appear in the result, putting NULL in the uniqnull column when no matching columns are present in the_relation.
Remember, any effort spent for some days (or weeks or months) in designing a well normalized database (and the corresponding denormalizing views and procedures) will save you years (or decades) of pain and wasted resources.
SOURCE: https://git-scm.com/book/en/v2/Distributed-Git-Maintaining-a-Project#Integrating-Contributed-Work
The other way to move introduced work from one branch to another is to cherry-pick it. A cherry-pick in Git is like a rebase for a single commit. It takes the patch that was introduced in a commit and tries to reapply it on the branch you’re currently on. This is useful if you have a number of commits on a topic branch and you want to integrate only one of them, or if you only have one commit on a topic branch and you’d prefer to cherry-pick it rather than run rebase. For example, suppose you have a project that looks like this:
If you want to pull commit e43a6 into your master branch, you can run
$ git cherry-pick e43a6
Finished one cherry-pick.
[master]: created a0a41a9: "More friendly message when locking the index fails."
3 files changed, 17 insertions(+), 3 deletions(-)
This pulls the same change introduced in e43a6, but you get a new commit SHA-1 value, because the date applied is different. Now your history looks like this:
Now you can remove your topic branch and drop the commits you didn’t want to pull in.
The Replace string function will do that.
I think the choice between SortedSets/Lists and 'normal' sortable collections depends, whether you need sorting only for presentation purposes or at almost every point during runtime. Using a sorted collection may be much more expensive because the sorting is done everytime you insert an element.
If you can't opt for a collection in the JDK, you can take a look at the Apache Commons Collections
Try this:
From this question.
this.setState(
{
originId: input.originId,
destinationId: input.destinationId,
radius: input.radius,
search: input.search
},
function() { console.log("setState completed", this.state) }
)
this might be helpful
It seems that this can't be done, not at least with current versions of IE (6 and 7).
IE supports form attribute accept-charset, but only if its value is 'utf-8'.
The solution is to modify server A to produce encoding 'ISO-8859-1' for page that contains the form.
Ibrahim's comment on the other answer is the correct way to alter an existing user's home directory.
usermod -d /newhome/username username
usermod
is the command to edit an existing user.
-d
(abbreviation for --home
) will change the user's home directory.
usermod -m -d /newhome/username username
-m
(abbreviation for --move-home
) will move the content from the user's current directory to the new directory.
@dimas's answer is not logically consistent with your question; ifAllGranted
cannot be directly replaced with hasAnyRole
.
From the Spring Security 3—>4 migration guide:
Old:
<sec:authorize ifAllGranted="ROLE_ADMIN,ROLE_USER">
<p>Must have ROLE_ADMIN and ROLE_USER</p>
</sec:authorize>
New (SPeL):
<sec:authorize access="hasRole('ROLE_ADMIN') and hasRole('ROLE_USER')">
<p>Must have ROLE_ADMIN and ROLE_USER</p>
</sec:authorize>
Replacing ifAllGranted
directly with hasAnyRole
will cause spring to evaluate the statement using an OR
instead of an AND
. That is, hasAnyRole
will return true
if the authenticated principal contains at least one of the specified roles, whereas Spring's (now deprecated as of Spring Security 4) ifAllGranted
method only returned true
if the authenticated principal contained all of the specified roles.
TL;DR: To replicate the behavior of ifAllGranted
using Spring Security Taglib's new authentication Expression Language, the hasRole('ROLE_1') and hasRole('ROLE_2')
pattern needs to be used.
Once I found an xsd link on the top of the wsdl. Like this wsdl example from the web, you can see a link xsd1. The server has to be running to see it.
<?xml version="1.0"?>
<definitions name="StockQuote"
targetNamespace="http://example.com/stockquote.wsdl"
xmlns:tns="http://example.com/stockquote.wsdl"
xmlns:xsd1="http://example.com/stockquote.xsd"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns="http://schemas.xmlsoap.org/wsdl/">
I discovered today that you can use the stat
command to resolve paths.
So for a directory like "~/Documents":
You can run this:
stat -f %N ~/Documents
To get the full path:
/Users/me/Documents
For symlinks, you can use the %Y format option:
stat -f %Y example_symlink
Which might return a result like:
/usr/local/sbin/example_symlink
The formatting options might be different on other versions of *NIX but these worked for me on OSX.
For the record, this is documented in How do I add resources to my JAR? (illustrated for unit tests but the same applies for a "regular" resource):
To add resources to the classpath for your unit tests, you follow the same pattern as you do for adding resources to the JAR except the directory you place resources in is
${basedir}/src/test/resources
. At this point you would have a project directory structure that would look like the following:my-app |-- pom.xml `-- src |-- main | |-- java | | `-- com | | `-- mycompany | | `-- app | | `-- App.java | `-- resources | `-- META-INF | |-- application.properties `-- test |-- java | `-- com | `-- mycompany | `-- app | `-- AppTest.java `-- resources `-- test.properties
In a unit test you could use a simple snippet of code like the following to access the resource required for testing:
... // Retrieve resource InputStream is = getClass().getResourceAsStream("/test.properties" ); // Do something with the resource ...
If you don't mind getting a new data frame object returned as opposed to updating the original Pandas .assign() will avoid SettingWithCopyWarning
. Your example:
df = df.assign(B=df1['E'])
install certificate in java linux
/opt/jdk(version)/bin/keytool -import -alias aliasname -file certificate.cer -keystore cacerts -storepass password
I would say that way is more pythonic and fits on line:
If you need to check value only with the use of your function:
if filter( your_function, dictionary.values() ): ...
When you need to know if your dict contains any keys:
if dictionary: ...
Anyway, using loops here is not Python-way.
A rather obscure, yet potentially important case when layoutSubviews
never gets called is:
import UIKit
class View: UIView {
override class var layerClass: AnyClass { return Layer.self }
class Layer: CALayer {
override func layoutSublayers() {
// if we don't call super.layoutSublayers()...
print(type(of: self), #function)
}
}
override func layoutSubviews() {
// ... this method never gets called by the OS!
print(type(of: self), #function)
}
}
let view = View(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
The answer is in the JavaDoc of the equals()
method:
Unlike
compareTo
, this method considers twoBigDecimal
objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).
In other words: equals()
checks if the BigDecimal
objects are exactly the same in every aspect. compareTo()
"only" compares their numeric value.
As to why equals()
behaves this way, this has been answered in this SO question.
ng-init
is a directive that can be placed inside div
's, span
's, whatever, whereas onload
is an attribute specific to the ng-include
directive that functions as an ng-init
. To see what I mean try something like:
<span onload="a = 1">{{ a }}</span>
<span ng-init="b = 2">{{ b }}</span>
You'll see that only the second one shows up.
An isolated scope is a scope which does not prototypically inherit from its parent scope. In laymen's terms if you have a widget that doesn't need to read and write to the parent scope arbitrarily then you use an isolate scope on the widget so that the widget and widget container can freely use their scopes without overriding each other's properties.
Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.
So first you need to set up a class with some variables to get/set:
public class IDCard
{
private String mName;
private String mFileName;
private int mID;
}
But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:
IDCard test = new IDCard();
So - let's set up a default constructor, this is the method being called when you "instantiate" a class.
public IDCard()
{
mName = "";
mFileName = "";
mID = -1;
}
But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:
public IDCard(String name, int ID, String filename)
{
mName = name;
mID = ID;
mFileName = filename;
}
Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
Nice. Now we can access mName
. Add the rest of the accessors and mutators and you're now a certified Java newbie.
Good luck.
README.md
or .mkdn
or .markdown
denotes that the file is markdown formatted.
Markdown is a markup language. With it you can easily display headers or have italic words, or bold or almost anything that can be done to text
I think best way to avoid the OutOfMemoryError
is to face it and understand it.
I made an app to intentionally cause OutOfMemoryError
, and monitor memory usage.
After I've done a lot of experiments with this App, I've got the following conclusions:
I'm gonna talk about SDK versions before Honey Comb first.
Bitmap is stored in native heap, but it will get garbage collected automatically, calling recycle() is needless.
If {VM heap size} + {allocated native heap memory} >= {VM heap size limit for the device}, and you are trying to create bitmap, OOM will be thrown.
NOTICE: VM HEAP SIZE is counted rather than VM ALLOCATED MEMORY.
VM Heap size will never shrink after grown, even if the allocated VM memory is shrinked.
So you have to keep the peak VM memory as low as possible to keep VM Heap Size from growing too big to save available memory for Bitmaps.
Manually call System.gc() is meaningless, the system will call it first before trying to grow the heap size.
Native Heap Size will never shrink too, but it's not counted for OOM, so no need to worry about it.
Then, let's talk about SDK Starts from Honey Comb.
Bitmap is stored in VM heap, Native memory is not counted for OOM.
The condition for OOM is much simpler: {VM heap size} >= {VM heap size limit for the device}.
So you have more available memory to create bitmap with the same heap size limit, OOM is less likely to be thrown.
Here is some of my observations about Garbage Collection and Memory Leak.
You can see it yourself in the App. If an Activity executed an AsyncTask that was still running after the Activity was destroyed, the Activity will not get garbage collected until the AsyncTask finish.
This is because AsyncTask is an instance of an anonymous inner class, it holds a reference of the Activity.
Calling AsyncTask.cancel(true) will not stop the execution if the task is blocked in an IO operation in background thread.
Callbacks are anonymous inner classes too, so if a static instance in your project holds them and do not release them, memory would be leaked.
If you scheduled a repeating or delayed task, for example a Timer, and you do not call cancel() and purge() in onPause(), memory would be leaked.
You can only break
a block scope if you label it. For example:
myBlock: {
var a = 0;
break myBlock;
a = 1; // this is never run
};
a === 0;
You cannot break a block scope from within a function in the scope. This means you can't do stuff like:
foo: { // this doesn't work
(function() {
break foo;
}());
}
You can do something similar though with functions:
function myFunction() {myFunction:{
// you can now use break myFunction; instead of return;
}}
You need to trigger the onChange
event manually. On text inputs onChange listens for input
events.
So in you handleClick
function you need to trigger event like
handleClick () {
this.setState({value: 'another random text'})
var event = new Event('input', { bubbles: true });
this.myinput.dispatchEvent(event);
}
Complete code
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
value: 'random text'
}
}
handleChange (e) {
console.log('handle change called')
}
handleClick () {
this.setState({value: 'another random text'})
var event = new Event('input', { bubbles: true });
this.myinput.dispatchEvent(event);
}
render () {
return (
<div>
<input readOnly value={this.state.value} onChange={(e) => {this.handleChange(e)}} ref={(input)=> this.myinput = input}/>
<button onClick={this.handleClick.bind(this)}>Change Input</button>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))
Edit:
As Suggested by @Samuel in the comments, a simpler way would be to call handleChange
from handleClick
if you don't need to the event object
in handleChange
like
handleClick () {
this.setState({value: 'another random text'})
this.handleChange();
}
I hope this is what you need and it helps you.
Say the 1st date is in A1 cell
& the 2nd date is in B1 cell
Make sure that the cell type of both A1
& B1
is DATE
.
Then simply put the following formula in C1:
=A1-B1
The result of this formula may look funny to you.
Then Change the Cell type of C1
to GENERAL
.
It will give you the difference in Days.
You can also use this formula to get the remaining days of year or change the formula as you need:
=365-(A1-B1)
Hope this help
private bool isDate(Range cell)
{
if (cell.NumberFormat.ToString().Contains("/yy"))
{
return true;
}
return false;
}
isDate(worksheet.Cells[irow, icol])
1) I tried Broadcast Receiver approach as well even though I know CONNECTIVITY_ACTION/CONNECTIVITY_CHANGE is deprecated in API 28 and not recommended. Also bound to using explicit register, it listens as long as app is running.
2) I also tried Firebase Dispatcher which works but not beyond app killed.
3) Recommended way found is WorkManager to guarantee execution beyond process killed and internally using registerNetworkRequest()
The biggest evidence in favor of #3 approach is referred by Android doc itself. Especially for apps in the background.
Also here
In Android 7.0 we're removing three commonly-used implicit broadcasts — CONNECTIVITY_ACTION, ACTION_NEW_PICTURE, and ACTION_NEW_VIDEO — since those can wake the background processes of multiple apps at once and strain memory and battery. If your app is receiving these, take advantage of the Android 7.0 to migrate to JobScheduler and related APIs instead.
So far it works fine for us using Periodic WorkManager request.
Update: I ended up writing 2 series medium post about it.
In the question above the right answer would be to use Mock
, or to be more precise create_autospec
(because it will add spec to the mock methods of the class you are mocking), the defined spec
on the mock will be helpful in case of an attempt to call method of the class which doesn't exists ( regardless signature), please see some
from unittest import TestCase
from unittest.mock import Mock, create_autospec, patch
class MyClass:
@staticmethod
def method(foo, bar):
print(foo)
def something(some_class: MyClass):
arg = 1
# Would fail becuase of wrong parameters passed to methd.
return some_class.method(arg)
def second(some_class: MyClass):
arg = 1
return some_class.unexisted_method(arg)
class TestSomethingTestCase(TestCase):
def test_something_with_autospec(self):
mock = create_autospec(MyClass)
mock.method.return_value = True
# Fails because of signature misuse.
result = something(mock)
self.assertTrue(result)
self.assertTrue(mock.method.called)
def test_something(self):
mock = Mock() # Note that Mock(spec=MyClass) will also pass, because signatures of mock don't have spec.
mock.method.return_value = True
result = something(mock)
self.assertTrue(result)
self.assertTrue(mock.method.called)
def test_second_with_patch_autospec(self):
with patch(f'{__name__}.MyClass', autospec=True) as mock:
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
class TestSecondTestCase(TestCase):
def test_second_with_autospec(self):
mock = Mock(spec=MyClass)
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
def test_second_with_patch_autospec(self):
with patch(f'{__name__}.MyClass', autospec=True) as mock:
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
def test_second(self):
mock = Mock()
mock.unexisted_method.return_value = True
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
The test cases with defined spec used fail because methods called from something
and second
functions aren't complaint with MyClass, which means - they catch bugs, whereas default Mock
will display.
As a side note there is one more option: use patch.object to mock just the class method which is called with.
The good use cases for patch would be the case when the class is used as inner part of function:
def something():
arg = 1
return MyClass.method(arg)
Then you will want to use patch as a decorator to mock the MyClass.
Look here: http://en.cppreference.com/w/cpp/algorithm/sort.
It says:
template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
bool cmp(const Type1 &a, const Type2 &b);
Also, here's an example of how you can use std::sort
using a custom C++14 polymorphic lambda:
std::sort(std::begin(container), std::end(container),
[] (const auto& lhs, const auto& rhs) {
return lhs.first < rhs.first;
});
I just noticed that if you do:
monthCalendar1.SelectionRange.Start.ToShortDateString()
you will get only the date (e.g. 1/25/2014
) from a MonthCalendar
control.
It's opposite to:
monthCalendar1.SelectionRange.Start.ToString()
//The OUTPUT will be (e.g. 1/25/2014 12:00:00 AM)
Because these MonthCalendar
properties are of type DateTime. See the msdn and the methods available to convert to a String representation. Also this may help to convert from a String to a DateTime object where applicable.
very old post. but i'll just leave this here:
/* converts a number with byte unit (B / K / M / G) into an integer */
function unitToInt($s)
{
return (int)preg_replace_callback('/(\-?\d+)(.?)/', function ($m) {
return $m[1] * pow(1024, strpos('BKMG', $m[2]));
}, strtoupper($s));
}
$mem_limit = unitToInt(ini_get('memory_limit'));
list is mutable
Change
last_list=last_list.append(p.last_name)
to
last_list.append(p.last_name)
will work
Just use a onchnage Event
for select box.
<select id="selectbox" name="" onchange="javascript:location.href = this.value;">
<option value="https://www.yahoo.com/" selected>Option1</option>
<option value="https://www.google.co.in/">Option2</option>
<option value="https://www.gmail.com/">Option3</option>
</select>
And if selected option to be loaded at the page load then add some javascript code
<script type="text/javascript">
window.onload = function(){
location.href=document.getElementById("selectbox").value;
}
</script>
for jQuery: Remove the onchange event from <select>
tag
jQuery(function () {
// remove the below comment in case you need chnage on document ready
// location.href=jQuery("#selectbox").val();
jQuery("#selectbox").change(function () {
location.href = jQuery(this).val();
})
})
From the bottom of the ?mutate_each
(at least in dplyr 0.5) it looks like that function, as in @docendo discimus's answer, will be deprecated and replaced with more flexible alternatives mutate_if
, mutate_all
, and mutate_at
. The one most similar to what @hadley mentions in his comment is probably using mutate_at
. Note the order of the arguments is reversed, compared to mutate_each
, and vars()
uses select()
like semantics, which I interpret to mean the ?select_helpers
functions.
dat %>% mutate_at(vars(starts_with("fac")),funs(factor)) %>%
mutate_at(vars(starts_with("dbl")),funs(as.numeric))
But mutate_at
can take column numbers instead of a vars()
argument, and after reading through this page, and looking at the alternatives, I ended up using mutate_at
but with grep
to capture many different kinds of column names at once (unless you always have such obvious column names!)
dat %>% mutate_at(grep("^(fac|fctr|fckr)",colnames(.)),funs(factor)) %>%
mutate_at(grep("^(dbl|num|qty)",colnames(.)),funs(as.numeric))
I was pretty excited about figuring out mutate_at
+ grep
, because now one line can work on lots of columns.
EDIT - now I see matches()
in among the select_helpers, which handles regex, so now I like this.
dat %>% mutate_at(vars(matches("fac|fctr|fckr")),funs(factor)) %>%
mutate_at(vars(matches("dbl|num|qty")),funs(as.numeric))
Another generally-related comment - if you have all your date columns with matchable names, and consistent formats, this is powerful. In my case, this turns all my YYYYMMDD columns, which were read as numbers, into dates.
mutate_at(vars(matches("_DT$")),funs(as.Date(as.character(.),format="%Y%m%d")))
you can use something like this :
string [] filePaths = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
instead of using "." you can type the name of the file or just the type like "*.txt" also SearchOption.AllDirectories is to search in all subfolders you can change that if you only want one level more about how to use it on here
Above answers are pretty sufficient. Additional to the onChange
, if you upload a file using drag and drop events, you can get the file in drop
event by accessing eventArgs.dataTransfer.files
.
Use a terminal-handling library like the curses module:
The curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling.
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.
There are different types of joins available in SQL:
INNER JOIN: returns rows when there is a match in both tables.
LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.
RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.
FULL JOIN: It combines the results of both left and right outer joins.
The joined table will contain all records from both the tables and fill in NULLs for missing matches on either side.
SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.
CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined tables.
WE can take each first four joins in Details :
We have two tables with the following values.
TableA
id firstName lastName
.......................................
1 arun prasanth
2 ann antony
3 sruthy abc
6 new abc
TableB
id2 age Place
................
1 24 kerala
2 24 usa
3 25 ekm
5 24 chennai
....................................................................
INNER JOIN
Note :it gives the intersection of the two tables, i.e. rows they have common in TableA and TableB
Syntax
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
INNER JOIN TableB
ON TableA.id = TableB.id2;
Result Will Be
firstName lastName age Place
..............................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
LEFT JOIN
Note : will give all selected rows in TableA, plus any common selected rows in TableB.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
LEFT JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
LEFT JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
new abc NULL NULL
RIGHT JOIN
Note : will give all selected rows in TableB, plus any common selected rows in TableA.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
RIGHT JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
NULL NULL 24 chennai
FULL JOIN
Note :It will return all selected values from both tables.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
FULL JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
new abc NULL NULL
NULL NULL 24 chennai
Interesting Fact
For INNER joins the order doesn't matter
For (LEFT, RIGHT or FULL) OUTER joins,the order matter
Better to go check this Link it will give you interesting details about join order
Looking at the sample I guess you mean that a string array is actually an array of HEX representation of bytes, don't you?
If yes, then for each string item I would do the following:
build a byte value, where first char is higher bits and second char is lower ones. E.g.
int byteVal = (firstCharNumber << 4) | secondCharNumber;
You may use:
To create array of objects:
var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.map(value => ({[value]: 0}));_x000D_
_x000D_
console.log(result);
_x000D_
Or if you wants to create a single object from values of arrays:
var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});_x000D_
_x000D_
console.log(result);
_x000D_
In Javascript you can do the following:
Object.keys(ahash)[0];
Bash 4 has a coproc
command which establishes a named pipe to a command and allows you to communicate through it.
For starters,
mysql_connect() should not have a $ accompanying it; it is not a variable, it is a predefined function. Remove the $ to properly connect to the database.
Why do you have an XML tag at the top of this document? This is HTML/PHP - a HTML doctype should suffice.
From line 215, update:
if (isset($_POST)) {
$Name = $_POST['Name'];
$Surname = $_POST['Surname'];
$Username = $_POST['Username'];
$Email = $_POST['Email'];
$C_Email = $_POST['C_Email'];
$Password = $_POST['password'];
$C_Password = $_POST['c_password'];
$SecQ = $_POST['SecQ'];
$SecA = $_POST['SecA'];
}
POST variables are coming from your form, and you have to check whether they exist or not, else PHP will give you a NOTICE error. You can disable these notices by placing error_reporting(0); at the top of your document. It's best to keep these visible for development purposes.
You should only be interacting with the database (inserting, checking) under the condition that the form has been submitted. If you do not, PHP will run all of these operations without any input from the user. Its best to use an IF statement, like so:
if (isset($_POST['submit']) {
// blah blah
// check if user exists, check if fields are blank
// insert the user if all of this stuff checks out..
} else {
// just display the form
}
Awesome form tutorial: http://php.about.com/od/learnphp/ss/php_forms.htm
You can use:
width: -webkit-fit-content;
height: -webkit-fit-content;
width: -moz-fit-content;
height: -moz-fit-content;
EDIT: No. see http://red-team-design.com/horizontal-centering-using-css-fit-content-value/
One thing you can do is get rid of all those onclick attributes and do it the right way with bootstrap. You don't need to open them manually; you can specify the trigger and even subscribe to events before the modal opens so that you can do your operations and populate data in it.
I am just going to show as a static example which you can accommodate in your real world.
On each of your <tr>
's add a data attribute for id
(i.e. data-id
) with the corresponding id value and specify a data-target
, which is a selector you specify, so that when clicked, bootstrap will select that element as modal dialog and show it. And then you need to add another attribute data-toggle=modal
to make this a trigger for modal.
<tr data-toggle="modal" data-id="1" data-target="#orderModal">
<td>1</td>
<td>24234234</td>
<td>A</td>
</tr>
<tr data-toggle="modal" data-id="2" data-target="#orderModal">
<td>2</td>
<td>24234234</td>
<td>A</td>
</tr>
<tr data-toggle="modal" data-id="3" data-target="#orderModal">
<td>3</td>
<td>24234234</td>
<td>A</td>
</tr>
And now in the javascript just set up the modal just once and event listen to its events so you can do your work.
$(function(){
$('#orderModal').modal({
keyboard: true,
backdrop: "static",
show:false,
}).on('show', function(){ //subscribe to show method
var getIdFromRow = $(event.target).closest('tr').data('id'); //get the id from tr
//make your ajax call populate items or what even you need
$(this).find('#orderDetails').html($('<b> Order Id selected: ' + getIdFromRow + '</b>'))
});
});
Do not use inline click attributes any more. Use event bindings instead with vanilla js or using jquery.
Alternative ways here:
It depends on what database you are using. In MySQL, you would use the "ALTER TABLE" syntax. I don't remember exactly how, but it would go something like this if you wanted to add a column called 'newcol' that was a 200 character varchar:
ALTER TABLE example ADD newCol VARCHAR(200) AFTER otherCol;
You can use an IF statement to check the referenced cell(s) and return one result for zero or blank, and otherwise return your formula result.
A simple example:
=IF(B1=0;"";A1/B1)
This would return an empty string if the divisor B1 is blank or zero; otherwise it returns the result of dividing A1 by B1.
In your case of running an average, you could check to see whether or not your data set has a value:
=IF(SUM(K23:M23)=0;"";AVERAGE(K23:M23))
If there is nothing entered, or only zeros, it returns an empty string; if one or more values are present, you get the average.
You normally end a batch file with a line that just says exit
. If you want to make sure the file has run and the DOS window closes after 2 seconds, you can add the lines:
timeout 2 >nul
exit
But the exit
command will not work if your batch file opens another window, because while ever the second window is open the old DOS window will also be displayed.
SOLUTION: For example there's a great little free program called BgInfo which will display all the info about your computer. Assuming it's in a directory called C:\BgInfo
, to run it from a batch file with the /popup
switch and to close the DOS window while it still runs, use:
start "" "C:\BgInfo\BgInfo.exe" /popup
exit
Because you're trying to add a click event to a submit input you will need to prevent the normal flow that this will do that is submit the form.
You can also use $(document).ready()
But since you have your script tag at the end of the page the DOM is already loaded.
To prevent the default you will need something like this:
$("form").on('submit',function(e){
e.preventDefault();
$("#dsf").val("changed value")
})
If the element wasn't a submit input it will be as simple as
$("#cd").click(function(){
$("#dsf").val("changed value")
})
See this Fiddle
More detailed information are available in the platform
module.
Shift + Alt + J will help you add author name in existing file.
To add author name automatically,
go to Preferences --> java --> Code Style --> Code Templates
in case you don't find above option in new versions of Eclipse - install it from https://marketplace.eclipse.org/content/jautodoc
Use Linq's Union:
using System.Linq;
var l1 = new List<int>() { 1,2,3,4,5 };
var l2 = new List<int>() { 3,5,6,7,8 };
var l3 = l1.Union(l2).ToList();
If i understood correctly the easiest way is to use regular expression as it provides you lots of flexibility but the other simple method is to use for loop following is the code with example I also counted the occurrence of word and stored in dictionary..
s = """An... essay is, generally, a piece of writing that gives the author's own
argument — but the definition is vague,
overlapping with those of a paper, an article, a pamphlet, and a short story. Essays
have traditionally been
sub-classified as formal and informal. Formal essays are characterized by "serious
purpose, dignity, logical
organization, length," whereas the informal essay is characterized by "the personal
element (self-revelation,
individual tastes and experiences, confidential manner), humor, graceful style,
rambling structure, unconventionality
or novelty of theme," etc.[1]"""
d = {} # creating empty dic
words = s.split() # spliting string and stroing in list
for word in words:
new_word = ''
for c in word:
if c.isalnum(): # checking if indiviual chr is alphanumeric or not
new_word = new_word + c
print(new_word, end=' ')
# if new_word not in d:
# d[new_word] = 1
# else:
# d[new_word] = d[new_word] +1
print(d)
please rate this if this answer is useful!
This sounds like a bad clone. You could try the following to get (possibly?) more information:
git fsck --full
I had the following error message Port 80 in use by "Unable to open process" with PID 4! Apache WILL NOT start without the configured ports free! You need to uninstall/disable/reconfigure the blocking application or reconfigure Apache and the Control Panel to listen on a different port Starting Check-Timer Control Panel Ready
opened the httpd.conf and changed the listen port from 80 to 1234 in both places
Listen 1234
Then go to Config for the xampp control panel and go to service and port setting and changed the port from 80 to 1234
That worked.
A simple call back program. Hope it answers your question.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include "../../common_typedef.h"
typedef void (*call_back) (S32, S32);
void test_call_back(S32 a, S32 b)
{
printf("In call back function, a:%d \t b:%d \n", a, b);
}
void call_callback_func(call_back back)
{
S32 a = 5;
S32 b = 7;
back(a, b);
}
S32 main(S32 argc, S8 *argv[])
{
S32 ret = SUCCESS;
call_back back;
back = test_call_back;
call_callback_func(back);
return ret;
}
I found the solution thanks to the link in Vincent's answer.
\renewcommand{\familydefault}{\sfdefault}
This changes the default font family to sans-serif.
Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.
http://www.rgagnon.com/javadetails/java-0542.html
Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.
package filesendtest;
import java.io.*;
import java.net.*;
class TCPServer {
private final static String fileToSend = "C:\\test1.pdf";
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File( fileToSend );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
package filesendtest;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
private final static String serverIP = "127.0.0.1";
private final static int serverPort = 3248;
private final static String fileOutput = "C:\\testout.pdf";
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket( serverIP , serverPort );
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream( fileOutput );
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
Related
Byte array of unknown length in java
Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):
public static String md5String(File file) {
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0) {
md5er.update(buffer, 0, read);
}
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null) {
return null;
}
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
} catch (Exception e) {
return null;
}
}
I use this little function for VBA.
Public Function Pause(NumberOfSeconds As Variant)
On Error GoTo Error_GoTo
Dim PauseTime As Variant
Dim Start As Variant
Dim Elapsed As Variant
PauseTime = NumberOfSeconds
Start = Timer
Elapsed = 0
Do While Timer < Start + PauseTime
Elapsed = Elapsed + 1
If Timer = 0 Then
' Crossing midnight
PauseTime = PauseTime - Elapsed
Start = 0
Elapsed = 0
End If
DoEvents
Loop
Exit_GoTo:
On Error GoTo 0
Exit Function
Error_GoTo:
Debug.Print Err.Number, Err.Description, Erl
GoTo Exit_GoTo
End Function
You are not adding the object to the session, instead you are adding it to the request.
What you need is:
HttpSession session = request.getSession();
session.setAttribute("MySessionVariable", param);
In Servlets you have 4 scopes where you can store data.
Make sure you understand these. For more look here
lscpu
will list out these among other information regarding your CPU:
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
...
The accepted answer lead me to believe that decoupling Django backend and React Frontend is the right way to go no matter what. In fact there are approaches in which React and Django are coupled, which may be better suited in particular situations.
This tutorial well explains this. In particular:
I see the following patterns (which are common to almost every web framework):
-React in its own “frontend” Django app: load a single HTML template and let React manage the frontend (difficulty: medium)
-Django REST as a standalone API + React as a standalone SPA (difficulty: hard, it involves JWT for authentication)
-Mix and match: mini React apps inside Django templates (difficulty: simple)
Solution: Disable this warning in Eclipse. Don't @SuppressWarnings it, just disable it completely.
Several of the "solutions" presented above are way out of line, making code unreadable for the sake of suppressing a silly warning.
You can try sudo apt-get upgrade
to get the latest packages. It fixed the issue on my machine.
iPhone format strings are in Unicode format. Behind the link is a table explaining what all the letters above mean so you can build your own.
And of course don't forget to release your date formatters when you're done with them. The above code leaks format
, now
, and inFormat
.
This is very simple, you just need to add a background image to the select element and position it where you need to, but don't forget to add:
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
According to http://shouldiprefix.com/#appearance
Microsoft Edge and IE mobile support this property with the -webkit- prefix rather than -ms- for interop reasons.
I just made this fiddle http://jsfiddle.net/drjorgepolanco/uxxvayqe/
This was a good waste of an hour of my time. For you eager beavers, the following format worked for me:
<input type="datetime-local" name="to" id="to" value="2014-12-08T15:43:00">
The spec was a little confusing to me, it said to use RFC 3339, but on my PHP server when I used the format DATE_RFC3339 it wasn't initializing my hmtl input :( PHP's constant for DATE_RFC3339 is "Y-m-d\TH:i:sP" at the time of writing, it makes sense that you should get rid of the timezone info (we're using datetime-LOCAL, folks). So the format that worked for me was:
"Y-m-d\TH:i:s"
I would've thought it more intuitive to be able to set the value of the datepicker as the datepicker displays the date, but I'm guessing the way it is displayed differs across browsers.
Use suppressWarnings()
:
suppressWarnings(as.numeric(c("1", "2", "X")))
[1] 1 2 NA
This suppresses warnings.
You can also install Fiddler (http://www.fiddler2.com/fiddler2/) which is very easy to install (easier than Apache for example).
After launching it, it will register itself as system proxy. Then open the "Rules" menu, and choose "Customize Rules..." to open a JScript file which allow you to customize requests.
To add a custom header, just add a line in the OnBeforeRequest
function:
oSession.oRequest.headers.Add("MyHeader", "MyValue");
From the Python documentation:
And while the module doesn’t directly support parsing strings, it can easily be done:
import csv
for row in csv.reader(['one,two,three']):
print row
Just drop your string data into a singleton list.
You can use a method proposed by @Yar (with some modification):
#define mustOverride() @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"%s must be overridden in a subclass/category", __PRETTY_FUNCTION__] userInfo:nil]
#define setMustOverride() NSLog(@"%@ - method not implemented", NSStringFromClass([self class])); mustOverride()
Here you will get a message like:
<Date> ProjectName[7921:1967092] <Class where method not implemented> - method not implemented
<Date> ProjectName[7921:1967092] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[<Base class (if inherited or same if not> <Method name>] must be overridden in a subclass/category'
Or assertion:
NSAssert(![self respondsToSelector:@selector(<MethodName>)], @"Not implemented");
In this case you will get:
<Date> ProjectName[7926:1967491] *** Assertion failure in -[<Class Name> <Method name>], /Users/kirill/Documents/Projects/root/<ProjectName> Services/Classes/ViewControllers/YourClass:53
Also you can use protocols and other solutions - but this is one of the simplest ones.
There are padding built into various classes.
For example:
A asp.net web forms app:
<asp:CheckBox ID="chkShowDeletedServers" runat="server" AutoPostBack="True" Text="Show Deleted" />
this code above would place the Text of "Show Deleted" too close to the checkbox to what I see at nice to look at.
However with bootstrap
<div class="checkbox-inline">
<asp:CheckBox ID="chkShowDeletedServers" runat="server" AutoPostBack="True" Text="Show Deleted" />
</div>
This created the space, if you don't want the text bold, that class=checkbox
Bootstrap is very flexible, so in this case I don't need a hack, but sometimes you need to.
Had the same problem. I was passing a non-const reference of custom class and the constructor complained (some tuple template errors). Replaced the reference with pointer and it worked.
Although the accepted answer works fine, since v0.21.0rc1 it gives a warning
UserWarning: Pandas doesn't allow columns to be created via a new attribute name
Instead, one can do
df[["X", "A", "B", "C"]].plot(x="X", kind="bar")
g++ test.cpp LinearNode.cpp LinkedList.cpp -o test
Besides the fact that Python has built in support for dates and times (see bigmattyh's response), finding minutes or hours from seconds is easy:
minutes = seconds / 60
hours = minutes / 60
Now, when you want to display minutes or seconds, MOD them by 60 so that they will not be larger than 59
just add display: inline-block; property and removed width.
checkout this article :http://www.morgantechspace.com/2013/08/convert-object-to-byte-array-and-vice.html
Use the below code
// Convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
{
if(obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
// Convert a byte array to an Object
private Object ByteArrayToObject(byte[] arrBytes)
{
MemoryStream memStream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
Object obj = (Object) binForm.Deserialize(memStream);
return obj;
}
Also, you can add the following line to the _Layout.cshtml
or _Layout.Mobile.cshtml
:
@RenderSection("scripts", required: false)
It reads Hello World
(cat
), replaces all (g
) occurrences of %
by $
and (over)writes it to /etc/init.d/dropbox
as root.
For s: When used with printf functions, specifies a single-byte or multi-byte character string; when used with wprintf functions, specifies a wide-character string. Characters are displayed up to the first null character or until the precision value is reached.
For S: When used with printf functions, specifies a wide-character string; when used with wprintf functions, specifies a single-byte or multi-byte character string. Characters are displayed up to the first null character or until the precision value is reached.
In Unix-like platform, s and S have the same meaning as windows platform.
Reference: https://msdn.microsoft.com/en-us/library/hf4y5e3w.aspx
I've just tested a few browsers using this silly bit of JavaScript:
function log_newline(msg, test_value) {_x000D_
if (!test_value) { _x000D_
test_value = document.getElementById('test').value;_x000D_
}_x000D_
console.log(msg + ': ' + (test_value.match(/\r/) ? 'CR' : '')_x000D_
+ ' ' + (test_value.match(/\n/) ? 'LF' : ''));_x000D_
}_x000D_
_x000D_
log_newline('HTML source');_x000D_
log_newline('JS string', "foo\nbar");_x000D_
log_newline('JS template literal', `bar_x000D_
baz`);
_x000D_
<textarea id="test" name="test">_x000D_
_x000D_
</textarea>
_x000D_
IE8 and Opera 9 on Windows use \r\n
. All the other browsers I tested (Safari 4 and Firefox 3.5 on Windows, and Firefox 3.0 on Linux) use \n
. They can all handle \n
just fine when setting the value, though IE and Opera will convert that back to \r\n
again internally. There's a SitePoint article with some more details called Line endings in Javascript.
Note also that this is independent of the actual line endings in the HTML file itself (both \n
and \r\n
give the same results).
When submitting a form, all browsers canonicalize newlines to %0D%0A
in URL encoding. To see that, load e.g. data:text/html,<form><textarea name="foo">foo%0abar</textarea><input type="submit"></form>
and press the submit button. (Some browsers block the load of the submitted page, but you can see the URL-encoded form values in the console.)
I don't think you really need to do much of any determining, though. If you just want to split the text on newlines, you could do something like this:
lines = foo.value.split(/\r\n|\r|\n/g);
For me the issue seems to have been caused by power failure. Restarting the server computer solved it.
I had the same problem when trying to implement 'now typing' on chat app. try to extend EditText as follows:
public class TypingEditText extends EditText implements TextWatcher {
private static final int TypingInterval = 2000;
public interface OnTypingChanged {
public void onTyping(EditText view, boolean isTyping);
}
private OnTypingChanged t;
private Handler handler;
{
handler = new Handler();
}
public TypingEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.addTextChangedListener(this);
}
public TypingEditText(Context context, AttributeSet attrs) {
super(context, attrs);
this.addTextChangedListener(this);
}
public TypingEditText(Context context) {
super(context);
this.addTextChangedListener(this);
}
public void setOnTypingChanged(OnTypingChanged t) {
this.t = t;
}
@Override
public void afterTextChanged(Editable s) {
if(t != null){
t.onTyping(this, true);
handler.removeCallbacks(notifier);
handler.postDelayed(notifier, TypingInterval);
}
}
private Runnable notifier = new Runnable() {
@Override
public void run() {
if(t != null)
t.onTyping(TypingEditText.this, false);
}
};
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override
public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { }
}
In Chrome, for password type inputs, the autocomplete="new-password"
is the only thing working for me.
The usual rules should apply for how you send the request. If the request is to retrieve information (e.g. a partial search 'hint' result, or a new page to be displayed, etc...) you can use GET. If the data being sent is part of a request to change something (update a database, delete a record, etc..) then use POST.
Server-side, there's no reason to use the raw input, unless you want to grab the entire post/get data block in a single go. You can retrieve the specific information you want via the _GET/_POST arrays as usual. AJAX libraries such as MooTools/jQuery will handle the hard part of doing the actual AJAX calls and encoding form data into appropriate formats for you.
To retain both the margins and background color use:
background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<padding
android:bottom="10dp"
android:left="4dp"
android:right="8dp"
android:top="10dp" />
<solid android:color="@android:color/transparent" />
</shape>
Edit Text:
<androidx.appcompat.widget.AppCompatEditText
android:id="@+id/none_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/background"
android:inputType="text"
android:text="First Name And Last Name"
android:textSize="18sp" />
Building on @Adrien Be's answer above and using the code that Brian Huisman & David koelle created, here is a modified prototype sorting for an array of objects:
//Usage: unsortedArrayOfObjects.alphaNumObjectSort("name");
//Test Case: var unsortedArrayOfObjects = [{name: "a1"}, {name: "a2"}, {name: "a3"}, {name: "a10"}, {name: "a5"}, {name: "a13"}, {name: "a20"}, {name: "a8"}, {name: "8b7uaf5q11"}];
//Sorted: [{name: "8b7uaf5q11"}, {name: "a1"}, {name: "a2"}, {name: "a3"}, {name: "a5"}, {name: "a8"}, {name: "a10"}, {name: "a13"}, {name: "a20"}]
// **Sorts in place**
Array.prototype.alphaNumObjectSort = function(attribute, caseInsensitive) {
for (var z = 0, t; t = this[z]; z++) {
this[z].sortArray = new Array();
var x = 0, y = -1, n = 0, i, j;
while (i = (j = t[attribute].charAt(x++)).charCodeAt(0)) {
var m = (i == 46 || (i >=48 && i <= 57));
if (m !== n) {
this[z].sortArray[++y] = "";
n = m;
}
this[z].sortArray[y] += j;
}
}
this.sort(function(a, b) {
for (var x = 0, aa, bb; (aa = a.sortArray[x]) && (bb = b.sortArray[x]); x++) {
if (caseInsensitive) {
aa = aa.toLowerCase();
bb = bb.toLowerCase();
}
if (aa !== bb) {
var c = Number(aa), d = Number(bb);
if (c == aa && d == bb) {
return c - d;
} else {
return (aa > bb) ? 1 : -1;
}
}
}
return a.sortArray.length - b.sortArray.length;
});
for (var z = 0; z < this.length; z++) {
// Here we're deleting the unused "sortArray" instead of joining the string parts
delete this[z]["sortArray"];
}
}
Generic Conversion Macros (TN059 Other Considerations section is important):
A2CW (LPCSTR) -> (LPCWSTR)
A2W (LPCSTR) -> (LPWSTR)
W2CA (LPCWSTR) -> (LPCSTR)
W2A (LPCWSTR) -> (LPSTR)
Ubuntu Apache2 solution that worked for me .htaccess edit did not work for me I had to modify the conf file.
nano /etc/apache2/sites-available/mydomain.xyz.conf
my config that worked to allow CORS Support
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName mydomain.xyz
ServerAlias www.mydomain.xyz
ServerAdmin [email protected]
DocumentRoot /var/www/mydomain.xyz/public
### following three lines are for CORS support
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
SSLCertificateFile /etc/letsencrypt/live/mydomain.xyz/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/mydomain.xyz/privkey.pem
</VirtualHost>
</IfModule>
a2enmod headers
you can use rdd.coalesce(1, true).saveAsTextFile(path)
it will store data as singile file in path/part-00000
Often the complete testImplementation
, implementation
, and androidTestImplementation
dependency graph is too much to examine together. If you merely want the implementation
dependency graph you can use:
./gradlew app:dependencies --configuration implementation
Source: Gradle docs section 4.7.6
Note: compile
has been deprecated in more recent versions of Gradle and in more recent versions you are advised to shift all of your compile
dependencies to implementation
. Please see this answer here
The JSON.stringify
method supported by many modern browsers (including IE8) can output a beautified JSON string:
JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4); // stringify with 4 spaces at each level
Demo: http://jsfiddle.net/AndyE/HZPVL/
This method is also included with json2.js, for supporting older browsers.
If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.
You need to create installer, which will check if user has required .NET Framework 4.0. You can use WiX to create installer. It's very powerfull and customizable. Also you can use ClickOnce to create installer - it's very simple to use. It will allow you with one click add requirement to install .NET Framework 4.0.
I'm had the same problem, and I tried with the answers above, but I wanted something more thin, then I tried to change one by one opsions, and discover that we just need to add
.carousel {
height: 100%;
}
There's no fixed time for retransmission. Simple implementations estimate the RTT (round-trip-time) and if no ACK to send data has been received in 2x that time then they re-send.
They then double the wait-time and re-send once more if again there is no reply. Rinse. Repeat.
More sophisticated systems make better estimates of how long it should take for the ACK as well as guesses about exactly which data has been lost.
The bottom-line is that there is no hard-and-fast rule about exactly when to retransmit. It's up to the implementation. All retransmissions are triggered solely by the sender based on lack of response from the receiver.
TCP never drops data so no, there is no way to indicate a server should forget about some segment.
calling select
will result is lazy
evaluation: for example:
val df1 = df.select("col1")
val df2 = df1.filter("col1 == 3")
both above statements create lazy path that will be executed when you call action on that df
, such as show
, collect
etc.
val df3 = df2.collect()
use .explain
at the end of your transformation to follow its plan
here is more detailed info Transformations and Actions
You can use python-textops3 :
from textops import *
print('\n'.join(cat(f) | grep(search_term)))
with python-textops3 you can use unix-like commands with pipes
# tar all files within and deeper in a given directory
# with no prefixes ( neither <directory>/ nor ./ )
# parameters: <source directory> <target archive file>
function tar_all_in_dir {
{ cd "$1" && find -type f -print0; } \
| cut --zero-terminated --characters=3- \
| tar --create --file="$2" --directory="$1" --null --files-from=-
}
Safely handles filenames with spaces or other unusual characters. You can optionally add a -name '*.sql'
or similar filter to the find command to limit the files included.
An extension method for this which makes use of SemaphoreSlim and also allows to set maximum degree of parallelism
/// <summary>
/// Concurrently Executes async actions for each item of <see cref="IEnumerable<typeparamref name="T"/>
/// </summary>
/// <typeparam name="T">Type of IEnumerable</typeparam>
/// <param name="enumerable">instance of <see cref="IEnumerable<typeparamref name="T"/>"/></param>
/// <param name="action">an async <see cref="Action" /> to execute</param>
/// <param name="maxDegreeOfParallelism">Optional, An integer that represents the maximum degree of parallelism,
/// Must be grater than 0</param>
/// <returns>A Task representing an async operation</returns>
/// <exception cref="ArgumentOutOfRangeException">If the maxActionsToRunInParallel is less than 1</exception>
public static async Task ForEachAsyncConcurrent<T>(
this IEnumerable<T> enumerable,
Func<T, Task> action,
int? maxDegreeOfParallelism = null)
{
if (maxDegreeOfParallelism.HasValue)
{
using (var semaphoreSlim = new SemaphoreSlim(
maxDegreeOfParallelism.Value, maxDegreeOfParallelism.Value))
{
var tasksWithThrottler = new List<Task>();
foreach (var item in enumerable)
{
// Increment the number of currently running tasks and wait if they are more than limit.
await semaphoreSlim.WaitAsync();
tasksWithThrottler.Add(Task.Run(async () =>
{
await action(item).ContinueWith(res =>
{
// action is completed, so decrement the number of currently running tasks
semaphoreSlim.Release();
});
}));
}
// Wait for all tasks to complete.
await Task.WhenAll(tasksWithThrottler.ToArray());
}
}
else
{
await Task.WhenAll(enumerable.Select(item => action(item)));
}
}
Sample Usage:
await enumerable.ForEachAsyncConcurrent(
async item =>
{
await SomeAsyncMethod(item);
},
5);
Import this in to app.module.ts
import {HttpClientModule} from '@angular/common/http';
and add this one in imports
HttpClientModule
@Adam Just add a function using onClick="getId()"
function getId(){console.log(this.event.target.id)}
Here is a backbone.js implementation:
events: {
"click #toggleChecked" : "toggleChecked"
},
toggleChecked: function(event) {
var checkboxes = document.getElementsByName('options');
for(var i=0; i<checkboxes.length; i++) {
checkboxes[i].checked = event.currentTarget.checked;
}
},
You may have to use =IF(ISNUMBER(A1),A1,1)
in some situations where you are looking for number values in cell.
Googling gives me this:
Command A & Command B
Execute Command A, then execute Command B (no evaluation of anything)
Command A | Command B
Execute Command A, and redirect all its output into the input of Command B
Command A && Command B
Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B
Command A || Command B
Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B
You can't use fetch in actions without middleware. Actions must be plain objects. You can use a middleware like redux-thunk or redux-saga to do fetch and then dispatch another action.
Here is an example of async action using redux-thunk middleware.
export function checkUserLoggedIn (authCode) {
let url = `${loginUrl}validate?auth_code=${authCode}`;
return dispatch => {
return fetch(url,{
method: 'GET',
headers: {
"Content-Type": "application/json"
}
}
)
.then((resp) => {
let json = resp.json();
if (resp.status >= 200 && resp.status < 300) {
return json;
} else {
return json.then(Promise.reject.bind(Promise));
}
})
.then(
json => {
if (json.result && (json.result.status === 'error')) {
dispatch(errorOccurred(json.result));
dispatch(logOut());
}
else{
dispatch(verified(json.result));
}
}
)
.catch((error) => {
dispatch(warningOccurred(error, url));
})
}
}
var clonedArray = array.concat();
If you want to be able to concatenate vectors concisely, you could overload the +=
operator.
template <typename T>
std::vector<T>& operator +=(std::vector<T>& vector1, const std::vector<T>& vector2) {
vector1.insert(vector1.end(), vector2.begin(), vector2.end());
return vector1;
}
Then you can call it like this:
vector1 += vector2;
You should not extend the JFrame
class unnecessarily (only if you are adding extra functionality to the JFrame
class)
JFrame:
JFrame
extends Component
and Container
.
It is a top level container used to represent the minimum requirements for a window. This includes Border
s, resizability (is the JFrame
resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Event
s like windowClose
, windowOpened
etc.
JPanel:
JPanel
extends Component
, Container
and JComponent
It is a generic class used to group other Component
s together.
It is useful when working with LayoutManager
s e.g. GridLayout
f.i adding components to different JPanel
s which will then be added to the JFrame
to create the gui. It will be more manageable in terms of Layout
and re-usability.
It is also useful for when painting/drawing in Swing, you would override paintComponent(..)
and of course have the full joys of double buffering.
A Swing GUI cannot exist without a top level container like (JWindow
, Window
, JFrame
Frame
or Applet
), while it may exist without JPanel
s.
I'd suggest reading the W3 wiki page about structuring HTML5:
<header>
Used to contain the header content of a site.<footer>
Contains the footer content of a site.<nav>
Contains the navigation menu, or other navigation functionality for the page.
<article>
Contains a standalone piece of content that would make
sense if syndicated as an RSS item, for example a news item.
<section>
Used to either group different articles into different
purposes or subjects, or to define the different sections of a single article.
<aside>
Defines a block of content that is related to the main content around it, but not central to the flow of it.
They include an image that I've cleaned up here:
In code, this looks like so:
<body> <header></header> <nav></nav> <section id="sidebar"></section> <section id="content"></section> <aside></aside> <footer></footer> </body>
Let's explore some of the HTML5 elements in more detail.
<section>
The
<section>
element is for containing distinct different areas of functionality or subjects area, or breaking an article or story up into different sections. So in this case: "sidebar1" contains various useful links that will persist on every page of the site, such as "subscribe to RSS" and "Buy music from store". "main" contains the main content of this page, which is blog posts. On other pages of the site, this content will change. It is a fairly generic element, but still has way more semantic meaning than the plain old<div>
.
<article>
<article>
is related to<section>
, but is distinctly different. Whereas<section>
is for grouping distinct sections of content or functionality,<article>
is for containing related individual standalone pieces of content, such as individual blog posts, videos, images or news items. Think of it this way - if you have a number of items of content, each of which would be suitable for reading on their own, and would make sense to syndicate as separate items in an RSS feed, then<article>
is suitable for marking them up. In our example,<section id="main">
contains blog entries. Each blog entry would be suitable for syndicating as an item in an RSS feed, and would make sense when read on its own, out of context, therefore<article>
is perfect for them:<section id="main"> <article><!-- first blog post --></article> <article><!-- second blog post --></article> <article><!-- third blog post --></article> </section>
Simple huh? Be aware though that you can also nest sections inside articles, where it makes sense to do so. For example, if each one of these blog posts has a consistent structure of distinct sections, then you could put sections inside your articles as well. It could look something like this:
<article> <section id="introduction"></section> <section id="content"></section> <section id="summary"></section> </article>
<header>
and<footer>
as we already mentioned above, the purpose of the
<header>
and<footer>
elements is to wrap header and footer content, respectively. In our particular example the<header>
element contains a logo image, and the<footer>
element contains a copyright notice, but you could add more elaborate content if you wished. Also note that you can have more than one header and footer on each page - as well as the top level header and footer we have just discussed, you could also have a<header>
and<footer>
element nested inside each<article>
, in which case they would just apply to that particular article. Adding to our above example:<article> <header></header> <section id="introduction"></section> <section id="content"></section> <section id="summary"></section> <footer></footer> </article>
<nav>
The
<nav>
element is for marking up the navigation links or other constructs (eg a search form) that will take you to different pages of the current site, or different areas of the current page. Other links, such as sponsored links, do not count. You can of course include headings and other structuring elements inside the<nav>
, but it's not compulsory.
<aside>
you may have noticed that we used an
<aside>
element to markup the 2nd sidebar: the one containing latest gigs and contact details. This is perfectly appropriate, as<aside>
is for marking up pieces of information that are related to the main flow, but don't fit in to it directly. And the main content in this case is all about the band! Other good choices for an<aside>
would be information about the author of the blog post(s), a band biography, or a band discography with links to buy their albums.Where does that leave
<div>
?So, with all these great new elements to use on our pages, the days of the humble
<div>
are numbered, surely? NO. In fact, the<div>
still has a perfectly valid use. You should use it when there is no other more suitable element available for grouping an area of content, which will often be when you are purely using an element to group content together for styling/visual purposes. A common example is using a<div>
to wrap all of the content on the page, and then using CSS to centre all the content in the browser window, or apply a specific background image to the whole content.
In your svn\repos\YourRepo\conf folder you will find two files, authz and passwd. These are the two you need to adjust.
In the passwd file you need to add some usernames and passwords. I assume you have already done this since you have people using it:
[users]
User1=password1
User2=password2
Then you want to assign permissions accordingly with the authz file:
Create the conceptual groups you want, and add people to it:
[groups]
allaccess = user1
someaccess = user2
Then choose what access they have from both the permissions and project level.
So let's give our "all access" guys all access from the root:
[/]
@allaccess = rw
But only give our "some access" guys read-only access to some lower level project:
[/someproject]
@someaccess = r
You will also find some simple documentation in the authz and passwd files.
My problem is that I accidentally set the arguments for Main
static void Main(object value)
thanks to my refactoring tool. Took couple mins to figure out but should help someone along the way.
Solve it by this:
/usr/lib/python3/dist-packages# cp apt_pkg.cpython-34m-i386-linux-gnu.so apt_pkg.so
Or:
/usr/lib/python3/dist-packages# cp apt_pkg.cpython-35m-x86_64-linux-gnu.so apt_pkg.so
Basically, if you get a No such file or directory
just ls
to try to get the right name.
Don't forget the easy route:
static void Main(string[] args)
{
var text = File.ReadAllText(@"C:\words.txt");
File.WriteAllText(@"C:\words.txt", text + "DERP");
}
Locally within an virtualenv there are two methods you could use to test this. The first is a tool which is installed via the Heroku toolbelt (https://toolbelt.heroku.com/). The tool is foreman. It will export all of your environment variables that are stored in a .env file locally and then run app processes within your Procfile.
The second way if you're looking for a lighter approach is to have a .env file locally then run:
export $(cat .env)
according to JAVA documentation, the JDK should be installed in this path:
/Library/Java/JavaVirtualMachines/jdkmajor.minor.macro[_update].jdk
See the uninstall JDK part at https://docs.oracle.com/javase/8/docs/technotes/guides/install/mac_jdk.html
So if you can find such folder then the JDK is installed
updated
might be what you're looking for. https://vuejs.org/v2/api/#updated
Html
$('#save').click(function(event) {
var jenis = $('#jenis').val();
var model = $('#model').val();
var harga = $('#harga').val();
var json = { "jenis" : jenis, "model" : model, "harga": harga};
$.ajax({
url: 'phone/save',
data: JSON.stringify(json),
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data){
alert(data);
}
});
event.preventDefault();
});
Controller
@Controller
@RequestMapping(value="/phone")
public class phoneController {
phoneDao pd=new phoneDao();
@RequestMapping(value="/save",method=RequestMethod.POST)
public @ResponseBody
int save(@RequestBody Smartphones phone)
{
return pd.save(phone);
}
Dao
public Integer save(Smartphones i) {
int id = 0;
Session session=HibernateUtil.getSessionFactory().openSession();
Transaction trans=session.beginTransaction();
try {
session.save(i);
id=i.getId();
trans.commit();
}
catch(HibernateException he){}
return id;
}
you can solve it by overriding the Run function of CI_Form_Validation
copy this function in a class which extends CI_Form_Validation .
This function will override the parent class function . Here i added only a extra check which can handle file also
/**
* Run the Validator
*
* This function does all the work.
*
* @access public
* @return bool
*/
function run($group = '') {
// Do we even have any data to process? Mm?
if (count($_POST) == 0) {
return FALSE;
}
// Does the _field_data array containing the validation rules exist?
// If not, we look to see if they were assigned via a config file
if (count($this->_field_data) == 0) {
// No validation rules? We're done...
if (count($this->_config_rules) == 0) {
return FALSE;
}
// Is there a validation rule for the particular URI being accessed?
$uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group;
if ($uri != '' AND isset($this->_config_rules[$uri])) {
$this->set_rules($this->_config_rules[$uri]);
} else {
$this->set_rules($this->_config_rules);
}
// We're we able to set the rules correctly?
if (count($this->_field_data) == 0) {
log_message('debug', "Unable to find validation rules");
return FALSE;
}
}
// Load the language file containing error messages
$this->CI->lang->load('form_validation');
// Cycle through the rules for each field, match the
// corresponding $_POST or $_FILES item and test for errors
foreach ($this->_field_data as $field => $row) {
// Fetch the data from the corresponding $_POST or $_FILES array and cache it in the _field_data array.
// Depending on whether the field name is an array or a string will determine where we get it from.
if ($row['is_array'] == TRUE) {
if (isset($_FILES[$field])) {
$this->_field_data[$field]['postdata'] = $this->_reduce_array($_FILES, $row['keys']);
} else {
$this->_field_data[$field]['postdata'] = $this->_reduce_array($_POST, $row['keys']);
}
} else {
if (isset($_POST[$field]) AND $_POST[$field] != "") {
$this->_field_data[$field]['postdata'] = $_POST[$field];
} else if (isset($_FILES[$field]) AND $_FILES[$field] != "") {
$this->_field_data[$field]['postdata'] = $_FILES[$field];
}
}
$this->_execute($row, explode('|', $row['rules']), $this->_field_data[$field]['postdata']);
}
// Did we end up with any errors?
$total_errors = count($this->_error_array);
if ($total_errors > 0) {
$this->_safe_form_data = TRUE;
}
// Now we need to re-set the POST data with the new, processed data
$this->_reset_post_array();
// No errors, validation passes!
if ($total_errors == 0) {
return TRUE;
}
// Validation fails
return FALSE;
}
Database Clustering is actually a mode of synchronous replication between two or possibly more nodes with an added functionality of fault tolerance added to your system, and that too in a shared nothing architecture. By shared nothing it means that the individual nodes actually don't share any physical resources like disk or memory.
As far as keeping the data synchronized is concerned, there is a management server to which all the data nodes are connected along with the SQL node to achieve this(talking specifically about MySQL).
Now about the differences: load balancing is just one result that could be achieved through clustering, the others include high availability, scalability and fault tolerance.
Xcode8 swift3.1:
webViewDidFinishLoad
Delegate:let height = webView.scrollView.contentSize.height
Without step1, if webview.height > actual contentHeight, step 2 will return webview.height but not contentsize.height.
If we need to check Edge please go head with this
if(navigator.userAgent.indexOf("Edge") > 1 ){
//do something
}
My "convention": static before instance, public before private, constructor before methods, but main method at the bottom (if present).
The li
tag has a property called list-style-position
. This makes your bullets inside or outside the list. On default, it’s set to inside
. That makes your text wrap around it. If you set it to outside
, the text of your li
tags will be aligned.
The downside of that is that your bullets won't be aligned with the text outside the ul
. If you want to align it with the other text you can use a margin.
ul li {
/*
* We want the bullets outside of the list,
* so the text is aligned. Now the actual bullet
* is outside of the list’s container
*/
list-style-position: outside;
/*
* Because the bullet is outside of the list’s
* container, indent the list entirely
*/
margin-left: 1em;
}
Edit 15th of March, 2014 Seeing people are still coming in from Google, I felt like the original answer could use some improvement
em
’sul
elementDon't provide the handler to execute
.
Get the HttpResponse
object, use the handler to get the body and get the status code from it directly
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
final HttpGet httpGet = new HttpGet(GET_URL);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
StatusLine statusLine = response.getStatusLine();
System.out.println(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
System.out.println("Response body: " + responseBody);
}
}
For quick single calls, the fluent API is useful:
Response response = Request.Get(uri)
.connectTimeout(MILLIS_ONE_SECOND)
.socketTimeout(MILLIS_ONE_SECOND)
.execute();
HttpResponse httpResponse = response.returnResponse();
StatusLine statusLine = httpResponse.getStatusLine();
For older versions of java or httpcomponents, the code might look different.
See this fiddle for a preview and check the documentation for jquerys toggle and animate methods.
$('#toggle').toggle(function(){
$('#A').animate({width:0});
$('#B').animate({left:0});
},function(){
$('#A').animate({width:200});
$('#B').animate({left:200});
});
Basically you animate on the properties that sets the layout.
A more advanced version:
$('#toggle').toggle(function(){
$('#A').stop(true).animate({width:0});
$('#B').stop(true).animate({left:0});
},function(){
$('#A').stop(true).animate({width:200});
$('#B').stop(true).animate({left:200});
})
This stops the previous animation, clears animation queue and begins the new animation.
Yes, a UITextView is what you're looking for. You'll have to deal with some things differently (like the return key) but you can add text to it, and it will allow you to scroll up and down if there's too much text inside.
This link has info about making a screen to enter data:
For SQL query generating scripts, or anything that does a different action for the first or last elements, it is much faster (almost twice as fast) to avoid using unneccessary variable checks.
The current accepted solution uses a loop and a check within the loop that will be made every_single_iteration, the correct (fast) way to do this is the following :
$numItems = count($arr);
$i=0;
$firstitem=$arr[0];
$i++;
while($i<$numItems-1){
$some_item=$arr[$i];
$i++;
}
$last_item=$arr[$i];
$i++;
A little homemade benchmark showed the following:
test1: 100000 runs of model morg
time: 1869.3430423737 milliseconds
test2: 100000 runs of model if last
time: 3235.6359958649 milliseconds
My issue turned out to be that I had SSL Enabled on the project settings. I simply disabled this because I did not require SSL for running the project locally.
In Visual Studio 2015:
In my situation I was getting an error about port 443 in use because this was the port set on the SSL URL for the project.
They are taking a 'shotgun' approach to referencing the font. The browser will attempt to match each font name with any installed fonts on the user's machine (in the order they have been listed).
In your example "HelveticaNeue-Light"
will be tried first, if this font variant is unavailable the browser will try "Helvetica Neue Light"
and finally "Helvetica Neue"
.
As far as I'm aware "Helvetica Neue"
isn't considered a 'web safe font', which means you won't be able to rely on it being installed for your entire user base. It is quite common to define "serif"
or "sans-serif"
as a final default position.
In order to use fonts which aren't 'web safe' you'll need to use a technique known as font embedding. Embedded fonts do not need to be installed on a user's computer, instead they are downloaded as part of the page. Be aware this increases the overall payload (just like an image does) and can have an impact on page load times.
A great resource for free fonts with open-source licenses is Google Fonts. (You should still check individual licenses before using them.) Each font has a download link with instructions on how to embed them in your website.
In my case I was following the documentation for react-fontawesome
package, but they aren't clear about how to call the icon when setting the icons into the library
this is was what I was doing:
App.js file
import {faCoffee} from "@fortawesome/pro-light-svg-icons";
library.add(faSearch, faFileSearch, faCoffee);
Component file
<FontAwesomeIcon icon={"coffee"} />
But I was getting this error
Then I added the alias when passing the icon prop like:
<FontAwesomeIcon icon={["fal", "coffee"]} />
And it is working, you can find the prefix value in the icon.js file, in my case was: faCoffee.js
Try linking node to nodejs. First find out where nodejs is
whereis nodejs
Then soft link node to nodejs
ln -s [the path of nodejs] /usr/bin/node
I am assuming /usr/bin is in your execution path. Then you can test by typing node or npm into your command line, and everything should work now.
You should be able to accomplish this by using location.href
if(window.location.hostname == "www.myweb.com"){
window.location.href = window.location.href + "?single";
}
My experience when working with large & complicated XML files is that sometimes neither Elements nor Descendants seem to work in retrieving a specific Element (and I still do not know why).
In such cases, I found that a much safer option is to manually search for the Element, as described by the following MSDN post:
In short, you can create a GetElement function:
private XElement GetElement(XDocument doc,string elementName)
{
foreach (XNode node in doc.DescendantNodes())
{
if (node is XElement)
{
XElement element = (XElement)node;
if (element.Name.LocalName.Equals(elementName))
return element;
}
}
return null;
}
Which you can then call like this:
XElement element = GetElement(doc,"Band");
Note that this will return null if no matching element is found.
The VH 100 does not work well on mobile as it does not factor in the iOS bar (or similar functionality on other platforms).
One solution that works well is to use JavaScript "window.innerHeight".
Simply assign the height of the element to this value e.g. $('.element-name').height(window.innerHeight);
Note: It may be useful to create a function in JS, so that the height can change when the screen is resized. However, I would suggest only calling the function when the width of the screen is changed, this way the element will not jump in height when the iOS bar disappears when the user scrolls down the page.
I see a similar problem...
I need to spool CSV file from SQLPLUS, but the output has 250 columns.
What I did to avoid annoying SQLPLUS output formatting:
set linesize 9999
set pagesize 50000
spool myfile.csv
select x
from
(
select col1||';'||col2||';'||col3||';'||col4||';'||col5||';'||col6||';'||col7||';'||col8||';'||col9||';'||col10||';'||col11||';'||col12||';'||col13||';'||col14||';'||col15||';'||col16||';'||col17||';'||col18||';'||col19||';'||col20||';'||col21||';'||col22||';'||col23||';'||col24||';'||col25||';'||col26||';'||col27||';'||col28||';'||col29||';'||col30 as x
from (
... here is the "core" select
)
);
spool off
the problem is you will lose column header names...
you can add this:
set heading off
spool myfile.csv
select col1_name||';'||col2_name||';'||col3_name||';'||col4_name||';'||col5_name||';'||col6_name||';'||col7_name||';'||col8_name||';'||col9_name||';'||col10_name||';'||col11_name||';'||col12_name||';'||col13_name||';'||col14_name||';'||col15_name||';'||col16_name||';'||col17_name||';'||col18_name||';'||col19_name||';'||col20_name||';'||col21_name||';'||col22_name||';'||col23_name||';'||col24_name||';'||col25_name||';'||col26_name||';'||col27_name||';'||col28_name||';'||col29_name||';'||col30_name from dual;
select x
from
(
select col1||';'||col2||';'||col3||';'||col4||';'||col5||';'||col6||';'||col7||';'||col8||';'||col9||';'||col10||';'||col11||';'||col12||';'||col13||';'||col14||';'||col15||';'||col16||';'||col17||';'||col18||';'||col19||';'||col20||';'||col21||';'||col22||';'||col23||';'||col24||';'||col25||';'||col26||';'||col27||';'||col28||';'||col29||';'||col30 as x
from (
... here is the "core" select
)
);
spool off
I know it`s kinda hardcore, but it works for me...
Option 1 is to use display:table-cell
. You need to unfloat the Bootstrap col-* using float:none
..
.center {
display:table-cell;
vertical-align:middle;
float:none;
}
Option 2 is display:flex
to vertical align the row with flexbox:
.row.center {
display: flex;
align-items: center;
}
http://www.bootply.com/7rAuLpMCwr
Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4 https://stackoverflow.com/a/41464397/171456
Am afraid this question has been answered a few times, Pls take a look at the following if it's related
Save this python script to known_hosts.py
:
#! /usr/bin/env python
# $Id$
# Convert OpenSSH known_hosts and known_hosts2 files to "new format" PuTTY
# host keys.
# usage:
# kh2reg.py [ --win ] known_hosts1 2 3 4 ... > hosts.reg
# Creates a Windows .REG file (double-click to install).
# kh2reg.py --unix known_hosts1 2 3 4 ... > sshhostkeys
# Creates data suitable for storing in ~/.putty/sshhostkeys (Unix).
# Line endings are someone else's problem as is traditional.
# Developed for Python 1.5.2.
import fileinput
import base64
import struct
import string
import re
import sys
import getopt
def winmungestr(s):
"Duplicate of PuTTY's mungestr() in winstore.c:1.10 for Registry keys"
candot = 0
r = ""
for c in s:
if c in ' \*?%~' or ord(c)<ord(' ') or (c == '.' and not candot):
r = r + ("%%%02X" % ord(c))
else:
r = r + c
candot = 1
return r
def strtolong(s):
"Convert arbitrary-length big-endian binary data to a Python long"
bytes = struct.unpack(">%luB" % len(s), s)
return reduce ((lambda a, b: (long(a) << 8) + long(b)), bytes)
def longtohex(n):
"""Convert long int to lower-case hex.
Ick, Python (at least in 1.5.2) doesn't appear to have a way to
turn a long int into an unadorned hex string -- % gets upset if the
number is too big, and raw hex() uses uppercase (sometimes), and
adds unwanted "0x...L" around it."""
plain=string.lower(re.match(r"0x([0-9A-Fa-f]*)l?$", hex(n), re.I).group(1))
return "0x" + plain
output_type = 'windows'
try:
optlist, args = getopt.getopt(sys.argv[1:], '', [ 'win', 'unix' ])
if filter(lambda x: x[0] == '--unix', optlist):
output_type = 'unix'
except getopt.error, e:
sys.stderr.write(str(e) + "\n")
sys.exit(1)
if output_type == 'windows':
# Output REG file header.
sys.stdout.write("""REGEDIT4
[HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\SshHostKeys]
""")
# Now process all known_hosts input.
for line in fileinput.input(args):
try:
# Remove leading/trailing whitespace (should zap CR and LF)
line = string.strip (line)
# Skip blanks and comments
if line == '' or line[0] == '#':
raise "Skipping input line"
# Split line on spaces.
fields = string.split (line, ' ')
# Common fields
hostpat = fields[0]
magicnumbers = [] # placeholder
keytype = "" # placeholder
# Grotty heuristic to distinguish known_hosts from known_hosts2:
# is second field entirely decimal digits?
if re.match (r"\d*$", fields[1]):
# Treat as SSH-1-type host key.
# Format: hostpat bits10 exp10 mod10 comment...
# (PuTTY doesn't store the number of bits.)
magicnumbers = map (long, fields[2:4])
keytype = "rsa"
else:
# Treat as SSH-2-type host key.
# Format: hostpat keytype keyblob64 comment...
sshkeytype, blob = fields[1], base64.decodestring (fields[2])
# 'blob' consists of a number of
# uint32 N (big-endian)
# uint8[N] field_data
subfields = []
while blob:
sizefmt = ">L"
(size,) = struct.unpack (sizefmt, blob[0:4])
size = int(size) # req'd for slicage
(data,) = struct.unpack (">%lus" % size, blob[4:size+4])
subfields.append(data)
blob = blob [struct.calcsize(sizefmt) + size : ]
# The first field is keytype again, and the rest we can treat as
# an opaque list of bignums (same numbers and order as stored
# by PuTTY). (currently embedded keytype is ignored entirely)
magicnumbers = map (strtolong, subfields[1:])
# Translate key type into something PuTTY can use.
if sshkeytype == "ssh-rsa": keytype = "rsa2"
elif sshkeytype == "ssh-dss": keytype = "dss"
else:
raise "Unknown SSH key type", sshkeytype
# Now print out one line per host pattern, discarding wildcards.
for host in string.split (hostpat, ','):
if re.search (r"[*?!]", host):
sys.stderr.write("Skipping wildcard host pattern '%s'\n"
% host)
continue
elif re.match (r"\|", host):
sys.stderr.write("Skipping hashed hostname '%s'\n" % host)
continue
else:
m = re.match (r"\[([^]]*)\]:(\d*)$", host)
if m:
(host, port) = m.group(1,2)
port = int(port)
else:
port = 22
# Slightly bizarre output key format: 'type@port:hostname'
# XXX: does PuTTY do anything useful with literal IP[v4]s?
key = keytype + ("@%d:%s" % (port, host))
value = string.join (map (longtohex, magicnumbers), ',')
if output_type == 'unix':
# Unix format.
sys.stdout.write('%s %s\n' % (key, value))
else:
# Windows format.
# XXX: worry about double quotes?
sys.stdout.write("\"%s\"=\"%s\"\n"
% (winmungestr(key), value))
except "Unknown SSH key type", k:
sys.stderr.write("Unknown SSH key type '%s', skipping\n" % k)
except "Skipping input line":
pass
Tested on Win7x64 and Python 2.7.
Then run:
ssh-keyscan -t rsa bitbucket.org >>~/.ssh/known_hosts
python --win known_hosts.py >known_hosts.reg
start known_hosts.reg
And choose to import into the registry. The keyscan will retrieve the public key for the domain (I had my problems with bitbucket), and then the python script will convert it to Plink format.
UPDATE table1
SET column1 = (SELECT expression1
FROM table2
WHERE conditions)
[WHERE conditions];
Open a terminal and type: java -version
, or javac -version
.
If you have all the latest updates for Snow Leopard, you should be running JDK 1.6.0_20 at this moment (the same as Oracle's current JDK version).
void foo() {
/* do some stuff */
if (!condition) {
return;
}
}
You can just use the return keyword just like you would in any other function.
Here is a full example of setting up Guava Cache in Spring. I used Guava over Ehcache because it's a bit lighter weight and the config seemed more straight forward to me.
Import Maven Dependencies
Add these dependencies to your maven pom file and run clean and packages. These files are the Guava dep and Spring helper methods for use in the CacheBuilder.
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
Configure the Cache
You need to create a CacheConfig file to configure the cache using Java config.
@Configuration
@EnableCaching
public class CacheConfig {
public final static String CACHE_ONE = "cacheOne";
public final static String CACHE_TWO = "cacheTwo";
@Bean
public Cache cacheOne() {
return new GuavaCache(CACHE_ONE, CacheBuilder.newBuilder()
.expireAfterWrite(60, TimeUnit.MINUTES)
.build());
}
@Bean
public Cache cacheTwo() {
return new GuavaCache(CACHE_TWO, CacheBuilder.newBuilder()
.expireAfterWrite(60, TimeUnit.SECONDS)
.build());
}
}
Annotate the method to be cached
Add the @Cacheable annotation and pass in the cache name.
@Service
public class CachedService extends WebServiceGatewaySupport implements CachedService {
@Inject
private RestTemplate restTemplate;
@Cacheable(CacheConfig.CACHE_ONE)
public String getCached() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> reqEntity = new HttpEntity<>("url", headers);
ResponseEntity<String> response;
String url = "url";
response = restTemplate.exchange(
url,
HttpMethod.GET, reqEntity, String.class);
return response.getBody();
}
}
You can see a more complete example here with annotated screenshots: Guava Cache in Spring
Try this to redirect cout to file.
#include <iostream>
#include <fstream>
int main()
{
/** backup cout buffer and redirect to out.txt **/
std::ofstream out("out.txt");
auto *coutbuf = std::cout.rdbuf();
std::cout.rdbuf(out.rdbuf());
std::cout << "This will be redirected to file out.txt" << std::endl;
/** reset cout buffer **/
std::cout.rdbuf(coutbuf);
std::cout << "This will be printed on console" << std::endl;
return 0;
}
Read full article Use std::rdbuf to Redirect cin and cout
Another corner case that this could happen: if you read/write a JAR file through a URL
and later try to delete the same file within the same JVM session.
File f = new File("/tmp/foo.jar");
URL j = f.toURI().toURL();
URL u = new URL("jar:" + j + "!/META-INF/MANIFEST.MF");
URLConnection c = u.openConnection();
// open a Jar entry in auto-closing manner
try (InputStream i = c.getInputStream()) {
// just read some stuff; for demonstration purposes only
byte[] first16 = new byte[16];
i.read(first16);
System.out.println(new String(first16));
}
// ...
// i is now closed, so we should be good to delete the jar; but...
System.out.println(f.delete()); // says false!
Reason is that the internal JAR file handling logic of Java, tends to cache JarFile
entries:
// inner class of `JarURLConnection` that wraps the actual stream returned by `getInputStream()`
class JarURLInputStream extends FilterInputStream {
JarURLInputStream(InputStream var2) {
super(var2);
}
public void close() throws IOException {
try {
super.close();
} finally {
// if `getUseCaches()` is set, `jarFile` won't get closed!
if (!JarURLConnection.this.getUseCaches()) {
JarURLConnection.this.jarFile.close();
}
}
}
}
And each JarFile
(rather, the underlying ZipFile
structure) would hold a handle to the file, right from the time of construction up until close()
is invoked:
public ZipFile(File file, int mode, Charset charset) throws IOException {
// ...
jzfile = open(name, mode, file.lastModified(), usemmap);
// ...
}
// ...
private static native long open(String name, int mode, long lastModified,
boolean usemmap) throws IOException;
There's a good explanation on this NetBeans issue.
Apparently there are two ways to "fix" this:
You can disable the JAR file caching - for the current URLConnection
, or for all future URLConnection
s (globally) in the current JVM session:
URL u = new URL("jar:" + j + "!/META-INF/MANIFEST.MF");
URLConnection c = u.openConnection();
// for only c
c.setUseCaches(false);
// globally; for some reason this method is not static,
// so we still need to access it through a URLConnection instance :(
c.setDefaultUseCaches(false);
[HACK WARNING!] You can manually purge the JarFile
from the cache when you are done with it. The cache manager sun.net.www.protocol.jar.JarFileFactory
is package-private, but some reflection magic can get the job done for you:
class JarBridge {
static void closeJar(URL url) throws Exception {
// JarFileFactory jarFactory = JarFileFactory.getInstance();
Class<?> jarFactoryClazz = Class.forName("sun.net.www.protocol.jar.JarFileFactory");
Method getInstance = jarFactoryClazz.getMethod("getInstance");
getInstance.setAccessible(true);
Object jarFactory = getInstance.invoke(jarFactoryClazz);
// JarFile jarFile = jarFactory.get(url);
Method get = jarFactoryClazz.getMethod("get", URL.class);
get.setAccessible(true);
Object jarFile = get.invoke(jarFactory, url);
// jarFactory.close(jarFile);
Method close = jarFactoryClazz.getMethod("close", JarFile.class);
close.setAccessible(true);
//noinspection JavaReflectionInvocation
close.invoke(jarFactory, jarFile);
// jarFile.close();
((JarFile) jarFile).close();
}
}
// and in your code:
// i is now closed, so we should be good to delete the jar
JarBridge.closeJar(j);
System.out.println(f.delete()); // says true, phew.
Please note: All this is based on Java 8 codebase (1.8.0_144
); they may not work with other / later versions.
Please first delete data from that table and then run the migration again. You will get success
ZoomX — Android Logger Interceptor is a great interceptor can help you to solve your problem.
JOptionPane.showOptionDialog
JOptionPane.showMessageDialog
....
Have a look on this tutorial on how to make dialogs.
Just add one to the result. That turns [0, 10) into (0,10] (for integers). [0, 10) is just a more confusing way to say [0, 9], and (0,10] is [1,10] (for integers).
I'd go with the CASE WHEN
also.
Depending on what you actually want to do, there may be other options though, like using an outer join or whatever, but that doesn't seem to be what you need in this case.
i also recommend thinking this thru and then choosing to store images in your file system rather than the DB .. see here: Storing Images in DB - Yea or Nay?
GUID has longstanding usage in areas where it isn't necessarily a 128-bit value in the same way as a UUID. For example, the RSS specification defines GUIDs to be any string of your choosing, as long as it's unique, with an "isPermalink" attribute to specify that the value you're using is just a permalink back to the item being syndicated.
sed -i 's/[[:blank:]]\{1,\}$//' YourFile
[:blank:] is for space, tab mainly and {1,} to exclude 'no space at the end' of the substitution process (no big significant impact if line are short and file are small)
Use Application.ActiveWorkbook.Path
for just the path itself (without the workbook name) or Application.ActiveWorkbook.FullName
for the path with the workbook name.
string col1Value = rdr["ColumnOneName"].ToString();
or
string col1Value = rdr[0].ToString();
These are object
s, so you need to either cast them or .ToString()
.
Handling the rows / sections logic similar to iOS's UITableView is not as simple in Android as it is in iOS, however, when you use RecyclerView - the flexibility of what you can do is far greater.
In the end, it's all about how you figure out what type of view you're displaying in the Adapter. Once you got that figured out, it should be easy sailing (not really, but at least you'll have that sorted).
The Adapter exposes two methods which you should override:
getItemViewType(int position)
This method's default implementation will always return 0, indicating that there is only 1 type of view. In your case, it is not so, and so you will need find a way to assert which row corresponds to which view type. Unlike iOS, which manages this for you with rows and sections, here you will have only one index to rely on, and you'll need to use your developer skills to know when a position correlates to a section header, and when it correlates to a normal row.
createViewHolder(ViewGroup parent, int viewType)
You need to override this method anyway, but usually people just ignore the viewType parameter. According to the view type, you'll need to inflate the correct layout resource and create your view holder accordingly. The RecyclerView will handle recycling different view types in a way which avoids clashing of different view types.
If you're planning on using a default LayoutManager, such as LinearLayoutManager
, you should be good to go. If you're planning on making your own LayoutManager implementation, you'll need to work a bit harder. The only API you really have to work with is findViewByPosition(int position)
which gives a given view at a certain position. Since you'll probably want to lay it out differently depending on what type this view is, you have a few options:
Usually when using the ViewHolder pattern, you set the view's tag with the view holder. You could use this during runtime in the layout manager to find out what type the view is by adding a field in the view holder which expresses this.
Since you'll need a function which determines which position correlates to which view type, you might as well make this method globally accessible somehow (maybe a singleton class which manages the data?), and then you can simply query the same method according to the position.
Here's a code sample:
// in this sample, I use an object array to simulate the data of the list.
// I assume that if the object is a String, it means I should display a header with a basic title.
// If not, I assume it's a custom model object I created which I will use to bind my normal rows.
private Object[] myData;
public static final int ITEM_TYPE_NORMAL = 0;
public static final int ITEM_TYPE_HEADER = 1;
public class MyAdapter extends Adapter<ViewHolder> {
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == ITEM_TYPE_NORMAL) {
View normalView = LayoutInflater.from(getContext()).inflate(R.layout.my_normal_row, null);
return new MyNormalViewHolder(normalView); // view holder for normal items
} else if (viewType == ITEM_TYPE_HEADER) {
View headerRow = LayoutInflater.from(getContext()).inflate(R.layout.my_header_row, null);
return new MyHeaderViewHolder(headerRow); // view holder for header items
}
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final int itemType = getItemViewType(position);
if (itemType == ITEM_TYPE_NORMAL) {
((MyNormalViewHolder)holder).bindData((MyModel)myData[position]);
} else if (itemType == ITEM_TYPE_HEADER) {
((MyHeaderViewHolder)holder).setHeaderText((String)myData[position]);
}
}
@Override
public int getItemViewType(int position) {
if (myData[position] instanceof String) {
return ITEM_TYPE_HEADER;
} else {
return ITEM_TYPE_NORMAL;
}
}
@Override
public int getItemCount() {
return myData.length;
}
}
Here's a sample of how these view holders should look like:
public MyHeaderViewHolder extends ViewHolder {
private TextView headerLabel;
public MyHeaderViewHolder(View view) {
super(view);
headerLabel = (TextView)view.findViewById(R.id.headerLabel);
}
public void setHeaderText(String text) {
headerLabel.setText(text);
}
}
public MyNormalViewHolder extends ViewHolder {
private TextView titleLabel;
private TextView descriptionLabel;
public MyNormalViewHolder(View view) {
super(view);
titleLabel = (TextView)view.findViewById(R.id.titleLabel);
descriptionLabel = (TextView)view.findViewById(R.id.descriptionLabel);
}
public void bindData(MyModel model) {
titleLabel.setText(model.getTitle());
descriptionLabel.setText(model.getDescription());
}
}
Of course, this sample assumes you've constructed your data source (myData) in a way that makes it easy to implement an adapter in this way. As an example, I'll show you how I'd construct a data source which shows a list of names, and a header for every time the 1st letter of the name changes (assume the list is alphabetized) - similar to how a contacts list would look like:
// Assume names & descriptions are non-null and have the same length.
// Assume names are alphabetized
private void processDataSource(String[] names, String[] descriptions) {
String nextFirstLetter = "";
String currentFirstLetter;
List<Object> data = new ArrayList<Object>();
for (int i = 0; i < names.length; i++) {
currentFirstLetter = names[i].substring(0, 1); // get the 1st letter of the name
// if the first letter of this name is different from the last one, add a header row
if (!currentFirstLetter.equals(nextFirstLetter)) {
nextFirstLetter = currentFirstLetter;
data.add(nextFirstLetter);
}
data.add(new MyModel(names[i], descriptions[i]));
}
myData = data.toArray();
}
This example comes to solve a fairly specific issue, but I hope this gives you a good overview on how to handle different row types in a recycler, and allows you make the necessary adaptations in your own code to fit your needs.
strace supported By Git,as Michael Fox Mention Maybe not useful for complex/windows software.
TortoiseSVN users: right click on the root project directory > TortoiseSVN > Clean up... (make sure you check all the boxes). This worked for me.
I haven't tried it, but iOS WebKit debug proxy (ios_webkit_debug_proxy / iwdp) supposedly lets you remotely debug UIWebView. From the README.md
The ios_webkit_debug_proxy (aka iwdp) allows developers to inspect MobileSafari and UIWebViews on real and simulated iOS devices via the Chrome DevTools UI and Chrome Remote Debugging Protocol. DevTools requests are translated into Apple's Remote Web Inspector service calls.
run Android SDK Manager as administrator. that solved my problem
sudo android
The T
doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.
The Z
stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).
Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime()
method. You could have used Q
or M
or Monty Python
and the method would have returned them unchanged as well; the method only looks for patterns starting with %
to replace those with information from the datetime
object.
This is my recommended approach.
To promote reusability, I'd say create a category of CAGradientLayer
and add your desired gradients as class methods. Specify them in the header
file like this :
#import <QuartzCore/QuartzCore.h>
@interface CAGradientLayer (SJSGradients)
+ (CAGradientLayer *)redGradientLayer;
+ (CAGradientLayer *)blueGradientLayer;
+ (CAGradientLayer *)turquoiseGradientLayer;
+ (CAGradientLayer *)flavescentGradientLayer;
+ (CAGradientLayer *)whiteGradientLayer;
+ (CAGradientLayer *)chocolateGradientLayer;
+ (CAGradientLayer *)tangerineGradientLayer;
+ (CAGradientLayer *)pastelBlueGradientLayer;
+ (CAGradientLayer *)yellowGradientLayer;
+ (CAGradientLayer *)purpleGradientLayer;
+ (CAGradientLayer *)greenGradientLayer;
@end
Then in your implementation file, specify each gradient with this syntax :
+ (CAGradientLayer *)flavescentGradientLayer
{
UIColor *topColor = [UIColor colorWithRed:1 green:0.92 blue:0.56 alpha:1];
UIColor *bottomColor = [UIColor colorWithRed:0.18 green:0.18 blue:0.18 alpha:1];
NSArray *gradientColors = [NSArray arrayWithObjects:(id)topColor.CGColor, (id)bottomColor.CGColor, nil];
NSArray *gradientLocations = [NSArray arrayWithObjects:[NSNumber numberWithInt:0.0],[NSNumber numberWithInt:1.0], nil];
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = gradientColors;
gradientLayer.locations = gradientLocations;
return gradientLayer;
}
Then simply import this category in your ViewController
or any other required subclass
, and use it like this :
CAGradientLayer *backgroundLayer = [CAGradientLayer purpleGradientLayer];
backgroundLayer.frame = self.view.frame;
[self.view.layer insertSublayer:backgroundLayer atIndex:0];
Smoke testing is about checking if the requirements are satisfied or not. Smoke testing is a general health check up.
Sanity testing is about checking if a particular module is completely working or not. Sanity testing is specialized in particular health check up.
I think you want an additional projection that maps each group to a sorted-version of the group:
.Select(group => group.OrderByDescending(student => student.Grade))
It also appears like you might want another flattening operation after that which will give you a sequence of students instead of a sequence of groups:
.SelectMany(group => group)
You can always collapse both into a single SelectMany
call that does the projection and flattening together.
EDIT:
As Jon Skeet points out, there are certain inefficiencies in the overall query; the information gained from sorting each group is not being used in the ordering of the groups themselves. By moving the sorting of each group to come before the ordering of the groups themselves, the Max
query can be dodged into a simpler First
query.
https://pythonhosted.org/pyexcel/iapi/pyexcel.sheets.Sheet.html see : row_range() Utility function to get row range
if you use pyexcel, can call row_range get max rows.
python 3.4 test pass.
You may get an unexpected result when the class doesn't have a namespace. I.e. get_class
returns Foo
, then $baseClass
would be oo
.
$baseClass = substr(strrchr(get_class($this), '\\'), 1);
This can easily be fixed by prefixing get_class
with a backslash:
$baseClass = substr(strrchr('\\'.get_class($this), '\\'), 1);
Now also classes without a namespace will return the right value.
I am not an expert but try white-space:nowrap;
The white-space property is supported in all major browsers.
Note: The value "inherit"
is not supported in IE7 and earlier. IE8 requires a !DOCTYPE
. IE9 supports "inherit"
.
"Assuming that you have nodejs installed",
mini-http is a pretty easy command-line tool to create http server,
install the package globally npm install mini-http -g
then using your cmd (terminal) run mini-http -p=3000
in your project directory
And boom! you created a server on port 3000 now go check http://localhost:3000
Note: specifying a port is not required you can simply run mini-http
or mh
to start the server
The difference lies in the fact that ./gradlew
indicates you are using a gradle wrapper. The wrapper is generally part of a project and it facilitates installation of gradle. If you were using gradle without the wrapper you would have to manually install it - for example, on a mac brew install gradle
and then invoke gradle using the gradle
command. In both cases you are using gradle, but the former is more convenient and ensures version consistency across different machines.
Each Wrapper is tied to a specific version of Gradle, so when you first run one of the commands above for a given Gradle version, it will download the corresponding Gradle distribution and use it to execute the build.
Not only does this mean that you don’t have to manually install Gradle yourself, but you are also sure to use the version of Gradle that the build is designed for. This makes your historical builds more reliable
Read more here - https://docs.gradle.org/current/userguide/gradle_wrapper.html
Also, Udacity has a neat, high level video explaining the concept of the gradle wrapper - https://www.youtube.com/watch?v=1aA949H-shk
Rebase and Cherry-pick is the only way you can keep clean commit history. Avoid using merge and avoid creating merge conflict. If you are using gerrit set one project to Merge if necessary and one project to cherry-pick mode and try yourself.
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream(new File(keyStoreFile)),
keyStorePassword.toCharArray());
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
new SSLContextBuilder()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.loadKeyMaterial(keyStore, keyStorePassword.toCharArray())
.build(),
NoopHostnameVerifier.INSTANCE);
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(
socketFactory).build();
ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
MyRecord record = restTemplate.getForObject(uri, MyRecord.class);
LOG.debug(record.toString());
df[df.columns.difference(['b'])]
Out:
a c d
0 0.427809 0.459807 0.333869
1 0.678031 0.668346 0.645951
2 0.996573 0.673730 0.314911
3 0.786942 0.719665 0.330833
truncate removes all the rows, but not the table itself, it is essentially equivalent to deleting with no where clause, but usually faster.
I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=D:\test.xls " & _
";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
strNaam = rs.Fields(0).Value
Next
rs.MoveNext
Loop
rs.Close
There are other ways, depending on what you want to do, such as GetString (GetString Method Description).
The dialog on this seems to be the antithesis of the conversation on naming interface
and abstract
classes. I find this alarming, and think that the decision runs much deeper than simply choosing one naming convention and using it always with static final
.
When naming interfaces and abstract classes, the accepted convention has evolved into not prefixing or suffixing your abstract class
or interface
with any identifying information that would indicate it is anything other than a class.
public interface Reader {}
public abstract class FileReader implements Reader {}
public class XmlFileReader extends FileReader {}
The developer is said not to need to know that the above classes are abstract
or an interface
.
My personal preference and belief is that we should follow similar logic when referring to static final
variables. Instead, we evaluate its usage when determining how to name it. It seems the all uppercase argument is something that has been somewhat blindly adopted from the C and C++ languages. In my estimation, that is not justification to continue the tradition in Java.
We should ask ourselves what is the function of static final
in our own context. Here are three examples of how static final
may be used in different contexts:
public class ChatMessage {
//Used like a private variable
private static final Logger logger = LoggerFactory.getLogger(XmlFileReader.class);
//Used like an Enum
public class Error {
public static final int Success = 0;
public static final int TooLong = 1;
public static final int IllegalCharacters = 2;
}
//Used to define some static, constant, publicly visible property
public static final int MAX_SIZE = Integer.MAX_VALUE;
}
Could you use all uppercase in all three scenarios? Absolutely, but I think it can be argued that it would detract from the purpose of each. So, let's examine each case individually.
In the case of the Logger
example above, the logger is declared as private, and will only be used within the class, or possibly an inner class. Even if it were declared at protected
or , its usage is the same:package
visibility
public void send(final String message) {
logger.info("Sending the following message: '" + message + "'.");
//Send the message
}
Here, we don't care that logger
is a static final
member variable. It could simply be a final
instance variable. We don't know. We don't need to know. All we need to know is that we are logging the message to the logger that the class instance has provided.
public class ChatMessage {
private final Logger logger = LoggerFactory.getLogger(getClass());
}
You wouldn't name it LOGGER
in this scenario, so why should you name it all uppercase if it was static final
? Its context, or intention, is the same in both circumstances.
Note: I reversed my position on package
visibility because it is more like a form of public
access, restricted to package
level.
Now you might say, why are you using static final
integers as an enum
? That is a discussion that is still evolving and I'd even say semi-controversial, so I'll try not to derail this discussion for long by venturing into it. However, it would be suggested that you could implement the following accepted enum pattern:
public enum Error {
Success(0),
TooLong(1),
IllegalCharacters(2);
private final int value;
private Error(final int value) {
this.value = value;
}
public int value() {
return value;
}
public static Error fromValue(final int value) {
switch (value) {
case 0:
return Error.Success;
case 1:
return Error.TooLong;
case 2:
return Error.IllegalCharacters;
default:
throw new IllegalArgumentException("Unknown Error value.");
}
}
}
There are variations of the above that achieve the same purpose of allowing explicit conversion of an enum->int
and int->enum
. In the scope of streaming this information over a network, native Java serialization is simply too verbose. A simple int
, short
, or byte
could save tremendous bandwidth. I could delve into a long winded compare and contrast about the pros and cons of enum
vs static final int
involving type safety, readability, maintainability, etc.; fortunately, that lies outside the scope of this discussion.
The bottom line is this, sometimes
static final int
will be used as anenum
style structure.
If you can bring yourself to accept that the above statement is true, we can follow that up with a discussion of style. When declaring an enum
, the accepted style says that we don't do the following:
public enum Error {
SUCCESS(0),
TOOLONG(1),
ILLEGALCHARACTERS(2);
}
Instead, we do the following:
public enum Error {
Success(0),
TooLong(1),
IllegalCharacters(2);
}
If your static final
block of integers serves as a loose enum
, then why should you use a different naming convention for it? Its context, or intention, is the same in both circumstances.
This usage case is perhaps the most cloudy and debatable of all. The static constant size usage example is where this is most often encountered. Java removes the need for sizeof()
, but there are times when it is important to know how many bytes a data structure will occupy.
For example, consider you are writing or reading a list of data structures to a binary file, and the format of that binary file requires that the total size of the data chunk be inserted before the actual data. This is common so that a reader knows when the data stops in the scenario that there is more, unrelated, data that follows. Consider the following made up file format:
File Format: MyFormat (MYFM) for example purposes only
[int filetype: MYFM]
[int version: 0] //0 - Version of MyFormat file format
[int dataSize: 325] //The data section occupies the next 325 bytes
[int checksumSize: 400] //The checksum section occupies 400 bytes after the data section (16 bytes each)
[byte[] data]
[byte[] checksum]
This file contains a list of MyObject
objects serialized into a byte stream and written to this file. This file has 325 bytes of MyObject
objects, but without knowing the size of each MyObject
you have no way of knowing which bytes belong to each MyObject
. So, you define the size of MyObject
on MyObject
:
public class MyObject {
private final long id; //It has a 64bit identifier (+8 bytes)
private final int value; //It has a 32bit integer value (+4 bytes)
private final boolean special; //Is it special? (+1 byte)
public static final int SIZE = 13; //8 + 4 + 1 = 13 bytes
}
The MyObject
data structure will occupy 13 bytes when written to the file as defined above. Knowing this, when reading our binary file, we can figure out dynamically how many MyObject
objects follow in the file:
int dataSize = buffer.getInt();
int totalObjects = dataSize / MyObject.SIZE;
This seems to be the typical usage case and argument for all uppercase static final
constants, and I agree that in this context, all uppercase makes sense. Here's why:
Java doesn't have a struct
class like the C language, but a struct
is simply a class with all public members and no constructor. It's simply a data struct
ure. So, you can declare a class
in struct
like fashion:
public class MyFile {
public static final int MYFM = 0x4D59464D; //'MYFM' another use of all uppercase!
//The struct
public static class MyFileHeader {
public int fileType = MYFM;
public int version = 0;
public int dataSize = 0;
public int checksumSize = 0;
}
}
Let me preface this example by stating I personally wouldn't parse in this manner. I'd suggest an immutable class instead that handles the parsing internally by accepting a ByteBuffer
or all 4 variables as constructor arguments. That said, accessing (setting in this case) this struct
s members would look something like:
MyFileHeader header = new MyFileHeader();
header.fileType = buffer.getInt();
header.version = buffer.getInt();
header.dataSize = buffer.getInt();
header.checksumSize = buffer.getInt();
These aren't static
or final
, yet they are publicly exposed members that can be directly set. For this reason, I think that when a static final
member is exposed publicly, it makes sense to uppercase it entirely. This is the one time when it is important to distinguish it from public, non-static variables.
Note: Even in this case, if a developer attempted to set a final
variable, they would be met with either an IDE or compiler error.
In conclusion, the convention you choose for static final
variables is going to be your preference, but I strongly believe that the context of use should heavily weigh on your design decision. My personal recommendation would be to follow one of the two methodologies:
[highly subjective; logical]
private
variable that should be indistinguishable from a private
instance variable, then name them the same. all lowercaseenum
style block of static
values, then name it as you would an enum
. pascal case: initial-cap each word[objective; logical]
Methodology 2 basically condenses its context into visibility, and leaves no room for interpretation.
private
or protected
then it should be all lowercase.public
or package
then it should be all uppercase.This is how I view the naming convention of static final
variables. I don't think it is something that can or should be boxed into a single catch all. I believe that you should evaluate its intent before deciding how to name it.
However, the main objective should be to try and stay consistent throughout your project/package's scope. In the end, that is all you have control over.
(I do expect to be met with resistance, but also hope to gather some support from the community on this approach. Whatever your stance, please keep it civil when rebuking, critiquing, or acclaiming this style choice.)
Another useful resource:
http://psoug.org/reference/roles.html
Try GraphIT from TechNewLogic, you can find it on CodePlex here: http://graphit.codeplex.com
Full Disclosure: I am the developer of GraphIT and owner of the developing company.
By Default it stores to:
String DATABASE_PATH = "/data/data/" + PACKAGE_NAME + "/databases/" + DATABASE_NAME;
Where:
String DATABASE_NAME = "your_dbname";
String PACKAGE_NAME = "com.example.your_app_name";
And check whether your database is stored to Device Storage. If So, You have to use permission in Manifest.xml :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Try this:
SELECT to_char(sysdate - (2 / 24), 'MM-DD-YYYY HH24') FROM DUAL
To test it using a new date instance:
SELECT to_char(TO_DATE('11/06/2015 00:00','dd/mm/yyyy HH24:MI') - (2 / 24), 'MM-DD-YYYY HH24:MI') FROM DUAL
Output is: 06-10-2015 22:00, which is the previous day.
Adding the following line of CSS works for Chrome, but not Internet Explorer or Firefox.
text-shadow: #fff 0px 1px 1px;
From a lambda, you can't get a reference to anything that isn't final. You need to declare a final wrapper from outside the lamda to hold your variable.
I've added the final 'reference' object as this wrapper.
private TimeZone extractCalendarTimeZoneComponent(Calendar cal,TimeZone calTz) {
final AtomicReference<TimeZone> reference = new AtomicReference<>();
try {
cal.getComponents().getComponents("VTIMEZONE").forEach(component->{
VTimeZone v = (VTimeZone) component;
v.getTimeZoneId();
if(reference.get()==null) {
reference.set(TimeZone.getTimeZone(v.getTimeZoneId().getValue()));
}
});
} catch (Exception e) {
//log.warn("Unable to determine ical timezone", e);
}
return reference.get();
}
Use somethings like this :
public static class PropertyExtension{
public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
{
PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
property.SetValue(p_object, Convert.ChangeType(value, property.PropertyType), null);
}
}
or
public static class PropertyExtension{
public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
{
PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
object safeValue = (value == null) ? null : Convert.ChangeType(value, t);
property.SetValue(p_object, safeValue, null);
}
}
The (+) operator indicates an outer join. This means that Oracle will still return records from the other side of the join even when there is no match. For example if a and b are emp and dept and you can have employees unassigned to a department then the following statement will return details of all employees whether or not they've been assigned to a department.
select * from emp, dept where emp.dept_id=dept.dept_id(+)
So in short, removing the (+) may make a significance difference but you might not notice for a while depending on your data!
mybytestring.encode(somecodec) is meaningful for these values of somecodec
:
I am not sure what decoding an already decoded unicode text is good for. Trying that with any encoding seems to always try to encode with the system's default encoding first.
Using reshape2
and dplyr
. Your data:
df <- read.table(text=
"tea coke beer water gender
14.55 26.50793651 22.53968254 40 1
24.92997199 24.50980392 26.05042017 24.50980393 2
23.03732304 30.63063063 25.41827542 20.91377091 1
225.51781276 24.6064623 24.85501243 50.80645161 1
24.53662842 26.03706973 25.24271845 24.18358341 2", header=TRUE)
Getting data into correct form:
library(reshape2)
library(dplyr)
df.melt <- melt(df, id="gender")
bar <- group_by(df.melt, variable, gender)%.%summarise(mean=mean(value))
Plotting:
library(ggplot2)
ggplot(bar, aes(x=variable, y=mean, fill=factor(gender)))+
geom_bar(position="dodge", stat="identity")
I think move
would probably be the closest standard cursor value for what you're doing:
move
Indicates something is to be moved.
The JSON you are receiving is in string. You have to convert it into JSON object You have commented the most important line of code
data = JSON.parse(data);
Or if you are using jQuery
data = $.parseJSON(data)
I've been using keyup on a number field, but today I noticed in chrome the input has up/down buttons to increase/decrease the value which aren't recognized by keyup.
My solution is to use keyup and change together:
(keyup)="unitsChanged[i] = true" (change)="unitsChanged[i] = true"
Initial tests indicate this works fine, will post back if any bugs found after further testing.
How about something like this, comments should explain:
--DJ - 2015-07-15 Example for view CREATE or REPLACE
--Replace with schema and view names
DECLARE @viewName NVARCHAR(30)= 'T';
DECLARE @schemaName NVARCHAR(30)= 'dbo';
--Leave this section as-is
BEGIN TRY
DECLARE @view AS NVARCHAR(100) = '
CREATE VIEW ' + @schemaName + '.' + @viewName + ' AS SELECT '''' AS [1]';
EXEC sp_executesql
@view;
END TRY
BEGIN CATCH
PRINT 'View already exists';
END CATCH;
GO
--Put full select statement here after modifying the view & schema name appropriately
ALTER VIEW [dbo].[T]
AS
SELECT '' AS [2];
GO
--Verify results with select statement against the view
SELECT *
FROM [T];
Cheers -DJ
// Initiate set interval and assign it to intervalListener
var intervalListener = self.setInterval(function () {someProcess()}, 1000);
function someProcess() {
console.log('someProcess() has been called');
// If some condition is true clear the interval
if (stopIntervalIsTrue) {
window.clearInterval(intervalListener);
}
}
Following is small snippet i've created in javascript to convert array of objects to hash map, indexed by attribute value of object. You can provide a function to evaluate the key of hash map dynamically (run time).
function isFunction(func){
return Object.prototype.toString.call(func) === '[object Function]';
}
/**
* This function converts an array to hash map
* @param {String | function} key describes the key to be evaluated in each object to use as key for hasmap
* @returns Object
* @Example
* [{id:123, name:'naveen'}, {id:345, name:"kumar"}].toHashMap("id")
Returns :- Object {123: Object, 345: Object}
[{id:123, name:'naveen'}, {id:345, name:"kumar"}].toHashMap(function(obj){return obj.id+1})
Returns :- Object {124: Object, 346: Object}
*/
Array.prototype.toHashMap = function(key){
var _hashMap = {}, getKey = isFunction(key)?key: function(_obj){return _obj[key];};
this.forEach(function (obj){
_hashMap[getKey(obj)] = obj;
});
return _hashMap;
};
You can find the gist here : https://gist.github.com/naveen-ithappu/c7cd5026f6002131c1fa
CASE might help you out:
SELECT t.first_name,
t.last_name,
t.employid,
t.status
FROM employeetable t
WHERE t.status = (CASE WHEN status_flag = STATUS_ACTIVE THEN 'A'
WHEN status_flag = STATUS_INACTIVE THEN 'T'
ELSE null END)
AND t.business_unit = (CASE WHEN source_flag = SOURCE_FUNCTION THEN 'production'
WHEN source_flag = SOURCE_USER THEN 'users'
ELSE null END)
AND t.first_name LIKE firstname
AND t.last_name LIKE lastname
AND t.employid LIKE employeeid;
The CASE statement evaluates multiple conditions to produce a single value. So, in the first usage, I check the value of status_flag, returning 'A', 'T' or null depending on what it's value is, and compare that to t.status. I do the same for the business_unit column with a second CASE statement.