You can declare as many Exceptions as you want for your interface method. But the class you gave in your question is invalid. It should read
public class MyClass implements MyInterface {
public void find(int x) throws A_Exception, B_Exception{
----
----
---
}
}
Then an interface would look like this
public interface MyInterface {
void find(int x) throws A_Exception, B_Exception;
}
all the solutions are not working with server-side or in angular universal
Spent some time working on a solution to my issue and thought it may be of interest. I ran into a problem trying to automate code generation using PowerShell 3.0 on Windows 8. The target IDE was the Keil compiler using MDK-ARM Essential Toolchain 5.24.1. A bit different from OP, as I am using PowerShell natively during the pre-build step. When I tried to #include the generated file, I received the error
fatal error: UTF-16 (LE) byte order mark detected '..\GITVersion.h' but encoding is not supported
I solved the problem by changing the line that generated the output file from:
out-file -FilePath GITVersion.h -InputObject $result
to:
out-file -FilePath GITVersion.h -Encoding ascii -InputObject $result
For strings you can just after process the string. For docstrings you need to after process the function instead. Here is a solution for both that is still readable.
class Lstrip(object):
def __rsub__(self, other):
import re
return re.sub('^\n', '', re.sub('\n$', '', re.sub('\n\s+', '\n', other)))
msg = '''
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.
''' - Lstrip()
print msg
def lstrip_docstring(func):
func.__doc__ = func.__doc__ - Lstrip()
return func
@lstrip_docstring
def foo():
'''
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.
'''
pass
print foo.__doc__
This works, as long as you remove the height attribute from the table.
<table id="content" border="0px" cellspacing="0px" cellpadding="0px">
<tr><td height='9px' bgcolor="#990000">Upper</td></tr>
<tr><td height='100px' bgcolor="#990099">Lower</td></tr>
</table>
This question is old, but I got here looking for a way to find a given query its field names in a dynamic way (not necessarily only the fields of a table). And since people keep pointing this as the answer for that given task in other related questions, I'm sharing the way I found it can be done, using Gavin Simpson's tips:
//Function to generate a HTML table from a SQL query
function myTable($obConn,$sql)
{
$rsResult = mysqli_query($obConn, $sql) or die(mysqli_error($obConn));
if(mysqli_num_rows($rsResult)>0)
{
//We start with header. >>>Here we retrieve the field names<<<
echo "<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"0\"><tr align=\"center\" bgcolor=\"#CCCCCC\">";
$i = 0;
while ($i < mysqli_num_fields($rsResult)){
$field = mysqli_fetch_field_direct($rsResult, $i);
$fieldName=$field->name;
echo "<td><strong>$fieldName</strong></td>";
$i = $i + 1;
}
echo "</tr>";
//>>>Field names retrieved<<<
//We dump info
$bolWhite=true;
while ($row = mysqli_fetch_assoc($rsResult)) {
echo $bolWhite ? "<tr bgcolor=\"#CCCCCC\">" : "<tr bgcolor=\"#FFF\">";
$bolWhite=!$bolWhite;
foreach($row as $data) {
echo "<td>$data</td>";
}
echo "</tr>";
}
echo "</table>";
}
}
This can be easily modded to insert the field names in an array.
Using a simple: $sql="SELECT * FROM myTable LIMIT 1"
can give you the fields of any table, without needing to use SHOW COLUMNS
or any extra php module, if needed (removing the data dump part).
Hopefully this helps someone else.
We can decode json string into array using json_decode function in php
1) json_decode($json_string) // it returns object
2) json_decode($json_string,true) // it returns array
$json_string = '{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}';
$array = json_decode($json_string,true);
echo $array['type']; //it gives donut
You can use destructuring to only focus on the part of your interest.
So you can do:
let str = "My cow always gives milk";
let [, result] = str.match(/\bcow\s+(.*?)\s+milk\b/) || [];
console.log(result);
_x000D_
In this way you ignore the first part (the complete match) and only get the capture group's match. The addition of || []
may be interesting if you are not sure there will be a match at all. In that case match
would return null
which cannot be destructured, and so we return []
instead in that case, and then result
will be null
.
The additional \b
ensures the surrounding words "cow" and "milk" are really separate words (e.g. not "milky"). Also \s+
is needed to avoid that the match includes some outer spacing.
SOAP 1.1 uses namespace http://schemas.xmlsoap.org/wsdl/soap/
SOAP 1.2 uses namespace http://schemas.xmlsoap.org/wsdl/soap12/
The wsdl is able to define operations under soap 1.1 and soap 1.2 at the same time in the same wsdl. Thats useful if you need to evolve your wsdl to support new functionality that requires soap 1.2 (eg. MTOM), in this case you dont need to create a new service but just evolve the original one.
Try creating a new pivot table, and not just refreshing.
I had a case where I forgot to add in a few dates. After adding them in I updated the pivot table range and hit refresh. They appeared at the end of the pivot table, out of order. I then tried to simply create a new pivot table and the dates where all in order.
In this code i is iterated till 3 then the loop ends;
int function (void)
{
for (int i=0; i<5; i++)
{
if (i == 3)
{
break;
}
}
}
In this code i is iterated till 3 but with an output;
int function (void)
{
for (int i=0; i<5; i++)
{
if (i == 3)
{
return i;
}
}
}
You should also be aware of the fact, that with utf8_general_ci when using a varchar field as unique or primary index inserting 2 values like 'a' and 'á' would give a duplicate key error.
To Replace backslash at particular location:
if ((stringValue.contains("\\"))&&(stringValue.indexOf("\\", location-1)==(location-1))) {
stringValue=stringValue.substring(0,location-1);
}
As other people suggested, you need to use a combobox. However, most tutorials show you how to set up just one combobox and the process is quite tedious.
As I faced this problem before when entering a large amount of data from a list, I can suggest you use this autocomplete add-in . It helps you create the combobox on any cells you select and you can define a list to appear in the dropdown.
The duplicate values in any column can be deleted with a simple for loop.
Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then Rows(a).Delete
Next
End Sub
select *
from my_table
where length( Name ) = (
select max( length( Name ) )
from my_table
limit 1
);
It this involves two table scans, and so might not be very fast !
If you're trying to access the property of an object, you have to start with the scope of window
and go through each property of the object until you get to the one you want. Assuming that a.b.c
has been defined somewhere else in the script, you can use the following:
var values = window;
var str = 'a.b.c'.values.split('.');
for(var i=0; i < str.length; i++)
values = values[str[i]];
This will work for getting the property of any object, no matter how deep it is.
The EntityManager doesn't flush change automatically by default. You should use the following option with your statement of query:
@Modifying(clearAutomatically = true)
@Query("update RssFeedEntry feedEntry set feedEntry.read =:isRead where feedEntry.id =:entryId")
void markEntryAsRead(@Param("entryId") Long rssFeedEntryId, @Param("isRead") boolean isRead);
Go through this and remove corresponding cache files in selected db then after you can drop your database
First find Your MySQL Data Directory Containing Your selected DB
Linux
Search for the term "datadir": /datadir
If it exists, it will highlight a line that reads: datadir = [path]
You can also manually look for that line. It typically would be found under a section heading of [mysqld] but it does not necessarily have to be found there.
If that line does not exist, then MySQL will default to: /var/lib/mysql.
Windows 1. Open up MySQL's configuration file into Notepad: my.ini
The my.ini will be located in the MySQL program folder, which would be wherever it got installed. If you did not install MySQL, then use the Windows "search" feature to look for my.ini. You could also manually search for it by browsing to [drive]:\Program Files\MySQL\MySQL Server 5.5.
Do a search in Notepad to find the term "datadir".
If it exists, it will highlight a line that reads: datadir = [path]
You can also manually look for that line. It typically would be found under a section heading of [mysqld] but it does not necessarily have to be found there.
If that line does not exist, then you'll probably find it under [drive]:\ProgramData\MySQL\MySQL Server 5.5\data.
NOTE: The "ProgramData" folder may be hidden. You may have to type the explicit path into Windows Explore
private void drawArrows(Point[] point, Canvas canvas, Paint paint) {
float [] points = new float[8];
points[0] = point[0].x;
points[1] = point[0].y;
points[2] = point[1].x;
points[3] = point[1].y;
points[4] = point[2].x;
points[5] = point[2].y;
points[6] = point[0].x;
points[7] = point[0].y;
canvas.drawVertices(VertexMode.TRIANGLES, 8, points, 0, null, 0, null, 0, null, 0, 0, paint);
Path path = new Path();
path.moveTo(point[0].x , point[0].y);
path.lineTo(point[1].x,point[1].y);
path.lineTo(point[2].x,point[2].y);
canvas.drawPath(path,paint);
}
Here I am going to explain not only the GROUP clause use, but also the Aggregate functions use.
The GROUP BY
clause is used in conjunction with the aggregate functions to group the result-set by one or more columns. e.g.:
-- GROUP BY with one parameter:
SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
-- GROUP BY with two parameters:
SELECT
column_name1,
column_name2,
AGGREGATE_FUNCTION(column_name3)
FROM
table_name
GROUP BY
column_name1,
column_name2;
Remember this order:
SELECT (is used to select data from a database)
FROM (clause is used to list the tables)
WHERE (clause is used to filter records)
GROUP BY (clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns)
HAVING (clause is used in combination with the GROUP BY clause to restrict the groups of returned rows to only those whose the condition is TRUE)
ORDER BY (keyword is used to sort the result-set)
You can use all of these if you are using aggregate functions, and this is the order that they must be set, otherwise you can get an error.
Aggregate Functions are:
MIN() returns the smallest value in a given column
MAX() returns the maximum value in a given column.
SUM() returns the sum of the numeric values in a given column
AVG() returns the average value of a given column
COUNT() returns the total number of values in a given column
COUNT(*) returns the number of rows in a table
SQL script examples about using aggregate functions:
Let's say we need to find the sale orders whose total sale is greater than $950. We combine the HAVING
clause and the GROUP BY
clause to accomplish this:
SELECT
orderId, SUM(unitPrice * qty) Total
FROM
OrderDetails
GROUP BY orderId
HAVING Total > 950;
Counting all orders and grouping them customerID and sorting the result ascendant. We combine the COUNT
function and the GROUP BY
, ORDER BY
clauses and ASC
:
SELECT
customerId, COUNT(*)
FROM
Orders
GROUP BY customerId
ORDER BY COUNT(*) ASC;
Retrieve the category that has an average Unit Price greater than $10, using AVG
function combine with GROUP BY
and HAVING
clauses:
SELECT
categoryName, AVG(unitPrice)
FROM
Products p
INNER JOIN
Categories c ON c.categoryId = p.categoryId
GROUP BY categoryName
HAVING AVG(unitPrice) > 10;
Getting the less expensive product by each category, using the MIN
function in a subquery:
SELECT categoryId,
productId,
productName,
unitPrice
FROM Products p1
WHERE unitPrice = (
SELECT MIN(unitPrice)
FROM Products p2
WHERE p2.categoryId = p1.categoryId)
The following statement groups rows with the same values in both categoryId and productId columns:
SELECT
categoryId, categoryName, productId, SUM(unitPrice)
FROM
Products p
INNER JOIN
Categories c ON c.categoryId = p.categoryId
GROUP BY categoryId, productId
Please try File-> Synchronize. Then close and reopen IntelliJ before you invalidate.
Once I restarted. I would have invalidated but the synchronize cleared everything after restarting.
The settings from the example above didn't work for the server I was using (authsmtp.com). I kept on getting this error:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
I removed the mail.smtp.socketFactory settings and everything worked. The final settings were this (SMTP auth was not used and I set the port elsewhere):
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.starttls.enable", "true");
had a simliar problem with that connection exception. it is thrown either when the registry is not started yet (like in your case) or when the registry is already unexported (like in my case).
but a short comment to the difference between the 2 ways to start the registry:
Runtime.getRuntime().exec("rmiregistry 2020");
runs the rmiregistry.exe in javas bin-directory in a new process and continues parallel with your java code.
LocateRegistry.createRegistry(2020);
the rmi method call starts the registry, returns the reference to that registry remote object and then continues with the next statement.
in your case the registry is not started in time when you try to bind your object
You also can take an array of keys with type []Value
by method MapKeys
of struct Value
from package "reflect":
package main
import (
"fmt"
"reflect"
)
func main() {
abc := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
keys := reflect.ValueOf(abc).MapKeys()
fmt.Println(keys) // [a b c]
}
Isn't it smoother to make a method to be called after the creation of the EditText unit in an AlertDialog, for general use?
public static void EditTextListPicker(final Activity activity, final EditText EditTextItem, final String SelectTitle, final String[] SelectList) {
EditTextItem.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(SelectTitle);
builder.setItems(SelectList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
EditTextItem.setText(SelectList[item]);
}
});
builder.create().show();
return false;
}
});
}
If your query has any JOINs, Mysql Workbench will not allow you to alter the table, even if your results are all from a single table.
For example, the following query
SELECT u.* FROM users u JOIN passwords p ON u.id=p.user_id WHERE p.password IS NULL;
will not allow you to edit the results or add rows, even though the results are limited to one table. You must specifically do something like:
SELECT * FROM users WHERE id=1012;
and then you can edit the row and add rows to the table.
This is Very Good Example of minus Length of an array in java, i am giving here both examples
public static int linearSearchArray(){
int[] arrayOFInt = {1,7,5,55,89,1,214,78,2,0,8,2,3,4,7};
int key = 7;
int i = 0;
int count = 0;
for ( i = 0; i< arrayOFInt.length; i++){
if ( arrayOFInt[i] == key ){
System.out.println("Key Found in arrayOFInt = " + arrayOFInt[i] );
count ++;
}
}
System.out.println("this Element found the ("+ count +") number of Times");
return i;
}
this above i < arrayOFInt.length; not need to minus one by length of array; but if you i <= arrayOFInt.length -1; is necessary other wise arrayOutOfIndexException Occur, hope this will help you.
>>> L = [1,2,3]
>>> " ".join(str(x) for x in L)
'1 2 3'
I'm would recommend it:
<style>
.clearfix {
*zoom: 1;
}
.clearfix:before,
.clearfix:after {
content: " ";
display: table;
}
.clearfix:after {
clear: both;
}
ul.list {
list-style: none;
}
ul.list li {
display: inline-block;
}
</style>
<ul class="list clearfix">
<li>li-one</li>
<li>li-two</li>
<li>li-three</li>
<li>li-four</li>
</ul>
No, since the new throw
is not in the try
block directly.
Here's what I used:
In JavaScript:
var url = "http://www.mynewsfeed.com/articles/index.php?id=17";
var encoded_url = encodeURIComponent(url);
var decoded_url = decodeURIComponent(encoded_url);
In PHP:
$url = "http://www.mynewsfeed.com/articles/index.php?id=17";
$encoded_url = url_encode(url);
$decoded_url = url_decode($encoded_url);
You can also try it online here: http://www.mynewsfeed.x10.mx/articles/index.php?id=17
I have this function for this case ..
Function GetValue(r As Range, Tag As String) As Integer
Dim c, nRet As String
Dim n, x As Integer
Dim bNum As Boolean
c = r.Value
n = InStr(c, Tag)
For x = n + 1 To Len(c)
Select Case Mid(c, x, 1)
Case ":": bNum = True
Case " ": Exit For
Case Else: If bNum Then nRet = nRet & Mid(c, x, 1)
End Select
Next
GetValue = val(nRet)
End Function
To fill cell BC .. (assumed that you check cell A1)
Worksheets("Übersicht_2013").Cells(i, "BC") = GetValue(range("A1"),"S")
Even if that's a 7 years old question, people new to R should consider using the data.table, package.
A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.
vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]
You can do this by using Year(), Month() Day() and datepart().
In you example this would be:
select Closing_Date, Category, COUNT(Status)TotalCount from MyTable
where Closing_Date >= '2012-02-01' and Closing_Date <= '2012-12-31'
and Defect_Status1 is not null
group by Year(Closing_Date), Month(Closing_Date), Category
All modern browsers (tested with Chrome 4, Firefox 3.5, IE8, Opera 10 and Safari 4) will always request a favicon.ico
unless you've specified a shortcut icon via <link>
. So if you don't explicitly specify one, it's best to always have a favicon.ico
file, to avoid a 404. Yahoo! suggests you make it small and cacheable.
And you don't have to go for a PNG just for the alpha transparency either. ICO files support alpha transparency just fine (i.e. 32-bit color), though hardly any tools allow you to create them. I regularly use Dynamic Drive's FavIcon Generator to create favicon.ico
files with alpha transparency. It's the only online tool I know of that can do it.
There's also a free Photoshop plug-in that can create them.
C and C++ used to be defined by an execution trace of a well formed program.
Now they are half defined by an execution trace of a program, and half a posteriori by many orderings on synchronisation objects.
Meaning that these language definitions make no sense at all as no logical method to mix these two approaches. In particular, destruction of a mutex or atomic variable is not well defined.
Sorry to dig up an old question but in case someone stumbles onto this thread and wants a quicker solution.
Bulk inserting a unknown width file with \n row terminators into a temp table that is created outside of the EXEC statement.
DECLARE @SQL VARCHAR(8000)
IF OBJECT_ID('TempDB..#BulkInsert') IS NOT NULL
BEGIN
DROP TABLE #BulkInsert
END
CREATE TABLE #BulkInsert
(
Line VARCHAR(MAX)
)
SET @SQL = 'BULK INSERT #BulkInser FROM ''##FILEPATH##'' WITH (ROWTERMINATOR = ''\n'')'
EXEC (@SQL)
SELECT * FROM #BulkInsert
Further support that dynamic SQL within an EXEC statement has access to temp tables outside of the EXEC statement. http://sqlfiddle.com/#!3/d41d8/19343
DECLARE @SQL VARCHAR(8000)
IF OBJECT_ID('TempDB..#BulkInsert') IS NOT NULL
BEGIN
DROP TABLE #BulkInsert
END
CREATE TABLE #BulkInsert
(
Line VARCHAR(MAX)
)
INSERT INTO #BulkInsert
(
Line
)
SELECT 1
UNION SELECT 2
UNION SELECT 3
SET @SQL = 'SELECT * FROM #BulkInsert'
EXEC (@SQL)
Further support, written for MSSQL2000 http://technet.microsoft.com/en-us/library/aa175921(v=sql.80).aspx
Example at the bottom of the link
DECLARE @cmd VARCHAR(1000), @ExecError INT
CREATE TABLE #ErrFile (ExecError INT)
SET @cmd = 'EXEC GetTableCount ' +
'''pubs.dbo.authors''' +
'INSERT #ErrFile VALUES(@@ERROR)'
EXEC(@cmd)
SET @ExecError = (SELECT * FROM #ErrFile)
SELECT @ExecError AS '@@ERROR'
In SQL, there is only one kind of relationship, it is called a Reference. (Your front end may do helpful or confusing things [such as in some of the Answers], but that is a different story.)
In SQL terms, Bar references Foo
Not the other way around
CREATE TABLE Foo (
Foo CHAR(10) NOT NULL, -- primary key
Name CHAR(30) NOT NULL
CONSTRAINT PK -- constraint name
PRIMARY KEY (Foo) -- pk
)
CREATE TABLE Bar (
Bar CHAR(10) NOT NULL, -- primary key
Foo CHAR(10) NOT NULL, -- foreign key to Foo
Name CHAR(30) NOT NULL
CONSTRAINT PK -- constraint name
PRIMARY KEY (Bar), -- pk
CONSTRAINT Foo_HasMany_Bars -- constraint name
FOREIGN KEY (Foo) -- fk in (this) referencing table
REFERENCES Foo(Foo) -- pk in referenced table
)
Since Foo.Foo
is a Primary Key, it is unique, there is only one row for any given value of Foo
Bar.Foo
is a Reference, a Foreign Key, and there is no unique index on it, there can be many rows for any given value of Foo
Foo::Bar
is one-to-many Bar::Foo
is many-to-one
Bar
row, there is just one Foo
row that it ReferencesWhat is the real difference between one to many and many to one relationship?
There is only one relation, therefore there is no difference. Perception (from one "end" or the other "end") or reading it backwards, does not change the relation.
Cardinality is declared first in the data model, which means Logical and Physical (the intent), and then in the implementation (the intent realised).
One to zero-to-many
In SQL that (the above) is all that is required.
One to one-to-many
You need a Transaction to enforce the one in the Referencing table.
One to zero-to-one
You need in Bar
:
CONSTRAINT AK -- constraint name
UNIQUE (Foo) -- unique column, which makes it an Alternate Key
One to one
You need a Transaction to enforce the one in the Referencing table.
Many to many
There is no such thing at the Physical level (recall, there is only one type of relation in SQL).
At the early Logical levels during the modelling exercise, it is convenient to draw such a relation. Before the model gets close to implementation, it had better be elevated to using only things that can exist. Such a relation is resolved by implementing an Associative Table.
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string s="000101";
cout<<s<<"\n";
int a = stoi(s);
cout<<a<<"\n";
s=to_string(a);
s+='1';
cout<<s;
return 0;
}
Output:
You can double click directly on the .cs file representing your form in the Solution Explorer :
This will open Form1.cs [Design]
, which contains the drag&drop controls.
If you are directly in the code behind (The file named Form1.cs
, without "[Design]"), you can press Shift + F7 (or only F7 depending on the project type) instead to open it.
From the design view, you can switch back to the Code Behind by pressing F7.
Currently, UUID's are as specified in RFC4122. An often neglected edge case is the NIL UUID, noted here. The following regex takes this into account and will return a match for a NIL UUID. See below for a UUID which only accepts non-NIL UUIDs. Both of these solutions are for versions 1 to 5 (see the first character of the third block).
Therefore to validate a UUID...
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i
...ensures you have a canonically formatted UUID that is Version 1 through 5 and is the appropriate Variant as per RFC4122.
NOTE: Braces {
and }
are not canonical. They are an artifact of some systems and usages.
Easy to modify the above regex to meet the requirements of the original question.
HINT: regex group/captures
To avoid matching NIL UUID:
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
AFAIK, the only way this could be done is by using the state=directory
option.
While template
module supports most of copy
options, which in turn supports most file
options, you can not use something like state=directory
with it. Moreover, it would be quite confusing (would it mean that {{project_root}}/conf/code.conf
is a directory ? or would it mean that {{project_root}}/conf/
should be created first.
So I don't think this is possible right now without adding a previous file
task.
- file:
path: "{{project_root}}/conf"
state: directory
recurse: yes
<div ng-controller="ExampleController">
<form name="myForm">
<label for="repeatSelect"> Repeat select: </label>
<select name="repeatSelect" id="repeatSelect" ng-model="data.model">
<option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
</select>
</form>
<hr>
<tt>model = {{data.model}}</tt><br/>
</div>
AngularJS:
angular.module('ngrepeatSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
model: null,
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
]
};
}]);
taken from AngularJS docs
By doing so you'd be able to control any action of the framed page, which you cannot. Same-domain origin policy applies.
find location -ctime time_period
Examples of time_period:
More than 30 days ago: -ctime +30
Less than 30 days ago: -ctime -30
Exactly 30 days ago: -ctime 30
datetime has fields hour
and minute
. So to get the hours and minutes, you would use t1.hour
and t1.minute
.
However, when you subtract two datetimes, the result is a timedelta, which only has the days
and seconds
fields. So you'll need to divide and multiply as necessary to get the numbers you need.
A funny way to remove all spaces from a variable is to use printf:
$ myvar='a cool variable with lots of spaces in it'
$ printf -v myvar '%s' $myvar
$ echo "$myvar"
acoolvariablewithlotsofspacesinit
It turns out it's slightly more efficient than myvar="${myvar// /}"
, but not safe regarding globs (*
) that can appear in the string. So don't use it in production code.
If you really really want to use this method and are really worried about the globbing thing (and you really should), you can use set -f
(which disables globbing altogether):
$ ls
file1 file2
$ myvar=' a cool variable with spaces and oh! no! there is a glob * in it'
$ echo "$myvar"
a cool variable with spaces and oh! no! there is a glob * in it
$ printf '%s' $myvar ; echo
acoolvariablewithspacesandoh!no!thereisaglobfile1file2init
$ # See the trouble? Let's fix it with set -f:
$ set -f
$ printf '%s' $myvar ; echo
acoolvariablewithspacesandoh!no!thereisaglob*init
$ # Since we like globbing, we unset the f option:
$ set +f
I posted this answer just because it's funny, not to use it in practice.
This code works for me. When keyboard appears, you can scroll screen
In AndroidManifest.xml
<activity android:name=".signup.screen_2.SignUpNameAndPasswordActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize">
</activity>
activity_sign_up.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
tools:context=".signup.screen_2.SignUpNameAndPasswordActivity">
<LinearLayout
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_marginTop="@dimen/dp_24"
android:layout_marginStart="@dimen/dp_24"
android:layout_marginEnd="@dimen/dp_24"
android:id="@+id/lin_name_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:fontFamily="sans-serif-medium"
android:text="@string/name_and_password"
android:textColor="@color/colorBlack"
android:layout_marginTop="@dimen/dp_5"
android:textSize="@dimen/ts_16"/>
<EditText
android:id="@+id/edit_full_name"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_44"
app:layout_constraintTop_toTopOf="parent"
android:hint="@string/email_address_hint"
android:inputType="textPersonName"
android:imeOptions="flagNoFullscreen"
android:textSize="@dimen/ts_15"
android:background="@drawable/rounded_border_edittext"
android:layout_marginTop="@dimen/dp_15"
android:paddingStart="@dimen/dp_8"
android:paddingEnd="@dimen/dp_8"
android:maxLength="100"
android:maxLines="1"/>
<EditText
android:id="@+id/edit_password"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_44"
app:layout_constraintTop_toTopOf="parent"
android:hint="@string/password"
android:inputType="textPassword"
android:imeOptions="flagNoFullscreen"
android:textSize="@dimen/ts_15"
android:background="@drawable/rounded_border_edittext"
android:layout_marginTop="@dimen/dp_15"
android:paddingStart="@dimen/dp_8"
android:paddingEnd="@dimen/dp_8"
android:maxLength="100"
android:maxLines="1"/>
<TextView
android:id="@+id/btn_continue_and_sync_contacts"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_44"
android:gravity="center"
android:clickable="true"
android:focusable="true"
android:layout_marginTop="@dimen/dp_15"
android:background="@drawable/btn_blue_selector"
android:enabled="false"
android:text="@string/continue_and_sync_contacts"
android:textColor="@color/colorWhite"
android:textSize="@dimen/ts_15"
android:textStyle="bold"/>
<TextView
android:id="@+id/btn_continue_without_syncing_contacts"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_44"
android:gravity="center"
android:clickable="true"
android:focusable="true"
android:layout_marginTop="@dimen/dp_10"
android:enabled="false"
android:text="@string/continue_without_syncing_contacts"
android:textColor="@color/colorBlue"
android:textSize="@dimen/ts_15"
android:textStyle="bold"/>
</LinearLayout>
<!--RelativeLayout is scaled when keyboard appears-->
<RelativeLayout
android:layout_marginStart="@dimen/dp_24"
android:layout_marginEnd="@dimen/dp_24"
android:layout_marginBottom="@dimen/dp_20"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_learn_more_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:layout_gravity="center_horizontal"
android:text="@string/learn_more_syncing_contacts"
android:textColor="@color/black_alpha_70"
android:gravity="center"
android:layout_marginBottom="1dp"
android:textSize="@dimen/ts_13"/>
<TextView
android:id="@+id/tv_learn_more_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:layout_gravity="center_horizontal"
android:text="@string/learn_more"
android:fontFamily="sans-serif-medium"
android:textColor="@color/black_alpha_70"
android:textSize="@dimen/ts_13"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</ScrollView>
rounded_border_edittext.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true">
<shape android:shape="rectangle">
<solid android:color="#F6F6F6"/>
<corners android:radius="3dp"/>
<stroke
android:width="1dp"
android:color="@color/red"/>
</shape>
</item>
<item android:state_activated="false">
<shape android:shape="rectangle">
<solid android:color="#F6F6F6"/>
<corners android:radius="3dp"/>
<stroke
android:width="1dp"
android:color="@color/colorGray"/>
</shape>
</item>
</selector>
btn_blue_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true" android:state_pressed="true">
<shape android:shape="rectangle">
<corners android:radius="3dp"/>
<solid android:color="@color/colorBlueLight"/>
<stroke android:width="1dp" android:color="@color/colorBlueLight"/>
</shape>
</item>
<item android:state_enabled="true">
<shape android:shape="rectangle">
<corners android:radius="3dp"/>
<solid android:color="@color/colorBlue"/>
<stroke android:width="1dp" android:color="@color/colorBlue"/>
</shape>
</item>
<item android:state_enabled="false">
<shape android:shape="rectangle">
<corners android:radius="3dp"/>
<solid android:color="@color/colorBlueAlpha"/>
<stroke android:width="0dp" android:color="@color/colorBlueAlpha"/>
</shape>
</item>
</selector>
I had the same problem.
Solved by sharing internet connection (on the hosting OS).
Network Connection Properties -> advanced -> Allow other users to connect...
If you need a small and specific mechanism, you can search for DLL Triggers info.
<table style='border:1px solid black'>
<tr>
<td>Derp</td>
</tr>
</table>
This should work. I use the shorthand syntax for borders.
What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.
Why not do something like this:
var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';
nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.
For Windows users: Try deleting files: java.exe, javaw.exe and javaws.exe from Windows\System32
My issue was the java version 1.7 installed.
I tried the example that you have provided and the only difference is that you have True and False values switched as @bdparrish
had pointed out. Here is a working example of making an SSRS Texbox visible or hidden based on the number of rows present in a dataset. This example uses SSRS 2008 R2
.
Step-by-step process: SSRS 2008 R2
In this example, the report has a dataset named Items
and has textbox to show row counts. It also has another textbox which will be visible only if the dataset Items has rows.
Right-click on the textbox that should be visible/hidden based on an expression and select Text Box Properties...
. Refer screenshot #1.
On the Text Box Properties
dialog, click on Visibility
from the left section. Refer screenshot #2.
Select Show or hide based on an epxression
.
Click on the expression button fx
.
Enter the expression =IIf(CountRows("Items") = 0 , True, False)
. Note that this expression is to hide the Textbox (Hidden).
Click OK twice to close the dialogs.
Screenshot #3 shows data in the SQL Server table dbo.Items
, which is the source for the report data set Items
. The table contains 3 rows. Screenshot #4 shows the sample report execution against the data.
Screenshot #5 shows data in the SQL Server table dbo.Items
, which is the source for the report data set Items
. The table contains no data. Screenshot #6 shows the sample report execution against the data.
Hope that helps.
Screenshot #1:
Screenshot #2:
Screenshot #3:
Screenshot #4:
Screenshot #5:
Screenshot #6:
In R the equivalent function is seq
and you can use it with the option by
:
seq(from = 5, to = 100, by = 5)
# [1] 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100
In addition to by
you can also have other options such as length.out
and along.with
.
length.out: If you want to get a total of 10 numbers between 0 and 1, for example:
seq(0, 1, length.out = 10)
# gives 10 equally spaced numbers from 0 to 1
along.with: It takes the length of the vector you supply as input and provides a vector from 1:length(input).
seq(along.with=c(10,20,30))
# [1] 1 2 3
Although, instead of using the along.with
option, it is recommended to use seq_along
in this case. From the documentation for ?seq
seq
is generic, and only the default method is described here. Note that it dispatches on the class of the first argument irrespective of argument names. This can have unintended consequences if it is called with just one argument intending this to be taken as along.with: it is much better to useseq_along
in that case.
seq_along: Instead of seq(along.with(.))
seq_along(c(10,20,30))
# [1] 1 2 3
Hope this helps.
Something like this should work:
sh -c 'cd /tmp && exec pwd'
from urllib.request import Request, urlopen
url="https://svnweb.freebsd.org/csrg/share/dict/words?revision=61569&view=co"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
web_byte = urlopen(req).read()
webpage = web_byte.decode('utf-8')
print(webpage)
Randomizing the first 500 words
from urllib.request import Request, urlopen
import random
url="https://svnweb.freebsd.org/csrg/share/dict/words?revision=61569&view=co"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
web_byte = urlopen(req).read()
webpage = web_byte.decode('utf-8')
first500 = webpage[:500].split("\n")
random.shuffle(first500)
print(first500)
Output
['abnegation', 'able', 'aborning', 'Abigail', 'Abidjan', 'ablaze', 'abolish', 'abbe', 'above', 'abort', 'aberrant', 'aboriginal', 'aborigine', 'Aberdeen', 'Abbott', 'Abernathy', 'aback', 'abate', 'abominate', 'AAA', 'abc', 'abed', 'abhorred', 'abolition', 'ablate', 'abbey', 'abbot', 'Abelson', 'ABA', 'Abner', 'abduct', 'aboard', 'Abo', 'abalone', 'a', 'abhorrent', 'Abelian', 'aardvark', 'Aarhus', 'Abe', 'abjure', 'abeyance', 'Abel', 'abetting', 'abash', 'AAAS', 'abdicate', 'abbreviate', 'abnormal', 'abject', 'abacus', 'abide', 'abominable', 'abode', 'abandon', 'abase', 'Ababa', 'abdominal', 'abet', 'abbas', 'aberrate', 'abdomen', 'abetted', 'abound', 'Aaron', 'abhor', 'ablution', 'abeyant', 'about']
Make sure the scp command is available on both sides - both on the client and on the server.
If this is Fedora or Red Hat Enterprise Linux and clones (CentOS), make sure this package is installed:
yum -y install openssh-clients
If you work with Debian or Ubuntu and clones, install this package:
apt-get install openssh-client
Again, you need to do this both on the server and the client, otherwise you can encounter "weird" error messages on your client: scp: command not found
or similar although you have it locally. This already confused thousands of people, I guess :)
Solution: Remove STRICT_TRANS_TABLES
from sql_mode
To check your default setting,
mysql> set @@sql_mode =
'STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
Query OK, 0 rows affected (0.00 sec)
mysql> select @@sql_mode;
+----------------------------------------------------------------+
| @@sql_mode |
+----------------------------------------------------------------+
| STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION |
+----------------------------------------------------------------+
1 row in set (0.00 sec)
Run a sample query
mysql> INSERT INTO nb (id) VALUES(3);
ERROR 1364 (HY000): Field 'field' doesn't have a default value
Remove your STRICT_TRANS_TABLES
by resetting it to null.
mysql> set @@sql_mode = '';
Query OK, 0 rows affected (0.00 sec)
Now, run the same test query.
mysql> INSERT INTO nb (id) VALUES(3);
Query OK, 1 row affected, 1 warning (0.00 sec)
Source: https://netbeans.org/bugzilla/show_bug.cgi?id=190731
For v3 users.
http://google.github.io/proto-lens/installing-protoc.html
PROTOC_ZIP=protoc-3.7.1-osx-x86_64.zip
curl -OL https://github.com/protocolbuffers/protobuf/releases/download/v3.7.1/$PROTOC_ZIP
sudo unzip -o $PROTOC_ZIP -d /usr/local bin/protoc
sudo unzip -o $PROTOC_ZIP -d /usr/local 'include/*'
rm -f $PROTOC_ZIP
That you are running Windows. Read:
http://en.wikipedia.org/wiki/Sudo
It basically allows you to execute an application with elevated privileges. If you want to achieve a similar effect under Windows, open an administrative prompt and execute your command from there. Under Vista, this is easily done by opening the shortcut while holding Ctrl+Shift at the same time.
That being said, it might very well be possible that your account already has sufficient privileges, depending on how your OS is setup, and the Windows version used.
IE < 8 does not render the dropdown list itself it just uses the windows control which cannot be styled this way. Beginning from IE 8 this has changed and the styling is now applied. Of course, its market share is rather negligible yet.
The 2 highest upvoted answers are correct. As of today, the only thing I needed to change (from default settings) was to enable generation using dot instead of the built-in generator.
Some important notes:
html/inherits.html
or (from the website navigation) classes => class hierarchy => "Go to the textual class hierarchy".T
.
foo
inherits from T
and the T
template type parameter has a default, such default will be assumed. If there is a type bar
which inherits from foo<U>
where U
is different than the default, bar
will have a foo<U>
parent. foo<>
and bar<U>
will not have a common parent.variant
instantiation will be displayed to inherit from variant<Ts...>
.<...>
string in their name representing type and non-type parameters which did not have defaults.The document has moved here it seems: https://help.apple.com/xcode/mac/8.0/#/dev564169bb1
Can't copy the icons here, but here are the descriptions:
Show: Present the content in the detail or master area depending on the content of the screen.
If the app is displaying a master and detail view, the content is pushed onto the detail area. If the app is only displaying the master or the detail, the content is pushed on top of the current view controller stack.
Show Detail: Present the content in the detail area.
If the app is displaying a master and detail view, the new content replaces the current detail. If the app is only displaying the master or the detail, the content replaces the top of the current view controller stack.
Present Modally: Present the content modally.
Present as Popover: Present the content as a popover anchored to an existing view.
Custom: Create your own behaviors by using a custom segue.
Using Underscore.js:
var myArray = [
Object { key="11", value="1100", $$hashKey="00X"},
Object { key="22", value="2200", $$hashKey="018"}
];
var myObj = _.object(_.pluck(myArray, 'key'), _.pluck(myArray, 'value'));
Under Window Administrative Tools, run ODBC Data Sources (32-bit).
Under the Drivers tab, check you have the Microsoft Excel Driver (*.xls, *.xlsx etc...) - the file name is ACEODBC.DLL
If this is missing, you will need to install the Microsoft Access Database Engine 2016 Redistributable.
You'll find the installer here https://www.microsoft.com/en-us/download/details.aspx?id=54920
Set objConn1 = Server.CreateObject("ADODB.Connection")
objConn1.Provider = "Microsoft.ACE.OLEDB.12.0"
objConn1.ConnectionString = "Data Source=" & pPath & ";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1"""
If your current line wraps around the visible screen onto the next line, you can use g$ to get to the end of the screen line.
Amber's answer is correct but I found it unclear; The syntax is:
git blame {commit_id} -- {path/to/file}
Note: the --
is used to separate the tree-ish sha1 from the relative file paths. 1
For example:
git blame master -- index.html
Full credit to Amber for knowing all the things! :)
With an Android-powered device, you can develop and debug your Android applications just as you would on the emulator.
1. Declare your application as "debuggable" in AndroidManifest.xml
.
<application
android:debuggable="true"
... >
...
</application>
2. On your handset, navigate to Settings > Security and check Unknown sources
3. Go to Settings > Developer Options and check USB debugging
Note that if Developer Options
is invisible you will need to navigate to Settings > About Phone and tap on Build number
several times until you are notified that it has been unlocked.
4. Set up your system to detect your device.
Follow the instructions below for your OS:
Install the Google USB Driver from the ADT SDK Manager
(Support for: ADP1, ADP2, Verizon Droid, Nexus One, Nexus S).
For devices not listed above, install an OEM driver for your device
Your device should automatically work; Go to the next step
Add a udev
rules file that contains a USB configuration for each type of device you want to use for development. In the rules file, each device manufacturer is identified by a unique vendor ID, as specified by the ATTR{idVendor} property. For a list of vendor IDs, click here. To set up device detection on Ubuntu Linux:
/etc/udev/rules.d/51-android.rules
.SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"
chmod a+r /etc/udev/rules.d/51-android.rules
Note: The rule syntax may vary slightly depending on your environment. Consult the udev documentation for your system as needed. For an overview of rule syntax, see this guide to writing udev rules.
5. Run the project with your connected device.
With Eclipse/ADT: run or debug your application as usual. You will be presented with a Device Chooser dialog that lists the available emulator(s) and connected device(s).
With ADB: issue commands with the -d flag to target your connected device.
Still need help? Click here for the full guide.
There are standard statistical functions and methods for finding outliers to data, which is probably what you need in the first case. Using derivatives would solve your second. I'm not sure for a method which solves both continuous functions and sampled data, however.
You might also look at apache commons IO, it has a built in last modified comparator and many other nice utilities for working with files.
You could use the Laravel query builder, but this is not the best way to do it.
Check Wader's answer below for the Eloquent way - which is better as it allows you to check that there is actually a user that matches the email address, and handle the error if there isn't.
DB::table('users')
->where('email', $userEmail) // find your user by their email
->limit(1) // optional - to ensure only one record is updated.
->update(array('member_type' => $plan)); // update the record in the DB.
If you have multiple fields to update you can simply add more values to that array at the end.
Its workaround.
If you not push to server, you will clone into new folder else washout(delete all files) from your repository folder and clone new.
I used the solution below to export all datagrid values to a text file, rather than using the column names you can use the column index instead.
foreach (DataGridViewRow row in xxxCsvDG.Rows)
{
File.AppendAllText(csvLocation, row.Cells[0].Value + "," + row.Cells[1].Value + "," + row.Cells[2].Value + "," + row.Cells[3].Value + Environment.NewLine);
}
Below code is working on my live server as well as in my own Lapy.
Note:
Please Create data folder in WebContent and put in any single image or any file(jsp or html file).
Add jar files
commons-collections-3.1.jar
commons-fileupload-1.2.2.jar
commons-io-2.1.jar
commons-logging-1.0.4.jar
upload.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="dataFile" id="fileChooser"/><br/><br/>
<input type="submit" value="Upload" />
</form>
</body>
</html>
UploadServlet.java
package com.servlet;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class UploadServlet
*/
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String DATA_DIRECTORY = "data";
private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
private static final int MAX_REQUEST_SIZE = 1024 * 1024;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
return;
}
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Sets the size threshold beyond which files are written directly to
// disk.
factory.setSizeThreshold(MAX_MEMORY_SIZE);
// Sets the directory used to temporarily store files that are larger
// than the configured size threshold. We use temporary directory for
// java
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
// constructs the folder where uploaded file will be stored
String uploadFolder = getServletContext().getRealPath("")
+ File.separator + DATA_DIRECTORY;
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(MAX_REQUEST_SIZE);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadFolder + File.separator + fileName;
File uploadedFile = new File(filePath);
System.out.println(filePath);
// saves the file to upload directory
item.write(uploadedFile);
}
}
// displays done.jsp page after upload finished
getServletContext().getRequestDispatcher("/done.jsp").forward(
request, response);
} catch (FileUploadException ex) {
throw new ServletException(ex);
} catch (Exception ex) {
throw new ServletException(ex);
}
}
}
web.xml
<servlet>
<description></description>
<display-name>UploadServlet</display-name>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.servlet.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
done.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Done</title>
</head>
<body>
<h3>Your file has been uploaded!</h3>
</body>
</html>
This is the pattern you are looking for
/^[\w-_.]*$/
What this means:
^
Start of string[...]
Match characters inside\w
Any word character so 0-9
a-z
A-Z
-_.
Match -
and _
and .
*
Zero or more of pattern or unlimited $
End of stringIf you want to limit the amount of characters:
/^[\w-_.]{0,5}$/
{0,5}
Means 0-5
characters
I needed to specify min-height
#login
display: flex
align-items: center
justify-content: center
min-height: 16em
Use v.clear() to empty the vector.
If your vector contains pointers, clear calls the destructor for the object but does not delete the memory referenced by the pointer.
vector<SomeClass*> v(0);
v.push_back( new SomeClass("one") );
v.clear(); //Memory leak where "one" instance of SomeClass is lost
For Swift 2, you should change it to the following:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.map.setRegion(region, animated: true)
}
I've discovered another reason for this error. It has to do with the CSS-in-JS returning a null value to the top-level JSX of the return function in a React component.
For example:
const Css = styled.div`
<whatever css>
`;
export function exampleFunction(args1) {
...
return null;
}
export default class ExampleComponent extends Component {
...
render() {
const CssInJs = exampleFunction(args1);
...
return (
<CssInJs>
<OtherCssInJs />
...
</CssInJs>
);
}
I would get this warning:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: null.
Followed by this error:
Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: null.
I discovered it was because there was no CSS with the CSS-in-JS component that I was trying to render. I fixed it by making sure there was CSS being returned and not a null value.
For example:
const Css = styled.div`
<whatever css>
`;
export function exampleFunction(args1) {
...
return Css;
}
export default class ExampleComponent extends Component {
...
render() {
const CssInJs = exampleFunction(args1);
...
return (
<CssInJs>
<OtherCssInJs />
...
</CssInJs>
);
}
A caveat which the other answers don't seem to mention is that the time which is shown by dmesg
doesn't take into account any sleep/suspend time. So there are cases where the usual answer of using dmesg -T
doesn't work, and shows a completely wrong time.
A workaround for such situations is to write something to the kernel log at a known time and then use that entry as a reference to calculate the other times. Obviously, it will only work for times after the last suspend.
So to display the correct time for recent entries on machines which may have been suspended since their last boot, use something like this from my other answer here:
# write current time to kernel ring buffer so it appears in dmesg output
echo "timecheck: $(date +%s) = $(date +%F_%T)" | sudo tee /dev/kmsg
# use our "timecheck" entry to get the difference
# between the dmesg timestamp and real time
offset=$(dmesg | grep timecheck | tail -1 \
| perl -nle '($t1,$t2)=/^.(\d+)\S+ timecheck: (\d+)/; print $t2-$t1')
# pipe dmesg output through a Perl snippet to
# convert it's timestamp to correct readable times
dmesg | tail \
| perl -pe 'BEGIN{$offset=shift} s/^\[(\d+)\S+/localtime($1+$offset)/e' $offset
Okay, it took me a while to see this, but there's no way this compiles:
return String.(ConfigurationManager.AppSettings[paramName]);
You're not even calling a method on the String
type. Just do this:
return ConfigurationManager.AppSettings[paramName];
The AppSettings
KeyValuePair already returns a string. If the name doesn't exist, it will return null
.
Based on your edit you have not yet added a Reference to the System.Configuration
assembly for the project you're working in.
min-height: 100%;
position: relative;
here's what I found with my experiments using the built-in
FORMATMESSAGE() function
sp_addmessage @msgnum=50001,@severity=1,@msgText='Hello %s you are #%d',@replace='replace'
SELECT FORMATMESSAGE(50001, 'Table1', 5)
when you call up sp_addmessage, your message template gets stored into the system table master.dbo.sysmessages (verified on SQLServer 2000).
You must manage addition and removal of template strings from the table yourself, which is awkward if all you really want is output a quick message to the results screen.
The solution provided by Kathik DV, looks interesting but doesn't work with SQL Server 2000, so i altered it a bit, and this version should work with all versions of SQL Server:
IF OBJECT_ID( N'[dbo].[FormatString]', 'FN' ) IS NOT NULL
DROP FUNCTION [dbo].[FormatString]
GO
/***************************************************
Object Name : FormatString
Purpose : Returns the formatted string.
Original Author : Karthik D V http://stringformat-in-sql.blogspot.com/
Sample Call:
SELECT dbo.FormatString ( N'Format {0} {1} {2} {0}', N'1,2,3' )
*******************************************/
CREATE FUNCTION [dbo].[FormatString](
@Format NVARCHAR(4000) ,
@Parameters NVARCHAR(4000)
)
RETURNS NVARCHAR(4000)
AS
BEGIN
--DECLARE @Format NVARCHAR(4000), @Parameters NVARCHAR(4000) select @format='{0}{1}', @Parameters='hello,world'
DECLARE @Message NVARCHAR(400), @Delimiter CHAR(1)
DECLARE @ParamTable TABLE ( ID INT IDENTITY(0,1), Parameter VARCHAR(1000) )
Declare @startPos int, @endPos int
SELECT @Message = @Format, @Delimiter = ','
--handle first parameter
set @endPos=CHARINDEX(@Delimiter,@Parameters)
if (@endPos=0 and @Parameters is not null) --there is only one parameter
insert into @ParamTable (Parameter) values(@Parameters)
else begin
insert into @ParamTable (Parameter) select substring(@Parameters,0,@endPos)
end
while @endPos>0
Begin
--insert a row for each parameter in the
set @startPos = @endPos + LEN(@Delimiter)
set @endPos = CHARINDEX(@Delimiter,@Parameters, @startPos)
if (@endPos>0)
insert into @ParamTable (Parameter) select substring(@Parameters,@startPos,@endPos)
else
insert into @ParamTable (Parameter) select substring(@Parameters,@startPos,4000)
End
UPDATE @ParamTable SET @Message = REPLACE ( @Message, '{'+CONVERT(VARCHAR,ID) + '}', Parameter )
RETURN @Message
END
Go
grant execute,references on dbo.formatString to public
Usage:
print dbo.formatString('hello {0}... you are {1}','world,good')
--result: hello world... you are good
To compare, there are more options:
import (
"fmt"
"regexp"
"strings"
)
const (
str = "something"
substr = "some"
)
// 1. Contains
res := strings.Contains(str, substr)
fmt.Println(res) // true
// 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
i := strings.Index(str, substr)
fmt.Println(i) // 0
// 3. Split by substr and check len of the slice, or length is 1 if substr is not present
ss := strings.Split(str, substr)
fmt.Println(len(ss)) // 2
// 4. Check number of non-overlapping instances of substr in str
c := strings.Count(str, substr)
fmt.Println(c) // 1
// 5. RegExp
matched, _ := regexp.MatchString(substr, str)
fmt.Println(matched) // true
// 6. Compiled RegExp
re = regexp.MustCompile(substr)
res = re.MatchString(str)
fmt.Println(res) // true
Benchmarks:
Contains
internally calls Index
, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on Go 1.14.3).
BenchmarkStringsContains-4 100000000 10.5 ns/op 0 B/op 0 allocs/op
BenchmarkStringsIndex-4 117090943 10.1 ns/op 0 B/op 0 allocs/op
BenchmarkStringsSplit-4 6958126 152 ns/op 32 B/op 1 allocs/op
BenchmarkStringsCount-4 42397729 29.1 ns/op 0 B/op 0 allocs/op
BenchmarkStringsRegExp-4 461696 2467 ns/op 1326 B/op 16 allocs/op
BenchmarkStringsRegExpCompiled-4 7109509 168 ns/op 0 B/op 0 allocs/op
Windows 10:
open cmd
change directory where you want to create text file(movie_list.txt) for the folder (d:\videos\movies)
type following command
d:\videos\movies> dir /b /a-d > movie_list.txt
Start the control panel using "Run as administrator". Then you can install Apache and MySQL as a service:
def touch(fname):
if os.path.exists(fname):
os.utime(fname, None)
else:
open(fname, 'a').close()
The error message tells the exact reason: "abstract methods cannot have a body".
They can only be defined in abstract classes and interfaces (interface methods are implicitly abstract!) and the idea is, that the subclass implements the method.
Example:
public abstract class AbstractGreeter {
public abstract String getHelloMessage();
public void sayHello() {
System.out.println(getHelloMessage());
}
}
public class FrenchGreeter extends AbstractGreeter{
// we must implement the abstract method
@Override
public String getHelloMessage() {
return "bonjour";
}
}
It's somewhat weird to read but yes, the exception will bubble up to the calling code - but only if you await
or Wait()
the call to Foo
.
public async Task Foo()
{
var x = await DoSomethingAsync();
}
public async void DoFoo()
{
try
{
await Foo();
}
catch (ProtocolException ex)
{
// The exception will be caught because you've awaited
// the call in an async method.
}
}
//or//
public void DoFoo()
{
try
{
Foo().Wait();
}
catch (ProtocolException ex)
{
/* The exception will be caught because you've
waited for the completion of the call. */
}
}
Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. - https://msdn.microsoft.com/en-us/magazine/jj991977.aspx
Note that using Wait() may cause your application to block, if .Net decides to execute your method synchronously.
This explanation http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions is pretty good - it discusses the steps the compiler takes to achieve this magic.
When I want to see a snapshot of a table(s), and/or view (in a read-only way)
An Example with python3
and the requests
library as mentioned by @leoluk:
pip install requests
Script req.py:
import requests
url='http://localhost'
# in case you need a session
cd = { 'sessionid': '123..'}
r = requests.get(url, cookies=cd)
# or without a session: r = requests.get(url)
r.content
Now,execute it and you will get the html source of localhost!
python3 req.py
My async function
const getAllRedis = async (key) => {
let obj = [];
await client.hgetall(key, (err, object) => {
console.log(object);
_.map(object, (ob)=>{
obj.push(JSON.parse(ob));
})
return obj;
// res.send(obj);
});
}
// Define the string
var string = 'Hello World!';
// Encode the String
var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"
Here is how you encode normal text to base64 in Node.js:
//Buffer() requires a number, array or string as the first parameter, and an optional encoding type as the second parameter.
// Default is utf8, possible encoding types are ascii, utf8, ucs2, base64, binary, and hex
var b = new Buffer('JavaScript');
// If we don't use toString(), JavaScript assumes we want to convert the object to utf8.
// We can make it convert to other formats by passing the encoding type to toString().
var s = b.toString('base64');
And here is how you decode base64 encoded strings:
var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();
To encode an array of bytes using dojox.encoding.base64:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a base64-encoded string:
var bytes = dojox.encoding.base64.decode(str)
<script src="bower_components/angular-base64/angular-base64.js"></script>
angular
.module('myApp', ['base64'])
.controller('myController', [
'$base64', '$scope',
function($base64, $scope) {
$scope.encoded = $base64.encode('a string');
$scope.decoded = $base64.decode('YSBzdHJpbmc=');
}]);
If you would like to learn more about how base64 is encoded in general, and in JavaScript in-particular, I would recommend this article: Computer science in JavaScript: Base64 encoding
#include<stdio.h>
int main(void)
{
printf("Minimum Signed Char %d\n",-(char)((unsigned char) ~0 >> 1) - 1);
printf("Maximum Signed Char %d\n",(char) ((unsigned char) ~0 >> 1));
printf("Minimum Signed Short %d\n",-(short)((unsigned short)~0 >>1) -1);
printf("Maximum Signed Short %d\n",(short)((unsigned short)~0 >> 1));
printf("Minimum Signed Int %d\n",-(int)((unsigned int)~0 >> 1) -1);
printf("Maximum Signed Int %d\n",(int)((unsigned int)~0 >> 1));
printf("Minimum Signed Long %ld\n",-(long)((unsigned long)~0 >>1) -1);
printf("Maximum signed Long %ld\n",(long)((unsigned long)~0 >> 1));
/* Unsigned Maximum Values */
printf("Maximum Unsigned Char %d\n",(unsigned char)~0);
printf("Maximum Unsigned Short %d\n",(unsigned short)~0);
printf("Maximum Unsigned Int %u\n",(unsigned int)~0);
printf("Maximum Unsigned Long %lu\n",(unsigned long)~0);
return 0;
}
the problem is that the dom element 'speclist' is not created at the time the javascript code is getting executed. So I put the javascript code inside a function and called that function on body onload event.
function do_this_first(){
//appending code
}
<body onload="do_this_first()">
</body>
Kotlin
this.findViewById<View>(android.R.id.content)
.rootView
.setBackgroundColor(ContextCompat.getColor(this, R.color.black))
I had a similar issue where I was not able to either install a CRX file into Chrome.
It turns out that since I had my Downloads folder set to a network mapped drive, it would not allow Chrome to install any extensions and would either do nothing (drag and drop on Chrome) or ask me to download the extension (if I clicked a link from the Web Store).
Setting the Downloads folder to a local disk directory instead of a network directory allowed extensions to be installed.
Running: 20.0.1132.57 m
Your find should look like that to avoid sending directory names to sed:
find ./ -type f -exec sed -i -e 's/apple/orange/g' {} \;
create table encrypt(username varchar(20),password varbinary(200))
insert into encrypt values('raju',aes_encrypt('kumar','key')) select *,cast(aes_decrypt(password,'key') as char(40)) from encrypt where username='raju';
extension Date {
func isBetween(_ date1: Date, and date2: Date) -> Bool {
return (min(date1, date2) ... max(date1, date2)).contains(self)
}
}
let resultArray = dateArray.filter { $0.dateObj!.isBetween(startDate, and: endDate) }
For me, these steps worked in Ubuntu with PHP 7.3:
1. vi /etc/php/7.3/apache2/php.ini > uncomment:
;extension=pdo_sqlite
;extension=pdo_mysql
2. sudo apt-get install php7.3-sqlite3
3. sudo service apache2 restart
I got the same error. Saved the file in UTF-8 and it worked.
I use a Dictionary and because of the repetetiveness and possible missing keys, I quickly patched together a small method:
private static string GetKey(IReadOnlyDictionary<string, string> dictValues, string keyValue)
{
return dictValues.ContainsKey(keyValue) ? dictValues[keyValue] : "";
}
Calling it:
var entry = GetKey(dictList,"KeyValue1");
Gets the job done.
ui router make your life easier! You can add it to you AngularJS application via injecting it into your applications...
ng-route
comes as part of the core AngularJS, so it's simpler and gives you fewer options...
Look at here to understand ng-route better: https://docs.angularjs.org/api/ngRoute
Also when using it, don't forget to use: ngView ..
ng-ui-router is different but:
https://github.com/angular-ui/ui-router but gives you more options....
SQL Wildcards are enough for this purpose. Follow this link: http://www.w3schools.com/SQL/sql_wildcards.asp
you need to use a query like this:
select * from mytable where msisdn like '%7%'
or
select * from mytable where msisdn like '56655%'
UPDATED
Some time on, I see a comment that brings me back to my old answer, and I think I'd do it differently now. These days I'd write:
private static IEnumerable<T> GetEnumValues<T>()
{
// Can't use type constraints on value types, so have to do check like this
if (typeof(T).BaseType != typeof(Enum))
{
throw new ArgumentException("T must be of type System.Enum");
}
return Enum.GetValues(typeof(T)).Cast<T>();
}
I have done it accessing the controls inside the cell control. Find in all control collections.
ControlCollection cc = (ControlCollection)e.Row.Controls[1].Controls;
Label lbCod = (Label)cc[1];
You need to write a document.write object:
document.write('<script type="text/javascript" src="file.js" ></script>');
and place it in your main javascript file
This is a self-compiled bat/.net hybrid (should be saved as .BAT
) that can be used on any system that have installed .net framework (it's a rare thing to see an windows without .NET framework even for the oldest XP/2003 installations) . It uses jscript.net compiler to create an exe capable to print strings with different background/foreground color only for the current line.
@if (@X)==(@Y) @end /* JScript comment
@echo off
setlocal
for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do (
set "jsc=%%v"
)
if not exist "%~n0.exe" (
"%jsc%" /nologo /out:"%~n0.exe" "%~dpsfnx0"
)
%~n0.exe %*
endlocal & exit /b %errorlevel%
*/
import System;
var arguments:String[] = Environment.GetCommandLineArgs();
var newLine = false;
var output = "";
var foregroundColor = Console.ForegroundColor;
var backgroundColor = Console.BackgroundColor;
var evaluate = false;
var currentBackground=Console.BackgroundColor;
var currentForeground=Console.ForegroundColor;
//http://stackoverflow.com/a/24294348/388389
var jsEscapes = {
'n': '\n',
'r': '\r',
't': '\t',
'f': '\f',
'v': '\v',
'b': '\b'
};
function decodeJsEscape(_, hex0, hex1, octal, other) {
var hex = hex0 || hex1;
if (hex) { return String.fromCharCode(parseInt(hex, 16)); }
if (octal) { return String.fromCharCode(parseInt(octal, 8)); }
return jsEscapes[other] || other;
}
function decodeJsString(s) {
return s.replace(
// Matches an escape sequence with UTF-16 in group 1, single byte hex in group 2,
// octal in group 3, and arbitrary other single-character escapes in group 4.
/\\(?:u([0-9A-Fa-f]{4})|x([0-9A-Fa-f]{2})|([0-3][0-7]{0,2}|[4-7][0-7]?)|(.))/g,
decodeJsEscape);
}
function printHelp( ) {
print( arguments[0] + " -s string [-f foreground] [-b background] [-n] [-e]" );
print( " " );
print( " string String to be printed" );
print( " foreground Foreground color - a " );
print( " number between 0 and 15." );
print( " background Background color - a " );
print( " number between 0 and 15." );
print( " -n Indicates if a new line should" );
print( " be written at the end of the ");
print( " string(by default - no)." );
print( " -e Evaluates special character " );
print( " sequences like \\n\\b\\r and etc ");
print( "" );
print( "Colors :" );
for ( var c = 0 ; c < 16 ; c++ ) {
Console.BackgroundColor = c;
Console.Write( " " );
Console.BackgroundColor=currentBackground;
Console.Write( "-"+c );
Console.WriteLine( "" );
}
Console.BackgroundColor=currentBackground;
}
function errorChecker( e:Error ) {
if ( e.message == "Input string was not in a correct format." ) {
print( "the color parameters should be numbers between 0 and 15" );
Environment.Exit( 1 );
} else if (e.message == "Index was outside the bounds of the array.") {
print( "invalid arguments" );
Environment.Exit( 2 );
} else {
print ( "Error Message: " + e.message );
print ( "Error Code: " + ( e.number & 0xFFFF ) );
print ( "Error Name: " + e.name );
Environment.Exit( 666 );
}
}
function numberChecker( i:Int32 ){
if( i > 15 || i < 0 ) {
print("the color parameters should be numbers between 0 and 15");
Environment.Exit(1);
}
}
if ( arguments.length == 1 || arguments[1].toLowerCase() == "-help" || arguments[1].toLowerCase() == "-help" ) {
printHelp();
Environment.Exit(0);
}
for (var arg = 1; arg <= arguments.length-1; arg++ ) {
if ( arguments[arg].toLowerCase() == "-n" ) {
newLine=true;
}
if ( arguments[arg].toLowerCase() == "-e" ) {
evaluate=true;
}
if ( arguments[arg].toLowerCase() == "-s" ) {
output=arguments[arg+1];
}
if ( arguments[arg].toLowerCase() == "-b" ) {
try {
backgroundColor=Int32.Parse( arguments[arg+1] );
} catch(e) {
errorChecker(e);
}
}
if ( arguments[arg].toLowerCase() == "-f" ) {
try {
foregroundColor=Int32.Parse(arguments[arg+1]);
} catch(e) {
errorChecker(e);
}
}
}
Console.BackgroundColor = backgroundColor ;
Console.ForegroundColor = foregroundColor ;
if ( evaluate ) {
output=decodeJsString(output);
}
if ( newLine ) {
Console.WriteLine(output);
} else {
Console.Write(output);
}
Console.BackgroundColor = currentBackground;
Console.ForegroundColor = currentForeground;
Here's the help message:
Example:
coloroutput.bat -s "aa\nbb\n\u0025cc" -b 10 -f 3 -n -e
You can also find this script here.
You can also check carlos' color function -> http://www.dostips.com/forum/viewtopic.php?f=3&t=4453
Execute the GetEventIdsByEventDate() method and save the results in a variable, and then you can use the .Contains() method
I tried with the following and it's worked:
release {
debuggable true
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
Tell the correlation to ignore the NAs with use
argument, e.g.:
cor(data$price, data$exprice, use = "complete.obs")
The mail
command does that (who would have guessed ;-). Open your shell and enter man mail
to get the manual page for the mail
command for all the options available.
As you learned the in-place shuffling was the problem. I also have problem frequently, and often seem to forget how to copy a list, too. Using sample(a, len(a))
is the solution, using len(a)
as the sample size. See https://docs.python.org/3.6/library/random.html#random.sample for the Python documentation.
Here's a simple version using random.sample()
that returns the shuffled result as a new list.
import random
a = range(5)
b = random.sample(a, len(a))
print a, b, "two list same:", a == b
# print: [0, 1, 2, 3, 4] [2, 1, 3, 4, 0] two list same: False
# The function sample allows no duplicates.
# Result can be smaller but not larger than the input.
a = range(555)
b = random.sample(a, len(a))
print "no duplicates:", a == list(set(b))
try:
random.sample(a, len(a) + 1)
except ValueError as e:
print "Nope!", e
# print: no duplicates: True
# print: Nope! sample larger than population
Here is what I would recommend.
It should conform to C89, and be completely portable. In particular, it works also on pipes and sockets on POSIXy systems.
The idea is that we read the input in large-ish chunks (READALL_CHUNK
), dynamically reallocating the buffer as we need it. We only use realloc()
, fread()
, ferror()
, and free()
:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
/* Size of each input chunk to be
read and allocate for. */
#ifndef READALL_CHUNK
#define READALL_CHUNK 262144
#endif
#define READALL_OK 0 /* Success */
#define READALL_INVALID -1 /* Invalid parameters */
#define READALL_ERROR -2 /* Stream error */
#define READALL_TOOMUCH -3 /* Too much input */
#define READALL_NOMEM -4 /* Out of memory */
/* This function returns one of the READALL_ constants above.
If the return value is zero == READALL_OK, then:
(*dataptr) points to a dynamically allocated buffer, with
(*sizeptr) chars read from the file.
The buffer is allocated for one extra char, which is NUL,
and automatically appended after the data.
Initial values of (*dataptr) and (*sizeptr) are ignored.
*/
int readall(FILE *in, char **dataptr, size_t *sizeptr)
{
char *data = NULL, *temp;
size_t size = 0;
size_t used = 0;
size_t n;
/* None of the parameters can be NULL. */
if (in == NULL || dataptr == NULL || sizeptr == NULL)
return READALL_INVALID;
/* A read error already occurred? */
if (ferror(in))
return READALL_ERROR;
while (1) {
if (used + READALL_CHUNK + 1 > size) {
size = used + READALL_CHUNK + 1;
/* Overflow check. Some ANSI C compilers
may optimize this away, though. */
if (size <= used) {
free(data);
return READALL_TOOMUCH;
}
temp = realloc(data, size);
if (temp == NULL) {
free(data);
return READALL_NOMEM;
}
data = temp;
}
n = fread(data + used, 1, READALL_CHUNK, in);
if (n == 0)
break;
used += n;
}
if (ferror(in)) {
free(data);
return READALL_ERROR;
}
temp = realloc(data, used + 1);
if (temp == NULL) {
free(data);
return READALL_NOMEM;
}
data = temp;
data[used] = '\0';
*dataptr = data;
*sizeptr = used;
return READALL_OK;
}
Above, I've used a constant chunk size, READALL_CHUNK
== 262144 (256*1024
). This means that in the worst case, up to 262145 chars are wasted (allocated but not used), but only temporarily. At the end, the function reallocates the buffer to the optimal size. Also, this means that we do four reallocations per megabyte of data read.
The 262144-byte default in the code above is a conservative value; it works well for even old minilaptops and Raspberry Pis and most embedded devices with at least a few megabytes of RAM available for the process. Yet, it is not so small that it slows down the operation (due to many read calls, and many buffer reallocations) on most systems.
For desktop machines at this time (2017), I recommend a much larger READALL_CHUNK
, perhaps #define READALL_CHUNK 2097152
(2 MiB).
Because the definition of READALL_CHUNK
is guarded (i.e., it is defined only if it is at that point in the code still undefined), you can override the default value at compile time, by using (in most C compilers) -DREADALL_CHUNK=2097152
command-line option -- but do check your compiler options for defining a preprocessor macro using command-line options.
Once I have followed all these steps, I start to receive error messages in all android classes calls like:
I revolved that including android.jar in the SDKs Platform Settings:
The sed
on macOS Mojave was released in 2005, so one solution is to install the gnu-sed
,
brew install gnu-sed
then use gsed
will do as you wish,
gsed 's/,/\n/g' file
If you prefer sed
, just sudo sh -c 'echo /usr/local/opt/gnu-sed/libexec/gnubin > /etc/paths.d/brew'
, which is suggested by brew info gnu-sed
. Restart your term, then your sed
in command line is gsed
.
I chased down this problem to a certificate provider that is not part of the default JVM trusted hosts as of JDK 8u74
. The provider is www.identrust.com, but that was not the domain I was trying to connect to. That domain had gotten its certificate from this provider. See Will the cross root cover trust by the default list in the JDK/JRE? -- read down a couple entries. Also see Which browsers and operating systems support Let’s Encrypt.
So, in order to connect to the domain I was interested in, which had a certificate issued from identrust.com
I did the following steps. Basically, I had to get the identrust.com (DST Root CA X3
) certificate to be trusted by the JVM. I was able to do that using Apache HttpComponents 4.5 like so:
1: Obtain the certificate from indettrust at Certificate Chain Download Instructions. Click on the DST Root CA X3 link.
2: Save the string to a file named "DST Root CA X3.pem". Be sure to add the lines "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" in the file at the beginning and the end.
3: Create a java keystore file, cacerts.jks with the following command:
keytool -import -v -trustcacerts -alias IdenTrust -keypass yourpassword -file dst_root_ca_x3.pem -keystore cacerts.jks -storepass yourpassword
4: Copy the resulting cacerts.jks keystore into the resources directory of your java/(maven) application.
5: Use the following code to load this file and attach it to the Apache 4.5 HttpClient. This will solve the problem for all domains that have certificates issued from indetrust.com
util oracle includes the certificate into the JRE default keystore.
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(new File(CalRestClient.class.getResource("/cacerts.jks").getFile()), "yourpasword".toCharArray(),
new TrustSelfSignedStrategy())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
When the project builds then the cacerts.jks will be copied into the classpath and loaded from there. I didn't, at this point in time, test against other ssl sites, but if the above code "chains" in this certificate then they will work too, but again, I don't know.
Reference: Custom SSL context and How do I accept a self-signed certificate with a Java HttpsURLConnection?
The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).
You can use the GUI to do the installation, or you can script the installation of msbuild:
vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet
Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:
You can find documentation about the other available CLI switches here.
The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet
there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin
.
If you don't see them there, try running without --quiet
to see any error messages that may occur during installation.
Magento Store Id : Mage::app()->getStore()->getStoreId();
Magento Store Name : Mage::app()->getStore()->getName();
You could alternatively do:
driver.findElements( By.id("...") ).size() != 0
Which saves the nasty try/catch
p.s.
Or more precisely by @JanHrcek here
!driver.findElements(By.id("...")).isEmpty()
you can download USBview and get all the information you need. Along with the list of devices it will also show you the configuration of each device.
Here are some other approaches you can take.
1. CTE with union:
;WITH cte AS (SELECT a, b, c FROM table1)
SELECT a AS val FROM cte
UNION SELECT b AS val FROM cte
UNION SELECT c AS val FROM cte;
2. CTE with unpivot:
;WITH cte AS (SELECT a, b, c FROM table1)
SELECT DISTINCT val
FROM cte
UNPIVOT (val FOR col IN (a, b, c)) u;
\l
for databases
\c
DatabaseName to switch to db
\df
for procedures stored in particular database
You don't need to create the table first and then add the keys in subsequent steps. You can add both primary key and foreign key while creating the table:
This example assumes the existence of a table (Codes
) that we would want to reference with our foreign key.
CREATE TABLE d (
id [numeric](1),
code [varchar](2),
PRIMARY KEY (id, code),
CONSTRAINT fk_d_codes FOREIGN KEY (code) REFERENCES Codes (code)
)
If you don't have a table that we can reference, add one like this so that the example will work:
CREATE TABLE Codes (
Code [varchar](2) PRIMARY KEY
)
NOTE: you must have a table to reference before creating the foreign key.
This worked for me in IE 11:
<meta http-equiv="x-ua-compatible" content="IE=edge; charset=UTF-8">
collections.defaultdict
can be sub-classed to make a nested dict. Then add any useful iteration methods to that class.
>>> from collections import defaultdict
>>> class nesteddict(defaultdict):
def __init__(self):
defaultdict.__init__(self, nesteddict)
def walk(self):
for key, value in self.iteritems():
if isinstance(value, nesteddict):
for tup in value.walk():
yield (key,) + tup
else:
yield key, value
>>> nd = nesteddict()
>>> nd['new jersey']['mercer county']['plumbers'] = 3
>>> nd['new jersey']['mercer county']['programmers'] = 81
>>> nd['new jersey']['middlesex county']['programmers'] = 81
>>> nd['new jersey']['middlesex county']['salesmen'] = 62
>>> nd['new york']['queens county']['plumbers'] = 9
>>> nd['new york']['queens county']['salesmen'] = 36
>>> for tup in nd.walk():
print tup
('new jersey', 'mercer county', 'programmers', 81)
('new jersey', 'mercer county', 'plumbers', 3)
('new jersey', 'middlesex county', 'programmers', 81)
('new jersey', 'middlesex county', 'salesmen', 62)
('new york', 'queens county', 'salesmen', 36)
('new york', 'queens county', 'plumbers', 9)
If you are using the animation listener, set v.setAnimationListener(null)
. Use the following code with all options.
v.getAnimation().cancel();
v.clearAnimation();
animation.setAnimationListener(null);
You can also use ISNULL and a select statement to get this result
SELECT
Table1.ID,
ISNULL((SELECT 'TRUE' FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID),'FALSE') AS columName,
etc
FROM TABLE1
If the types of the parameters are all the same (varchar2
for example), you can have a package like this which will do the following:
CREATE OR REPLACE PACKAGE testuser.test_pkg IS
TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);
END test_pkg;
CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
BEGIN
FOR i IN p_parm.first .. p_parm.last
LOOP
dbms_output.put_line(p_parm(i));
END LOOP;
END;
END test_pkg;
Then, to call it you'd need to set up the array and pass it:
DECLARE
l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
l_array(0) := 'hello';
l_array(1) := 'there';
testuser.test_pkg.your_proc(l_array);
END;
/
In .NET 4.6 the preferred way is to use a new method, Array.Empty
:
String[] a = Array.Empty<string>();
The implementation is succinct, using how static members in generic classes behave in .Net:
public static T[] Empty<T>()
{
return EmptyArray<T>.Value;
}
// Useful in number of places that return an empty byte array to avoid
// unnecessary memory allocation.
internal static class EmptyArray<T>
{
public static readonly T[] Value = new T[0];
}
(code contract related code removed for clarity)
See also:
Array.Empty
source code on Reference SourceArray.Empty<T>()
You can create a new alias in Terminal:
nano ~/.bash_profile
Copy this line and paste it into the editor:
alias subl='open -a "Sublime Text"'
Hit control + x, then y, then enter to save and close it.
Close all Terminal windows and open it up again.
That's it, you can now use subl filename
or subl .
I collected some ideas from other SO question (largely from here and this css page)
The idea is to use relative and absolute positioning to move your line to the bottom:
@media (min-width: 768px ) {
.row {
position: relative;
}
#bottom-align-text {
position: absolute;
bottom: 0;
right: 0;
}}
The display:flex
option is at the moment a solution to make the div get the same size as its parent. This breaks on the other hand the bootstrap possibilities to auto-linebreak on small devices by adding col-sx-12
class. (This is why the media query is needed)
git pull --rebase origin master
git push origin master
git push -f origin master
Warning git push -f origin master
PFX files are PKCS#12 Personal Information Exchange Syntax Standard bundles. They can include arbitrary number of private keys with accompanying X.509 certificates and a certificate authority chain (set certificates).
If you want to extract client certificates, you can use OpenSSL's PKCS12 tool.
openssl pkcs12 -in input.pfx -out mycerts.crt -nokeys -clcerts
The command above will output certificate(s) in PEM format. The ".crt" file extension is handled by both macOS and Window.
You mention ".cer" extension in the question which is conventionally used for the DER encoded files. A binary encoding. Try the ".crt" file first and if it's not accepted, easy to convert from PEM to DER:
openssl x509 -inform pem -in mycerts.crt -outform der -out mycerts.cer
Check the setting in your user config /home/username/.netbeans/version/etc/netbeans.conf
I had the problem where I was specifying the location globally, but my user setting was overriding the global setting.
CentOS 7/Netbeans 8.1
Go to keycloak admin console > SpringBootKeycloak> Cients>login-app page. Here in valid-redirect uris section add http://localhost:8080/sso/login
This will help resolve indirect-uri problem
JavaFX is part of OpenJDK
The JavaFX project itself is open source and is part of the OpenJDK project.
Update Dec 2019
For current information on how to use Open Source JavaFX, visit https://openjfx.io. This includes instructions on using JavaFX as a modular library accessed from an existing JDK (such as an Open JDK installation).
The open source code repository for JavaFX is at https://github.com/openjdk/jfx.
At the source location linked, you can find license files for open JavaFX (currently this license matches the license for OpenJDK: GPL+classpath exception).
The wiki for the project is located at: https://wiki.openjdk.java.net/display/OpenJFX/Main
If you want a quick start to using open JavaFX, the Belsoft Liberica JDK distributions provide pre-built binaries of OpenJDK that (currently) include open JavaFX for a variety of platforms.
For distribution as self-contained applications, Java 14, is scheduled to implement JEP 343: Packaging Tool, which "Supports native packaging formats to give end users a natural installation experience. These formats include msi and exe on Windows, pkg and dmg on macOS, and deb and rpm on Linux.", for deployment of OpenJFX based applications with native installers and no additional platform dependencies (such as a pre-installed JDK).
Older information which may become outdated over time
Building JavaFX from the OpenJDK repository
You can build an open version of OpenJDK (including JavaFX) completely from source which has no dependencies on the Oracle JDK or closed source code.
Update: Using a JavaFX distribution pre-built from OpenJDK sources
As noted in comments to this question and in another answer, the Debian Linux distributions offer a JavaFX binary distibution based upon OpenJDK:
Install via:
sudo apt-get install openjfx
(currently this only works for Java 8 as far as I know).
Differences between Open JDK and Oracle JDK with respect to JavaFX
The following information was provided for Java 8. As of Java 9, VP6 encoding is deprecated for JavaFX and the Oracle WebStart/Browser embedded application deployment technology is also deprecated. So future versions of JavaFX, even if they are distributed by Oracle, will likely not include any technology which is not open source.
Oracle JDK includes some software which is not usable from the OpenJDK. There are two main components which relate to JavaFX.
This means that an open version of JavaFX cannot play VP6 FLV files. This is not a big loss as it is difficult to find VP6 encoders or media encoded in VP6.
Other more common video formats, such as H.264 will playback fine with an open version of JavaFX (as long as you have the appropriate codecs pre-installed on the target machine).
The lack of WebStart/Browser Embedded deployment technology is really something to do with OpenJDK itself rather than JavaFX specifically. This technology can be used to deploy non-JavaFX applications.
It would be great if the OpenSource community developed a deployment technology for Java (and other software) which completely replaced WebStart and Browser Embedded deployment methods, allowing a nice light-weight, low impact user experience for application distribution. I believe there have been some projects started to serve such a goal, but they have not yet reached a high maturity and adoption level.
Personally, I feel that WebStart/Browser Embedded deployments are legacy technology and there are currently better ways to deploy many JavaFX applications (such as self-contained applications).
Update Dec, 2019:
An open source version of WebStart for JDK 11+ has been developed and is available at https://openwebstart.com.
Who needs to create Linux OpenJDK Distributions which include JavaFX
It is up to the people which create packages for Linux distributions based upon OpenJDK (e.g. Redhat, Ubuntu etc) to create RPMs for the JDK and JRE that include JavaFX. Those software distributors, then need to place the generated packages in their standard distribution code repositories (e.g. fedora/red hat network yum repositories). Currently this is not being done, but I would be quite surprised if Java 8 Linux packages did not include JavaFX when Java 8 is released in March 2014.
Update, Dec 2019:
Now that JavaFX has been separated from most binary JDK and JRE distributions (including Oracle's distribution) and is, instead, available as either a stand-alone SDK, set of jmods or as a library dependencies available from the central Maven repository (as outlined as https://openjfx.io), there is less of a need for standard Linux OpenJDK distributions to include JavaFX.
If you want a pre-built JDK which includes JavaFX, consider the Liberica JDK distributions, which are provided for a variety of platforms.
Advice on Deployment for Substantial Applications
I advise using Java's self-contained application deployment mode.
A description of this deployment mode is:
Application is installed on the local drive and runs as a standalone program using a private copy of Java and JavaFX runtimes. The application can be launched in the same way as other native applications for that operating system, for example using a desktop shortcut or menu entry.
You can build a self-contained application either from the Oracle JDK distribution or from an OpenJDK build which includes JavaFX. It currently easier to do so with an Oracle JDK.
As a version of Java is bundled with your application, you don't have to care about what version of Java may have been pre-installed on the machine, what capabilities it has and whether or not it is compatible with your program. Instead, you can test your application against an exact Java runtime version, and distribute that with your application. The user experience for deploying your application will be the same as installing a native application on their machine (e.g. a windows .exe or .msi installed, an OS X .dmg, a linux .rpm or .deb).
Note: The self-contained application feature was only available for Java 8 and 9, and not for Java 10-13. Java 14, via JEP 343: Packaging Tool, is scheduled to again provide support for this feature from OpenJDK distributions.
Update, April 2018: Information on Oracle's current policy towards future developments
SQL trigger for automatic date generation in oracle table:
CREATE OR REPLACE TRIGGER name_of_trigger
BEFORE INSERT
ON table_name
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
SELECT sysdate INTO :NEW.column_name FROM dual;
END;
/
Here are some classes I use for long-polling in C#. There are basically 6 classes (see below).
For those looking for an example of how to pass the OAuth2 authorization (access token) in the header (as opposed to using a request or body parameter), here is how it's done:
Authorization: Bearer 0b79bab50daca910b000d4f1a2b675d604257e42
simple way to do maxlength for textarea in html4 is:
<textarea cols="60" rows="5" onkeypress="if (this.value.length > 100) { return false; }"></textarea>
Change the "100" to however many characters you want
In my case, the problem was solved by adding this line to the module build.gradle:
// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'
If you want to find matches in the entire file (not just the tail), and you want it to sit and wait for any new matches, this works nicely:
tail -c +0 -f <file> | grep --line-buffered <pattern>
The -c +0
flag says that the output should start 0
bytes (-c
) from the beginning (+
) of the file.
Cannot delete or update a parent row: a foreign key constraint fails (table1
.user_role
, CONSTRAINT FK143BF46A8dsfsfds@#5A6BD60
FOREIGN KEY (user_id
) REFERENCES user
(id
))
What i did in two simple steps . first i delete the child row in child table like
mysql> delete from table2 where role_id = 2 && user_id =20;
Query OK, 1 row affected (0.10 sec)
and second step as deleting the parent
delete from table1 where id = 20;
Query OK, 1 row affected (0.12 sec)
By this i solve the Problem which means Delete Child then Delete parent
i Hope You got it. :)
getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.
#include <iostream>
using namespace std;
int main() {
string a, b, c;
cin >> a >> b >> c;
//now you have your three words
return 0;
}
I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.
Easy peasy. Your data frame will look like this:
df <- data.frame(sex=c('M','F','M'),
occupation=c('Student','Analyst','Analyst'))
You can then do the equivalent of a COUNTIF
by first specifying the IF
part, like so:
df$sex == 'M'
This will give you a boolean vector, i.e. a vector of TRUE
and FALSE
. What you want is to count the observations for which the condition is TRUE
. Since in R TRUE
and FALSE
double as 1 and 0 you can simply sum()
over the boolean vector. The equivalent of COUNTIF(sex='M')
is therefore
sum(df$sex == 'M')
Should there be rows in which the sex
is not specified the above will give back NA
. In that case, if you just want to ignore the missing observations use
sum(df$sex == 'M', na.rm=TRUE)
The icon on Apple's site is 152x152 pixels.
http://www.apple.com/apple-touch-icon.png
Hope that answers your question.
DO NOT have a wrapper that creates a new instance of HttpClient. If you do that, you will run out of sockets at runtime (even though you are disposing the HttpClient object).
If using MOQ, the correct way to do this is to add using Moq.Protected;
to your test and then write code like the following:
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("It worked!")
};
var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
mockHttpMessageHandler
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(() => response);
var httpClient = new HttpClient(mockHttpMessageHandler.Object);
With Moment.js simply use:
var jsDate = moment(netDateTime).toDate();
Where netDateTime
is your DateTime variable serialized, something like "/Date(1456956000000+0200)/"
.
I answered a similar question a couple weeks ago.
There is example code in that question, but basically you can do something like this: (Note the capitalization of User-Agent
as of RFC 2616, section 14.43.)
opener = urllib2.build_opener()
opener.addheaders = [('User-Agent', 'Mozilla/5.0')]
response = opener.open('http://www.stackoverflow.com')
To all the Functional Programming lovers, here is a somewhat functional approach :)
const getHexColor = (rgbValue) =>
rgbValue.replace("rgb(", "").replace(")", "").split(",")
.map(colorValue => (colorValue > 15 ? "0" : "") + colorValue.toString(16))
.reduce((acc, hexValue) => acc + hexValue, "#")
then use it like:
const testRGB = "rgb(13,23,12)"
getHexColor(testRGB)
Look at following demo code.
Here is your XML file for UI,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btnCapture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Camera" />
</LinearLayout>
And here is your Java class file,
public class CameraDemoActivity extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Here, we are making a folder named picFolder to store
// pics taken by the camera using this application.
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
Button capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Here, the counter will be incremented each time, and the
// picture taken by camera will be stored as 1.jpg,2.jpg
// and likewise.
count++;
String file = dir+count+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
}
catch (IOException e)
{
}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.d("CameraDemo", "Pic saved");
}
}
}
Note:
Specify the following permissions in your manifest file,
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I amended the code from stej (which was great, just what i needed!) to use larger buffer, [long] for larger files and used System.Diagnostics.Stopwatch class to track elapsed time and estimate time remaining.
Also added reporting of transfer rate during transfer and outputting overall elapsed time and overall transfer rate.
Using 4MB (4096*1024 bytes) buffer to get better than Win7 native throughput copying from NAS to USB stick on laptop over wifi.
On To-Do list:
Feel free to use/improve :-)
function Copy-File {
param( [string]$from, [string]$to)
$ffile = [io.file]::OpenRead($from)
$tofile = [io.file]::OpenWrite($to)
Write-Progress `
-Activity "Copying file" `
-status ($from.Split("\")|select -last 1) `
-PercentComplete 0
try {
$sw = [System.Diagnostics.Stopwatch]::StartNew();
[byte[]]$buff = new-object byte[] (4096*1024)
[long]$total = [long]$count = 0
do {
$count = $ffile.Read($buff, 0, $buff.Length)
$tofile.Write($buff, 0, $count)
$total += $count
[int]$pctcomp = ([int]($total/$ffile.Length* 100));
[int]$secselapsed = [int]($sw.elapsedmilliseconds.ToString())/1000;
if ( $secselapsed -ne 0 ) {
[single]$xferrate = (($total/$secselapsed)/1mb);
} else {
[single]$xferrate = 0.0
}
if ($total % 1mb -eq 0) {
if($pctcomp -gt 0)`
{[int]$secsleft = ((($secselapsed/$pctcomp)* 100)-$secselapsed);
} else {
[int]$secsleft = 0};
Write-Progress `
-Activity ($pctcomp.ToString() + "% Copying file @ " + "{0:n2}" -f $xferrate + " MB/s")`
-status ($from.Split("\")|select -last 1) `
-PercentComplete $pctcomp `
-SecondsRemaining $secsleft;
}
} while ($count -gt 0)
$sw.Stop();
$sw.Reset();
}
finally {
write-host (($from.Split("\")|select -last 1) + `
" copied in " + $secselapsed + " seconds at " + `
"{0:n2}" -f [int](($ffile.length/$secselapsed)/1mb) + " MB/s.");
$ffile.Close();
$tofile.Close();
}
}
What you could do is create a new class, similar to @Gregoire's example, however, you would want to override the ToString()
method so it appears correctly in the combo box e.g.
public class Language
{
private string _name;
private string _code;
public Language(string name, string code)
{
_name = name;
_code = code;
}
public string Name { get { return _name; } }
public string Code { get { return _code; } }
public override void ToString()
{
return _name;
}
}
Adding a page like below and routing might help
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutkart/utils/flutkart.dart';
import 'package:flutkart/utils/my_navigator.dart';
class SplashScreen extends StatefulWidget {
@override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
// TODO: implement initState
super.initState();
Timer(Duration(seconds: 5), () => MyNavigator.goToIntro(context));
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
fit: StackFit.expand,
children: <Widget>[
Container(
decoration: BoxDecoration(color: Colors.redAccent),
),
Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
flex: 2,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircleAvatar(
backgroundColor: Colors.white,
radius: 50.0,
child: Icon(
Icons.shopping_cart,
color: Colors.greenAccent,
size: 50.0,
),
),
Padding(
padding: EdgeInsets.only(top: 10.0),
),
Text(
Flutkart.name,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 24.0),
)
],
),
),
),
Expanded(
flex: 1,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(),
Padding(
padding: EdgeInsets.only(top: 20.0),
),
Text(
Flutkart.store,
softWrap: true,
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18.0,
color: Colors.white),
)
],
),
)
],
)
],
),
);
}
}
If you want to follow through, see: https://www.youtube.com/watch?v=FNBuo-7zg2Q
In your Topic
model you're allowing for more than one element to have the same topic
field. You have created two with the same one already.
topic=models.TextField(verbose_name='Thema')
Now when trying to add a new learningObjective
you seem to want to add it to only one Topic
that matches what you're sending on the form. Since there's more than one with the same topic
field get
is finding 2, hence the exception.
You can either add the learningObjective
to all Topics with that topic
field:
for t in topic.objects.filter(topic=request.POST['Thema']):
t.learningObjectivesTopic.add(neuesLernziel)
or restrict the Topic
model to have a unique topic
field and keep using get
, but that might not be what you want.
rgba
value for the backgroundColor
.For example,
backgroundColor: 'rgba(52, 52, 52, 0.8)'
This sets it to a grey color with 80% opacity, which is derived from the opacity decimal, 0.8
. This value can be anything from 0.0
to 1.0
.
You can also use dictionaries that allows you to have more control over the plots:
import matplotlib.pyplot as plt
# plot 0 plot 1 plot 2 plot 3
x=[[1,2,3,4],[1,4,3,4],[1,2,3,4],[9,8,7,4]]
y=[[3,2,3,4],[3,6,3,4],[6,7,8,9],[3,2,2,4]]
plots = zip(x,y)
def loop_plot(plots):
figs={}
axs={}
for idx,plot in enumerate(plots):
figs[idx]=plt.figure()
axs[idx]=figs[idx].add_subplot(111)
axs[idx].plot(plot[0],plot[1])
return figs, axs
figs, axs = loop_plot(plots)
Now you can select the plot that you want to modify easily:
axs[0].set_title("Now I can control it!")
Of course, is up to you to decide what to do with the plots. You can either save them to disk figs[idx].savefig("plot_%s.png" %idx)
or show them plt.show()
. Use the argument block=False
only if you want to pop up all the plots together (this could be quite messy if you have a lot of plots). You can do this inside the loop_plot
function or in a separate loop using the dictionaries that the function provided.
In my opinion, the accepted answer is confusing, since it uses a DataFrame with only missing values. I also do not like the term position-based for .iloc
and instead, prefer integer location as it is much more descriptive and exactly what .iloc
stands for. The key word is INTEGER - .iloc
needs INTEGERS.
See my extremely detailed blog series on subset selection for more
Because .ix
is deprecated we will only focus on the differences between .loc
and .iloc
.
Before we talk about the differences, it is important to understand that DataFrames have labels that help identify each column and each index. Let's take a look at a sample DataFrame:
df = pd.DataFrame({'age':[30, 2, 12, 4, 32, 33, 69],
'color':['blue', 'green', 'red', 'white', 'gray', 'black', 'red'],
'food':['Steak', 'Lamb', 'Mango', 'Apple', 'Cheese', 'Melon', 'Beans'],
'height':[165, 70, 120, 80, 180, 172, 150],
'score':[4.6, 8.3, 9.0, 3.3, 1.8, 9.5, 2.2],
'state':['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX']
},
index=['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean', 'Christina', 'Cornelia'])
All the words in bold are the labels. The labels, age
, color
, food
, height
, score
and state
are used for the columns. The other labels, Jane
, Nick
, Aaron
, Penelope
, Dean
, Christina
, Cornelia
are used for the index.
The primary ways to select particular rows in a DataFrame are with the .loc
and .iloc
indexers. Each of these indexers can also be used to simultaneously select columns but it is easier to just focus on rows for now. Also, each of the indexers use a set of brackets that immediately follow their name to make their selections.
We will first talk about the .loc
indexer which only selects data by the index or column labels. In our sample DataFrame, we have provided meaningful names as values for the index. Many DataFrames will not have any meaningful names and will instead, default to just the integers from 0 to n-1, where n is the length of the DataFrame.
There are three different inputs you can use for .loc
Selecting a single row with .loc with a string
To select a single row of data, place the index label inside of the brackets following .loc
.
df.loc['Penelope']
This returns the row of data as a Series
age 4
color white
food Apple
height 80
score 3.3
state AL
Name: Penelope, dtype: object
Selecting multiple rows with .loc with a list of strings
df.loc[['Cornelia', 'Jane', 'Dean']]
This returns a DataFrame with the rows in the order specified in the list:
Selecting multiple rows with .loc with slice notation
Slice notation is defined by a start, stop and step values. When slicing by label, pandas includes the stop value in the return. The following slices from Aaron to Dean, inclusive. Its step size is not explicitly defined but defaulted to 1.
df.loc['Aaron':'Dean']
Complex slices can be taken in the same manner as Python lists.
Let's now turn to .iloc
. Every row and column of data in a DataFrame has an integer location that defines it. This is in addition to the label that is visually displayed in the output. The integer location is simply the number of rows/columns from the top/left beginning at 0.
There are three different inputs you can use for .iloc
Selecting a single row with .iloc with an integer
df.iloc[4]
This returns the 5th row (integer location 4) as a Series
age 32
color gray
food Cheese
height 180
score 1.8
state AK
Name: Dean, dtype: object
Selecting multiple rows with .iloc with a list of integers
df.iloc[[2, -2]]
This returns a DataFrame of the third and second to last rows:
Selecting multiple rows with .iloc with slice notation
df.iloc[:5:3]
One excellent ability of both .loc/.iloc
is their ability to select both rows and columns simultaneously. In the examples above, all the columns were returned from each selection. We can choose columns with the same types of inputs as we do for rows. We simply need to separate the row and column selection with a comma.
For example, we can select rows Jane, and Dean with just the columns height, score and state like this:
df.loc[['Jane', 'Dean'], 'height':]
This uses a list of labels for the rows and slice notation for the columns
We can naturally do similar operations with .iloc
using only integers.
df.iloc[[1,4], 2]
Nick Lamb
Dean Cheese
Name: food, dtype: object
.ix
was used to make selections simultaneously with labels and integer location which was useful but confusing and ambiguous at times and thankfully it has been deprecated. In the event that you need to make a selection with a mix of labels and integer locations, you will have to make both your selections labels or integer locations.
For instance, if we want to select rows Nick
and Cornelia
along with columns 2 and 4, we could use .loc
by converting the integers to labels with the following:
col_names = df.columns[[2, 4]]
df.loc[['Nick', 'Cornelia'], col_names]
Or alternatively, convert the index labels to integers with the get_loc
index method.
labels = ['Nick', 'Cornelia']
index_ints = [df.index.get_loc(label) for label in labels]
df.iloc[index_ints, [2, 4]]
The .loc indexer can also do boolean selection. For instance, if we are interested in finding all the rows wher age is above 30 and return just the food
and score
columns we can do the following:
df.loc[df['age'] > 30, ['food', 'score']]
You can replicate this with .iloc
but you cannot pass it a boolean series. You must convert the boolean Series into a numpy array like this:
df.iloc[(df['age'] > 30).values, [2, 4]]
It is possible to use .loc/.iloc
for just column selection. You can select all the rows by using a colon like this:
df.loc[:, 'color':'score':2]
[]
, can select rows and columns too but not simultaneously.Most people are familiar with the primary purpose of the DataFrame indexing operator, which is to select columns. A string selects a single column as a Series and a list of strings selects multiple columns as a DataFrame.
df['food']
Jane Steak
Nick Lamb
Aaron Mango
Penelope Apple
Dean Cheese
Christina Melon
Cornelia Beans
Name: food, dtype: object
Using a list selects multiple columns
df[['food', 'score']]
What people are less familiar with, is that, when slice notation is used, then selection happens by row labels or by integer location. This is very confusing and something that I almost never use but it does work.
df['Penelope':'Christina'] # slice rows by label
df[2:6:2] # slice rows by integer location
The explicitness of .loc/.iloc
for selecting rows is highly preferred. The indexing operator alone is unable to select rows and columns simultaneously.
df[3:5, 'color']
TypeError: unhashable type: 'slice'
The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.
The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example):
`Example:
#!/usr/bin/python
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter
print "Good bye!"
This will produce following result:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
The preceding code does not execute any statement or code if the value of letter is 'h'. The pass statement is helpful when you have created a code block but it is no longer required.
You can then remove the statements inside the block but let the block remain with a pass statement so that it doesn't interfere with other parts of the code.
I don't know if this has changed. But from my experience. nested elements have a maximum opacity equal to the fathers.
Which mean:
<div id="a">
<div id="b">
</div></div>
Div#a has 0.6 opacity
div#b has 1 opacity
Has #b is within #a then it's maximum opacity is always 0.6
If #b would have 0.5 opacity. In reallity it would be 0.6*0.5 == 0.3 opacity
If you just need the free space on a device, see the answer using os.statvfs()
below.
If you also need the device name and mount point associated with the file, you should call an external program to get this information. df
will provide all the information you need -- when called as df filename
it prints a line about the partition that contains the file.
To give an example:
import subprocess
df = subprocess.Popen(["df", "filename"], stdout=subprocess.PIPE)
output = df.communicate()[0]
device, size, used, available, percent, mountpoint = \
output.split("\n")[1].split()
Note that this is rather brittle, since it depends on the exact format of the df
output, but I'm not aware of a more robust solution. (There are a few solutions relying on the /proc
filesystem below that are even less portable than this one.)
The answer from Billbad only works with a fixed width of the .inner
div.
This solution works for a dynamic width by adding the attribute text-align: center
to the .outer
div.
.outer {_x000D_
position: absolute;_x000D_
display: table;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
text-align: center;_x000D_
}_x000D_
.middle {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
}_x000D_
.inner {_x000D_
text-align: center;_x000D_
display: inline-block;_x000D_
width: auto;_x000D_
}
_x000D_
<div class="outer">_x000D_
<div class="middle">_x000D_
<div class="inner">_x000D_
Content_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
The HTML parser simply doesn't interpret the inlined javascript like this.
You may do this :
<td><input type="checkbox" id="repriseCheckBox" name="repriseCheckBox"/></td>
<script>document.getElementById("repriseCheckBox").disabled=checkStat == 1 ? true : false;</script>
ALTER TABLE xxx
AUTO_INCREMENT =1;
or
clear your table by TRUNCATE
see this http://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.String-
JSONObject
public JSONObject(java.lang.String source)
throws JSONException
Construct a JSONObject from a source JSON text string. This is the most commonly used` JSONObject constructor.
Parameters:
source - `A string beginning with { (left brace) and ending with } (right brace).`
Throws:
JSONException - If there is a syntax error in the source string or a duplicated key.
you try to use some thing like:
new JSONObject("{your string}")
If you are in need of specific implementation for sorting algorithms, data structures or anything that have a link to the above, could I recommend you the excellent "Data Structures and Algorithms" project on CodePlex?
It will have everything you need without reinventing the wheel.
Just my little grain of salt.
Here is a useful article by Michael J. Swart on the matter, which covers different patterns and antipatterns for implementing UPSERT
in SQL Server:
https://michaeljswart.com/2017/07/sql-server-upsert-patterns-and-antipatterns/
It addresses associated concurrency issues (primary key violations, deadlocks) - all of the answers provided here yet are considered antipatterns in the article (except for the @Bridge solution using triggers, which is not covered there).
Here is an extract from the article with the solution preferred by the author:
Inside a serializable transaction with lock hints:
CREATE PROCEDURE s_AccountDetails_Upsert ( @Email nvarchar(4000), @Etc nvarchar(max) )
AS
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRAN
IF EXISTS ( SELECT * FROM dbo.AccountDetails WITH (UPDLOCK) WHERE Email = @Email )
UPDATE dbo.AccountDetails
SET Etc = @Etc
WHERE Email = @Email;
ELSE
INSERT dbo.AccountDetails ( Email, Etc )
VALUES ( @Email, @Etc );
COMMIT
There is also related question with answers here on stackoverflow: Insert Update stored proc on SQL Server
one way is to convert it to list
>>> b=list(mytuple)
>>> b.append("something")
>>> a=tuple(b)
Do the following:
<html>
)This is a hacky way, but it's the easiest way to do this.
By default, the access modifier for a class is internal
. That means to say, a class is accessible within the same assembly. But if we want the class to be accessed from other assemblies then it has to be made public.
A fragment lives inside an activity, while an activity lives by itself.
List<Class1> list = new List<Class1>();
int index = list.FindIndex(item => item.Number == textBox6.Text);
Class1 newItem = new Class1();
newItem.Prob1 = "SomeValue";
list[index] = newItem;
Try this....
var d = new Date();
alert(d.getFullYear()+'/'+(d.getMonth()+1)+'/'+d.getDate());
getMonth() return month 0 to 11 so we would like to add 1 for accurate month
Reference by : http://www.w3schools.com/jsref/jsref_obj_date.asp
I think, from your description, the following would suffice:
DELETE FROM guide_category
WHERE id_guide NOT IN (SELECT id_guide FROM guide)
I assume, that there are no referential integrity constraints on the tables involved, are there?
<table>
<tbody>
<tr><td>{{data[0].foo}}</td></tr>
<tr ng-repeat="d in data[1]"><td>{{d.bar}}</td></tr>
<tr ng-repeat="d in data[2]"><td>{{d.lol}}</td></tr>
</tbody>
</table>
I think that this is valid :)
Something like gunzip using the -r flag?....
Travel the directory structure recursively. If any of the file names specified on the command line are directories, gzip will descend into the directory and compress all the files it finds there (or decompress them in the case of gunzip ).
For properties for which css transition will affect, can use transitionend event, example for z-index:
$(".observed-element").on("webkitTransitionEnd transitionend", function(e) {_x000D_
console.log("end", e);_x000D_
alert("z-index changed");_x000D_
});_x000D_
_x000D_
$(".changeButton").on("click", function() {_x000D_
console.log("click");_x000D_
document.querySelector(".observed-element").style.zIndex = (Math.random() * 1000) | 0;_x000D_
});
_x000D_
.observed-element {_x000D_
transition: z-index 1ms;_x000D_
-webkit-transition: z-index 1ms;_x000D_
}_x000D_
div {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
border: 1px solid;_x000D_
position: absolute;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button class="changeButton">change z-index</button>_x000D_
<div class="observed-element"></div>
_x000D_
use extent with custom function to handle multiple inheritance with es6
var aggregation = (baseClass, ...mixins) => {_x000D_
let base = class _Combined extends baseClass {_x000D_
constructor (...args) {_x000D_
super(...args)_x000D_
mixins.forEach((mixin) => {_x000D_
mixin.prototype.initializer.call(this)_x000D_
})_x000D_
}_x000D_
}_x000D_
let copyProps = (target, source) => {_x000D_
Object.getOwnPropertyNames(source)_x000D_
.concat(Object.getOwnPropertySymbols(source))_x000D_
.forEach((prop) => {_x000D_
if (prop.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/))_x000D_
return_x000D_
Object.defineProperty(target, prop, Object.getOwnPropertyDescriptor(source, prop))_x000D_
})_x000D_
}_x000D_
mixins.forEach((mixin) => {_x000D_
copyProps(base.prototype, mixin.prototype)_x000D_
copyProps(base, mixin)_x000D_
})_x000D_
return base_x000D_
}_x000D_
_x000D_
class Colored {_x000D_
initializer () { this._color = "white" }_x000D_
get color () { return this._color }_x000D_
set color (v) { this._color = v }_x000D_
}_x000D_
_x000D_
class ZCoord {_x000D_
initializer () { this._z = 0 }_x000D_
get z () { return this._z }_x000D_
set z (v) { this._z = v }_x000D_
}_x000D_
_x000D_
class Shape {_x000D_
constructor (x, y) { this._x = x; this._y = y }_x000D_
get x () { return this._x }_x000D_
set x (v) { this._x = v }_x000D_
get y () { return this._y }_x000D_
set y (v) { this._y = v }_x000D_
}_x000D_
_x000D_
class Rectangle extends aggregation(Shape, Colored, ZCoord) {}_x000D_
_x000D_
var rect = new Rectangle(7, 42)_x000D_
rect.z = 1000_x000D_
rect.color = "red"_x000D_
console.log(rect.x, rect.y, rect.z, rect.color)
_x000D_
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (object item in row.ItemArray)
{
// read item
}
}
}
Or, if you need the column info:
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
object item = row[column];
// read column and item
}
}
}
Test for ':' first, then take test string up to ':' or end, depending on if it was found
Dim strResult As String
' Position of :
intPos = InStr(1, strTest, ":")
If intPos > 0 Then
' : found, so take up to :
strResult = Left(strTest, intPos - 1)
Else
' : not found, so take whole string
strResult = strTest
End If
If you're working in a large multi-module project, with several different application.properties
files, then try adding your value to the parent project's property file.
If you are unsure which is your parent project, check your project's pom.xml
file, for a <parent>
tag.
This solved the issue for me.
Mainly If you are using Linux Based system Like 'Ubuntu' and this is only suggested for localhost user not for the server.
Follow all the steps mentioned in the previous answers. +
Check in Apache configuration for it. (AllowOverride All) If AllowOverride value is none then change it to All and restart apache again.
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
Let me know if this step help anyone. As it can save you time if you find it earlier.
I am adding the exact lines from my htaccess file in localhost. for your reference
Around line number 110
<IfModule mod_rewrite.c>
############################################
## enable rewrites
Options +FollowSymLinks
RewriteEngine on
############################################
## you can put here your magento root folder
## path relative to web root
#RewriteBase /
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
Images are for some user who understand easily from image the from the text:
Everything here was failing as wrong path. Then I remembered a trick from the old Win95 days. Open the program folder where the .dll resides, open C:/Windows/System32 scroll down to regsvr32 and drag and drop the dll from the program folder onto rgsrver32. Boom,done.
Private constructor and static methods on a class marked as final.
In my case, simply removing the tc.log in /var/lib/mysql was enough to start mariadb/mysql again.
&& ; || are logical operators.... short circuit
& ; | are boolean logical operators.... Non-short circuit
Moving to differences in execution on expressions. Bitwise operators evaluate both sides irrespective of the result of left hand side. But in the case of evaluating expressions with logical operators, the evaluation of the right hand expression is dependent on the left hand condition.
For Example:
int i = 25;
int j = 25;
if(i++ < 0 && j++ > 0)
System.out.println("OK");
System.out.printf("i = %d ; j = %d",i,j);
This will print i=26 ; j=25, As the first condition is false the right hand condition is bypassed as the result is false anyways irrespective of the right hand side condition.(short circuit)
int i = 25;
int j = 25;
if(i++ < 0 & j++ > 0)
System.out.println("OK");
System.out.printf("i = %d ; j = %d",i,j);
But, this will print i=26; j=26,
Apparently the question poorly describes the OP's problem, but this question is the top search result for dragging to reorder table rows, so that is what I will answer. I wasn't interested in bringing in jQuery UI for something so simple, so here is a jQuery only solution:
$(".grab").mousedown(function(e) {
var tr = $(e.target).closest("TR"),
si = tr.index(),
sy = e.pageY,
b = $(document.body),
drag;
if (si == 0) return;
b.addClass("grabCursor").css("userSelect", "none");
tr.addClass("grabbed");
function move(e) {
if (!drag && Math.abs(e.pageY - sy) < 10) return;
drag = true;
tr.siblings().each(function() {
var s = $(this),
i = s.index(),
y = s.offset().top;
if (i > 0 && e.pageY >= y && e.pageY < y + s.outerHeight()) {
if (i < tr.index())
tr.insertAfter(s);
else
tr.insertBefore(s);
return false;
}
});
}
function up(e) {
if (drag && si != tr.index()) {
drag = false;
alert("moved!");
}
$(document).unbind("mousemove", move).unbind("mouseup", up);
b.removeClass("grabCursor").css("userSelect", "none");
tr.removeClass("grabbed");
}
$(document).mousemove(move).mouseup(up);
});
_x000D_
.grab {
cursor: grab;
}
.grabbed {
box-shadow: 0 0 13px #000;
}
.grabCursor,
.grabCursor * {
cursor: grabbing !important;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th></th>
<th>Table Header</th>
</tr>
<tr>
<td class="grab">☰</td>
<td>Table Cell 1</td>
</tr>
<tr>
<td class="grab">☰</td>
<td>Table Cell 2</td>
</tr>
<tr>
<td class="grab">☰</td>
<td>Table Cell 3</td>
</tr>
</table>
_x000D_
Note si == 0
and i > 0
ignores the first row, which for me contains TH
tags. Replace the alert
with your "drag finished" logic.
GRANT
s on different objects are separate. GRANT
ing on a database doesn't GRANT
rights to the schema within. Similiarly, GRANT
ing on a schema doesn't grant rights on the tables within.
If you have rights to SELECT
from a table, but not the right to see it in the schema that contains it then you can't access the table.
The rights tests are done in order:
Do you have `USAGE` on the schema?
No: Reject access.
Yes: Do you also have the appropriate rights on the table?
No: Reject access.
Yes: Check column privileges.
Your confusion may arise from the fact that the public
schema has a default GRANT
of all rights to the role public
, which every user/group is a member of. So everyone already has usage on that schema.
The phrase:
(assuming that the objects' own privilege requirements are also met)
Is saying that you must have USAGE
on a schema to use objects within it, but having USAGE
on a schema is not by itself sufficient to use the objects within the schema, you must also have rights on the objects themselves.
It's like a directory tree. If you create a directory somedir
with file somefile
within it then set it so that only your own user can access the directory or the file (mode rwx------
on the dir, mode rw-------
on the file) then nobody else can list the directory to see that the file exists.
If you were to grant world-read rights on the file (mode rw-r--r--
) but not change the directory permissions it'd make no difference. Nobody could see the file in order to read it, because they don't have the rights to list the directory.
If you instead set rwx-r-xr-x
on the directory, setting it so people can list and traverse the directory but not changing the file permissions, people could list the file but could not read it because they'd have no access to the file.
You need to set both permissions for people to actually be able to view the file.
Same thing in Pg. You need both schema USAGE
rights and object rights to perform an action on an object, like SELECT
from a table.
(The analogy falls down a bit in that PostgreSQL doesn't have row-level security yet, so the user can still "see" that the table exists in the schema by SELECT
ing from pg_class
directly. They can't interact with it in any way, though, so it's just the "list" part that isn't quite the same.)
The simple way is to create table as textfile and move the file to the appropriate location
CREATE EXTERNAL TABLE mytable(col1 string, col2 string)
row format delimited fields terminated by '|' stored as textfile;
Copy the file to the HDFS Location where table is created.
Hope this helps!!!
I have tried to use AjaxableResponseMixin in my project, but had ended up with the following error message:
ImproperlyConfigured: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.
That is because the CreateView will return a redirect response instead of returning a HttpResponse when you to send JSON request to the browser. So I have made some changes to the AjaxableResponseMixin
. If the request is an ajax request, it will not call the super.form_valid
method, just call the form.save()
directly.
from django.http import JsonResponse
from django import forms
from django.db import models
class AjaxableResponseMixin(object):
success_return_code = 1
error_return_code = 0
"""
Mixin to add AJAX support to a form.
Must be used with an object-based FormView (e.g. CreateView)
"""
def form_invalid(self, form):
response = super(AjaxableResponseMixin, self).form_invalid(form)
if self.request.is_ajax():
form.errors.update({'result': self.error_return_code})
return JsonResponse(form.errors, status=400)
else:
return response
def form_valid(self, form):
# We make sure to call the parent's form_valid() method because
# it might do some processing (in the case of CreateView, it will
# call form.save() for example).
if self.request.is_ajax():
self.object = form.save()
data = {
'result': self.success_return_code
}
return JsonResponse(data)
else:
response = super(AjaxableResponseMixin, self).form_valid(form)
return response
class Product(models.Model):
name = models.CharField('product name', max_length=255)
class ProductAddForm(forms.ModelForm):
'''
Product add form
'''
class Meta:
model = Product
exclude = ['id']
class PriceUnitAddView(AjaxableResponseMixin, CreateView):
'''
Product add view
'''
model = Product
form_class = ProductAddForm
img And You can use this kode
class Nokta:
def __init__(self,x,y):
self.x=x
self.y=y
class Dogru:
def __init__(self,a,b):
self.a=a
self.b=b
def Kesisim(self,Dogru_b):
x1= self.a.x
x2=self.b.x
x3=Dogru_b.a.x
x4=Dogru_b.b.x
y1= self.a.y
y2=self.b.y
y3=Dogru_b.a.y
y4=Dogru_b.b.y
#Notlardaki denklemleri kullandim
pay1=((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3))
pay2=((x2-x1) * (y1 - y3) - (y2 - y1) * (x1 - x3))
payda=((y4 - y3) *(x2-x1)-(x4 - x3)*(y2 - y1))
if pay1==0 and pay2==0 and payda==0:
print("DOGRULAR BIRBIRINE ÇAKISIKTIR")
elif payda==0:
print("DOGRULAR BIRBIRNE PARALELDIR")
else:
ua=pay1/payda if payda else 0
ub=pay2/payda if payda else 0
#x ve y buldum
x=x1+ua*(x2-x1)
y=y1+ua*(y2-y1)
print("DOGRULAR {},{} NOKTASINDA KESISTI".format(x,y))
Try this:
$str = '546788';
$char_array = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
Http 415 Media Unsupported
is responded back only when the content type header you are providing is not supported by the application.
With POSTMAN, the Content-type
header you are sending is Content type 'multipart/form-data
not application/json
. While in the ajax code you are setting it correctly to application/json
. Pass the correct Content-type header in POSTMAN and it will work.
Use numpy.dot
or a.dot(b)
. See the documentation here.
>>> a = np.array([[ 5, 1 ,3],
[ 1, 1 ,1],
[ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])
This occurs because numpy arrays are not matrices, and the standard operations *, +, -, /
work element-wise on arrays. Instead, you could try using numpy.matrix
, and *
will be treated like matrix multiplication.
Also know there are other options:
As noted below, if using python3.5+ the @
operator works as you'd expect:
>>> print(a @ b)
array([16, 6, 8])
If you want overkill, you can use numpy.einsum
. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.
>>> np.einsum('ji,i->j', a, b)
array([16, 6, 8])
As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul
, which works like numpy.dot
with two major exceptions: no scalar multiplication but it works with stacks of matrices.
>>> np.matmul(a, b)
array([16, 6, 8])
numpy.inner
functions the same way as numpy.dot
for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).
>>> np.inner(a, b)
array([16, 6, 8])
# Beware using for matrix-matrix multiplication though!
>>> b = a.T
>>> np.dot(a, b)
array([[35, 9, 10],
[ 9, 3, 4],
[10, 4, 6]])
>>> np.inner(a, b)
array([[29, 12, 19],
[ 7, 4, 5],
[ 8, 5, 6]])
If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot
with the optional argument axes=1
:
>>> np.tensordot(a, b, axes=1)
array([16, 6, 8])
Don't use numpy.vdot
if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m
vs n
).
So to add the string hello
to a list as individual characters, try this:
newlist = []
newlist[:0] = 'hello'
print (newlist)
['h','e','l','l','o']
However, it is easier to do this:
splitlist = list(newlist)
print (splitlist)