PDO Prepared Inserts multiple rows in single query
Multiple Values Insert with PDO Prepared Statements
Inserting multiple values in one execute statement. Why because according to this page it is faster than regular inserts.
$datafields = array('fielda', 'fieldb', ... );
$data[] = array('fielda' => 'value', 'fieldb' => 'value' ....);
$data[] = array('fielda' => 'value', 'fieldb' => 'value' ....);
more data values or you probably have a loop that populates data.
With prepared inserts you need to know the fields you're inserting to, and the number of fields to create the ? placeholders to bind your parameters.
insert into table (fielda, fieldb, ... ) values (?,?...), (?,?...)....
That is basically how we want the insert statement to look like.
Now, the code:
function placeholders($text, $count=0, $separator=","){
$result = array();
if($count > 0){
for($x=0; $x<$count; $x++){
$result[] = $text;
}
}
return implode($separator, $result);
}
$pdo->beginTransaction(); // also helps speed up your inserts.
$insert_values = array();
foreach($data as $d){
$question_marks[] = '(' . placeholders('?', sizeof($d)) . ')';
$insert_values = array_merge($insert_values, array_values($d));
}
$sql = "INSERT INTO table (" . implode(",", $datafields ) . ") VALUES " .
implode(',', $question_marks);
$stmt = $pdo->prepare ($sql);
$stmt->execute($insert_values);
$pdo->commit();
Although in my test, there was only a 1 sec difference when using multiple inserts and regular prepared inserts with single value.
SQL Server 2008 - Help writing simple INSERT Trigger
cmsjr had the right solution. I just wanted to point out a couple of things for your future trigger development. If you are using the values statement in an insert in a trigger, there is a stong possibility that you are doing the wrong thing. Triggers fire once for each batch of records inserted, deleted, or updated. So if ten records were inserted in one batch, then the trigger fires once. If you are refering to the data in the inserted or deleted and using variables and the values clause then you are only going to get the data for one of those records. This causes data integrity problems. You can fix this by using a set-based insert as cmsjr shows above or by using a cursor. Don't ever choose the cursor path. A cursor in a trigger is a problem waiting to happen as they are slow and may well lock up your table for hours. I removed a cursor from a trigger once and improved an import process from 40 minutes to 45 seconds.
You may think nobody is ever going to add multiple records, but it happens more frequently than most non-database people realize. Don't write a trigger that will not work under all the possible insert, update, delete conditions. Nobody is going to use the one record at a time method when they have to import 1,000,000 sales target records from a new customer or update all the prices by 10% or delete all the records from a vendor whose products you don't sell anymore.
Python and SQLite: insert into table
conn = sqlite3.connect('/path/to/your/sqlite_file.db')
c = conn.cursor()
for item in my_list:
c.execute('insert into tablename values (?,?,?)', item)
Add (insert) a column between two columns in a data.frame
You can reorder the columns with [, or present the columns in the order that you want.
d <- data.frame(a=1:4, b=5:8, c=9:12)
target <- which(names(d) == 'b')[1]
cbind(d[,1:target,drop=F], data.frame(d=12:15), d[,(target+1):length(d),drop=F])
a b d c
1 1 5 12 9
2 2 6 13 10
3 3 7 14 11
4 4 8 15 12
MySQL Error 1264: out of range value for column
The value 3172978990 is greater than 2147483647 – the maximum value for INT
– hence the error. MySQL integer types and their ranges are listed here.
Also note that the (10)
in INT(10)
does not define the "size" of an integer. It specifies the display width of the column. This information is advisory only.
To fix the error, change your datatype to VARCHAR
. Phone and Fax numbers should be stored as strings. See this discussion.
"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
In case you want to see what this all means, here is a blow-by-blow of everything:
CREATE TABLE `users_partners` (
`uid` int(11) NOT NULL DEFAULT '0',
`pid` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`uid`,`pid`),
KEY `partner_user` (`pid`,`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
Primary key is based on both columns of this quick reference table. A Primary key requires unique values.
Let's begin:
INSERT INTO users_partners (uid,pid) VALUES (1,1);
...1 row(s) affected
INSERT INTO users_partners (uid,pid) VALUES (1,1);
...Error Code : 1062
...Duplicate entry '1-1' for key 'PRIMARY'
INSERT IGNORE INTO users_partners (uid,pid) VALUES (1,1);
...0 row(s) affected
INSERT INTO users_partners (uid,pid) VALUES (1,1) ON DUPLICATE KEY UPDATE uid=uid
...0 row(s) affected
note, the above saved too much extra work by setting the column equal to itself, no update actually needed
REPLACE INTO users_partners (uid,pid) VALUES (1,1)
...2 row(s) affected
and now some multiple row tests:
INSERT INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4)
...Error Code : 1062
...Duplicate entry '1-1' for key 'PRIMARY'
INSERT IGNORE INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4)
...3 row(s) affected
no other messages were generated in console, and it now has those 4 values in the table data. I deleted everything except (1,1) so I could test from the same playing field
INSERT INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4) ON DUPLICATE KEY UPDATE uid=uid
...3 row(s) affected
REPLACE INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4)
...5 row(s) affected
So there you have it. Since this was all performed on a fresh table with nearly no data and not in production, the times for execution were microscopic and irrelevant. Anyone with real-world data would be more than welcome to contribute it.
PHP mysql insert date format
HTML:
<div class="form-group">
<label for="pt_date" class="col-2 col-form-label">Date</label>
<input class="form-control" type="date" value=<?php echo date("Y-m-d") ;?> id="pt_date" name="pt_date">
</div>
SQL
$pt_date = $_POST['pt_date'];
$sql = "INSERT INTO `table` ( `pt_date`) VALUES ( '$pt_date')";
How to insert a picture into Excel at a specified cell position with VBA
If it's simply about inserting and resizing a picture, try the code below.
For the specific question you asked, the property TopLeftCell returns the range object related to the cell where the top left corner is parked. To place a new image at a specific place, I recommend creating an image at the "right" place and registering its top and left properties values of the dummy onto double variables.
Insert your Pic assigned to a variable to easily change its name. The Shape Object will have that same name as the Picture Object.
Sub Insert_Pic_From_File(PicPath as string, wsDestination as worksheet)
Dim Pic As Picture, Shp as Shape
Set Pic = wsDestination.Pictures.Insert(FilePath)
Pic.Name = "myPicture"
'Strongly recommend using a FileSystemObject.FileExists method to check if the path is good before executing the previous command
Set Shp = wsDestination.Shapes("myPicture")
With Shp
.Height = 100
.Width = 75
.LockAspectRatio = msoTrue 'Put this later so that changing height doesn't change width and vice-versa)
.Placement = 1
.Top = 100
.Left = 100
End with
End Sub
Good luck!
PHP - Insert date into mysql
try converting the date first.
$date = "2012-08-06";
mysql_query("INSERT INTO data_table (title, date_of_event)
VALUES('" . $_POST['post_title'] . "',
'" . $date . "')")
or die(mysql_error());
Insert text with single quotes in PostgreSQL
In postgresql if you want to insert values with '
in it then for this you have to give extra '
insert into test values (1,'user''s log');
insert into test values (2,'''my users''');
insert into test values (3,'customer''s');
SQL Server Insert Example
Here are 4 ways to insert data into a table.
Simple insertion when the table column sequence is known.
INSERT INTO Table1 VALUES (1,2,...)
Simple insertion into specified columns of the table.
INSERT INTO Table1(col2,col4) VALUES (1,2)
Bulk insertion when...
- You wish to insert every column of Table2 into Table1
- You know the column sequence of Table2
- You are certain that the column sequence of Table2 won't change while this statement is being used (perhaps you the statement will only be used once).
INSERT INTO Table1 {Column sequence} SELECT * FROM Table2
Bulk insertion of selected data into specified columns of Table2.
.
INSERT INTO Table1 (Column1,Column2 ....)
SELECT Column1,Column2...
FROM Table2
Increment a database field by 1
Updating an entry:
A simple increment should do the trick.
UPDATE mytable
SET logins = logins + 1
WHERE id = 12
Insert new row, or Update if already present:
If you would like to update a previously existing row, or insert it if it doesn't already exist, you can use the REPLACE
syntax or the INSERT...ON DUPLICATE KEY UPDATE
option (As Rob Van Dam demonstrated in his answer).
Inserting a new entry:
Or perhaps you're looking for something like INSERT...MAX(logins)+1
? Essentially you'd run a query much like the following - perhaps a bit more complex depending on your specific needs:
INSERT into mytable (logins)
SELECT max(logins) + 1
FROM mytable
PHP/MySQL Insert null values
I think you need quotes around your {$row['null_field']}
, so '{$row['null_field']}'
If you don't have the quotes, you'll occasionally end up with an insert statement that looks like this: insert into table2 (f1, f2) values ('val1',)
which is a syntax error.
If that is a numeric field, you will have to do some testing above it, and if there is no value in null_field, explicitly set it to null..
INSERT IF NOT EXISTS ELSE UPDATE?
You should use the INSERT OR IGNORE
command followed by an UPDATE
command:
In the following example name
is a primary key:
INSERT OR IGNORE INTO my_table (name, age) VALUES ('Karen', 34)
UPDATE my_table SET age = 34 WHERE name='Karen'
The first command will insert the record. If the record exists, it will ignore the error caused by the conflict with an existing primary key.
The second command will update the record (which now definitely exists)
Insert new item in array on any position in PHP
You can try it, use this method to make it easy
/**
* array insert element on position
*
* @link https://vector.cool
*
* @since 1.01.38
*
* @param array $original
* @param mixed $inserted
* @param int $position
* @return array
*/
function array_insert(&$original, $inserted, int $position): array
{
array_splice($original, $position, 0, array($inserted));
return $original;
}
$columns = [
['name' => '????', 'column' => 'item_name'],
['name' => '????', 'column' => 'start_time'],
['name' => '????', 'column' => 'full_name'],
['name' => '????', 'column' => 'phone'],
['name' => '????', 'column' => 'create_time']
];
$col = ['name' => '????', 'column' => 'user_id'];
$columns = array_insert($columns, $col, 3);
print_r($columns);
Print out:
Array
(
[0] => Array
(
[name] => ????
[column] => item_name
)
[1] => Array
(
[name] => ????
[column] => start_time
)
[2] => Array
(
[name] => ????
[column] => full_name
)
[3] => Array
(
[name] => ????1
[column] => num_of_people
)
[4] => Array
(
[name] => ????
[column] => phone
)
[5] => Array
(
[name] => ????
[column] => user_id
)
[6] => Array
(
[name] => ????
[column] => create_time
)
)
java: use StringBuilder to insert at the beginning
How about:
StringBuilder builder = new StringBuilder();
for(int i=99;i>=0;i--){
builder.append(Integer.toString(i));
}
builder.toString();
OR
StringBuilder builder = new StringBuilder();
for(int i=0;i<100;i++){
builder.insert(0, Integer.toString(i));
}
builder.toString();
But with this, you are making the operation O(N^2) instead of O(N).
Snippet from java docs:
Inserts the string representation of the Object argument into this
character sequence. The overall effect is exactly as if the second
argument were converted to a string by the method
String.valueOf(Object)
, and the characters of that string were then
inserted into this character sequence at the indicated offset.
How to insert values in table with foreign key using MySQL?
Case 1: Insert Row and Query Foreign Key
Here is an alternate syntax I use:
INSERT INTO tab_student
SET name_student = 'Bobby Tables',
id_teacher_fk = (
SELECT id_teacher
FROM tab_teacher
WHERE name_teacher = 'Dr. Smith')
I'm doing this in Excel to import a pivot table to a dimension table and a fact table in SQL so you can import to both department
and expenses
tables from the following:
Case 2: Insert Row and Then Insert Dependant Row
Luckily, MySQL supports LAST_INSERT_ID()
exactly for this purpose.
INSERT INTO tab_teacher
SET name_teacher = 'Dr. Smith';
INSERT INTO tab_student
SET name_student = 'Bobby Tables',
id_teacher_fk = LAST_INSERT_ID()
Combining INSERT INTO and WITH/CTE
Yep:
WITH tab (
bla bla
)
INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos ( BatchID, AccountNo,
APartyNo,
SourceRowID)
SELECT * FROM tab
Note that this is for SQL Server, which supports multiple CTEs:
WITH x AS (), y AS () INSERT INTO z (a, b, c) SELECT a, b, c FROM y
Teradata allows only one CTE and the syntax is as your example.
Add new row to dataframe, at specific row-index, not appended?
Here's a solution that avoids the (often slow) rbind
call:
existingDF <- as.data.frame(matrix(seq(20),nrow=5,ncol=4))
r <- 3
newrow <- seq(4)
insertRow <- function(existingDF, newrow, r) {
existingDF[seq(r+1,nrow(existingDF)+1),] <- existingDF[seq(r,nrow(existingDF)),]
existingDF[r,] <- newrow
existingDF
}
> insertRow(existingDF, newrow, r)
V1 V2 V3 V4
1 1 6 11 16
2 2 7 12 17
3 1 2 3 4
4 3 8 13 18
5 4 9 14 19
6 5 10 15 20
If speed is less important than clarity, then @Simon's solution works well:
existingDF <- rbind(existingDF[1:r,],newrow,existingDF[-(1:r),])
> existingDF
V1 V2 V3 V4
1 1 6 11 16
2 2 7 12 17
3 3 8 13 18
4 1 2 3 4
41 4 9 14 19
5 5 10 15 20
(Note we index r
differently).
And finally, benchmarks:
library(microbenchmark)
microbenchmark(
rbind(existingDF[1:r,],newrow,existingDF[-(1:r),]),
insertRow(existingDF,newrow,r)
)
Unit: microseconds
expr min lq median uq max
1 insertRow(existingDF, newrow, r) 660.131 678.3675 695.5515 725.2775 928.299
2 rbind(existingDF[1:r, ], newrow, existingDF[-(1:r), ]) 801.161 831.7730 854.6320 881.6560 10641.417
Benchmarks
As @MatthewDowle always points out to me, benchmarks need to be examined for the scaling as the size of the problem increases. Here we go then:
benchmarkInsertionSolutions <- function(nrow=5,ncol=4) {
existingDF <- as.data.frame(matrix(seq(nrow*ncol),nrow=nrow,ncol=ncol))
r <- 3 # Row to insert into
newrow <- seq(ncol)
m <- microbenchmark(
rbind(existingDF[1:r,],newrow,existingDF[-(1:r),]),
insertRow(existingDF,newrow,r),
insertRow2(existingDF,newrow,r)
)
# Now return the median times
mediansBy <- by(m$time,m$expr, FUN=median)
res <- as.numeric(mediansBy)
names(res) <- names(mediansBy)
res
}
nrows <- 5*10^(0:5)
benchmarks <- sapply(nrows,benchmarkInsertionSolutions)
colnames(benchmarks) <- as.character(nrows)
ggplot( melt(benchmarks), aes(x=Var2,y=value,colour=Var1) ) + geom_line() + scale_x_log10() + scale_y_log10()
@Roland's solution scales quite well, even with the call to rbind
:
5 50 500 5000 50000 5e+05
insertRow2(existingDF, newrow, r) 549861.5 579579.0 789452 2512926 46994560 414790214
insertRow(existingDF, newrow, r) 895401.0 905318.5 1168201 2603926 39765358 392904851
rbind(existingDF[1:r, ], newrow, existingDF[-(1:r), ]) 787218.0 814979.0 1263886 5591880 63351247 829650894
Plotted on a linear scale:
And a log-log scale:
LAST_INSERT_ID() MySQL
It would be possible to save the last_id_in_table1 variable into a php variable to use it later?
With this last_id I need to attach some records in another table with this last_id, so I need:
1) Do an INSERT and get the last_id_in_table1
INSERT into Table1(name) values ("AAA");
SET @last_id_in_table1 = LAST_INSERT_ID();
2) For any indeterminated rows in another table, UPDATING these rows with the last_id_insert generated in the insert.
$element = array(some ids)
foreach ($element as $e){
UPDATE Table2 SET column1 = @last_id_in_table1 WHERE id = $e
}
Oracle SQL: Use sequence in insert with Select Statement
Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like
INSERT INTO HISTORICAL_CAR_STATS (
HISTORICAL_CAR_STATS_ID,
YEAR,
MONTH,
MAKE,
MODEL,
REGION,
AVG_MSRP,
CNT)
SELECT MY_SEQ.nextval,
year,
month,
make,
model,
region,
avg_msrp,
cnt
FROM (SELECT '2010' year,
'12' month,
'ALL' make,
'ALL' model,
REGION,
sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp,
sum(cnt) cnt
FROM HISTORICAL_CAR_STATS
WHERE YEAR = '2010'
AND MONTH = '12'
AND MAKE != 'ALL'
GROUP BY REGION)
SELECT INTO a table variable in T-SQL
Try to use INSERT
instead of SELECT INTO
:
DECLARE @UserData TABLE(
name varchar(30) NOT NULL,
oldlocation varchar(30) NOT NULL
)
INSERT @UserData
SELECT name, oldlocation
Add row to query result using select
In SQL Server, you would say:
Select name from users
UNION [ALL]
SELECT 'JASON'
In Oracle, you would say
Select name from user
UNION [ALL]
Select 'JASON' from DUAL
Exporting data In SQL Server as INSERT INTO
If you are running SQL Server 2008 R2 the built in options on to do this in SSMS as marc_s described above changed a bit. Instead of selecting Script data = true
as shown in his diagram, there is now a new option called "Types of data to script"
just above the "Table/View Options" grouping. Here you can select to script data only, schema and data or schema only. Works like a charm.
MySQL direct INSERT INTO with WHERE clause
The INSERT INTO Statement
The INSERT INTO statement is used to insert a new row in a table.
SQL INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
ASP.net using a form to insert data into an sql server table
Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" />
</p>
</form>
</body>
Great, now every asp object IS an object. So you can access it in the asp's CS code.
The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page
If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.
Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.
The button is a web control Button Add a Click event to the button call it Button1Click:
void Button1Click(Object sender,EventArgs e) { }
Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.
So if for example you want to access the text in TextBox1
you just need to call that object in the C# code:
String firstBox = TextBox1.Text;
In the same way you can populate the objects when event occur.
Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.
TypeError: 'float' object is not subscriptable
PriceList[0]
is a float. PriceList[0][1]
is trying to access the first element of a float. Instead, do
PriceList[0] = PriceList[1] = ...code omitted... = PriceList[6] = PizzaChange
or
PriceList[0:7] = [PizzaChange]*7
MySql Table Insert if not exist otherwise update
Jai is correct that you should use INSERT ... ON DUPLICATE KEY UPDATE
.
Note that you do not need to include datenum in the update clause since it's the unique key, so it should not change. You do need to include all of the other columns from your table. You can use the VALUES()
function to make sure the proper values are used when updating the other columns.
Here is your update re-written using the proper INSERT ... ON DUPLICATE KEY UPDATE
syntax for MySQL:
INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE
Timestamp=VALUES(Timestamp)
Field 'id' doesn't have a default value?
Since mysql 5.6, there is a new default that makes sure you are explicitly inserting every field that doesn't have a default value set in the table definition.
to disable and test this: see this answer here: mysql error 1364 Field doesn't have a default values
I would recommend you test without it, then reenable it and make sure all your tables have default values for fields you are not explicitly passing in every INSERT query.
If a third party mysql viewer is giving this error, you are probably limited to the fix in that link.
Inserting multiple rows in a single SQL query?
If you are inserting into a single table, you can write your query like this (maybe only in MySQL):
INSERT INTO table1 (First, Last)
VALUES
('Fred', 'Smith'),
('John', 'Smith'),
('Michael', 'Smith'),
('Robert', 'Smith');
Incorrect integer value: '' for column 'id' at row 1
This is because your data sending column type is integer and your are sending a string value to it.
So, the following way worked for me.
Try with this one.
$insertQuery = "INSERT INTO workorders VALUES (
null,
'$priority',
'$requestType',
'$purchaseOrder',
'$nte',
'$jobSiteNumber'
)";
Don't use 'null'
. use it as null
without single quotes.
Insert a row to pandas dataframe
One way to achieve this is
>>> pd.DataFrame(np.array([[2, 3, 4]]), columns=['A', 'B', 'C']).append(df, ignore_index=True)
Out[330]:
A B C
0 2 3 4
1 5 6 7
2 7 8 9
Generally, it's easiest to append dataframes, not series. In your case, since you want the new row to be "on top" (with starting id), and there is no function pd.prepend()
, I first create the new dataframe and then append your old one.
ignore_index
will ignore the old ongoing index in your dataframe and ensure that the first row actually starts with index 1
instead of restarting with index 0
.
Typical Disclaimer: Cetero censeo ... appending rows is a quite inefficient operation. If you care about performance and can somehow ensure to first create a dataframe with the correct (longer) index and then just inserting the additional row into the dataframe, you should definitely do that. See:
>>> index = np.array([0, 1, 2])
>>> df2 = pd.DataFrame(columns=['A', 'B', 'C'], index=index)
>>> df2.loc[0:1] = [list(s1), list(s2)]
>>> df2
Out[336]:
A B C
0 5 6 7
1 7 8 9
2 NaN NaN NaN
>>> df2 = pd.DataFrame(columns=['A', 'B', 'C'], index=index)
>>> df2.loc[1:] = [list(s1), list(s2)]
So far, we have what you had as df
:
>>> df2
Out[339]:
A B C
0 NaN NaN NaN
1 5 6 7
2 7 8 9
But now you can easily insert the row as follows. Since the space was preallocated, this is more efficient.
>>> df2.loc[0] = np.array([2, 3, 4])
>>> df2
Out[341]:
A B C
0 2 3 4
1 5 6 7
2 7 8 9
Python pandas insert list into a cell
Since set_value
has been deprecated since version 0.21.0, you should now use at
. It can insert a list into a cell without raising a ValueError
as loc
does. I think this is because at
always refers to a single value, while loc
can refer to values as well as rows and columns.
df = pd.DataFrame(data={'A': [1, 2, 3], 'B': ['x', 'y', 'z']})
df.at[1, 'B'] = ['m', 'n']
df =
A B
0 1 x
1 2 [m, n]
2 3 z
You also need to make sure the column you are inserting into has dtype=object
. For example
>>> df = pd.DataFrame(data={'A': [1, 2, 3], 'B': [1,2,3]})
>>> df.dtypes
A int64
B int64
dtype: object
>>> df.at[1, 'B'] = [1, 2, 3]
ValueError: setting an array element with a sequence
>>> df['B'] = df['B'].astype('object')
>>> df.at[1, 'B'] = [1, 2, 3]
>>> df
A B
0 1 1
1 2 [1, 2, 3]
2 3 3
oracle plsql: how to parse XML and insert into table
select *
FROM XMLTABLE('/person/row'
PASSING
xmltype('
<person>
<row>
<name>Tom</name>
<Address>
<State>California</State>
<City>Los angeles</City>
</Address>
</row>
<row>
<name>Jim</name>
<Address>
<State>California</State>
<City>Los angeles</City>
</Address>
</row>
</person>
')
COLUMNS
--describe columns and path to them:
name varchar2(20) PATH './name',
state varchar2(20) PATH './Address/State',
city varchar2(20) PATH './Address/City'
) xmlt
;
How to insert an element after another element in JavaScript without using a library?
A quick Google search reveals this script
// create function, it expects 2 values.
function insertAfter(newElement,targetElement) {
// target is what you want it to go after. Look for this elements parent.
var parent = targetElement.parentNode;
// if the parents lastchild is the targetElement...
if (parent.lastChild == targetElement) {
// add the newElement after the target element.
parent.appendChild(newElement);
} else {
// else the target has siblings, insert the new element between the target and it's next sibling.
parent.insertBefore(newElement, targetElement.nextSibling);
}
}
Escaping single quote in PHP when inserting into MySQL
You have a couple of things fighting in your strings.
- lack of correct MySQL quoting (
mysql_real_escape_string()
)
- potential automatic 'magic quote' -- check your gpc_magic_quotes setting
- embedded string variables, which means you have to know how PHP correctly finds variables
It's also possible that the single-quoted value is not present in the parameters to the first query. Your example is a proper name, after all, and only the second query seems to be dealing with names.
Oracle Insert via Select from multiple tables where one table may not have a row
Outter joins don't work "as expected" in that case because you have explicitly told Oracle you only want data if that criteria on that table matches. In that scenario, the outter join is rendered useless.
A work-around
INSERT INTO account_type_standard
(account_type_Standard_id, tax_status_id, recipient_id)
VALUES(
(SELECT account_type_standard_seq.nextval FROM DUAL),
(SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?),
(SELECT recipient_id FROM recipient WHERE recipient_code = ?)
)
[Edit]
If you expect multiple rows from a sub-select, you can add ROWNUM=1 to each where clause OR use an aggregate such as MAX or MIN. This of course may not be the best solution for all cases.
[Edit] Per comment,
(SELECT account_type_standard_seq.nextval FROM DUAL),
can be just
account_type_standard_seq.nextval,
Java - Including variables within strings?
you can use String format to include variables within strings
i use this code to include 2 variable in string:
String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);
MySQL - ignore insert error: duplicate entry
You can make sure that you do not insert duplicate information by using the EXISTS condition.
For example, if you had a table named clients with a primary key of client_id, you could use the following statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT supplier_id, supplier_name, 'advertising'
FROM suppliers
WHERE not exists (select * from clients
where clients.client_id = suppliers.supplier_id);
This statement inserts multiple records with a subselect.
If you wanted to insert a single record, you could use the following statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT 10345, 'IBM', 'advertising'
FROM dual
WHERE not exists (select * from clients
where clients.client_id = 10345);
The use of the dual table allows you to enter your values in a select statement, even though the values are not currently stored in a table.
from http://www.techonthenet.com/sql/insert.php
How to insert a row in an HTML table body in JavaScript
You can use the following example:
<table id="purches">
<thead>
<tr>
<th>ID</th>
<th>Transaction Date</th>
<th>Category</th>
<th>Transaction Amount</th>
<th>Offer</th>
</tr>
</thead>
<!-- <tr th:each="person: ${list}" >
<td><li th:each="person: ${list}" th:text="|${person.description}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.price}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.available}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.from}|"></li></td>
</tr>
-->
<tbody id="feedback">
</tbody>
</table>
JavaScript file:
$.ajax({
type: "POST",
contentType: "application/json",
url: "/search",
data: JSON.stringify(search),
dataType: 'json',
cache: false,
timeout: 600000,
success: function (data) {
// var json = "<h4>Ajax Response</h4><pre>" + JSON.stringify(data, null, 4) + "</pre>";
// $('#feedback').html(json);
//
console.log("SUCCESS: ", data);
//$("#btn-search").prop("disabled", false);
for (var i = 0; i < data.length; i++) {
//$("#feedback").append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td></tr>');
$('#feedback').append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td></tr>');
alert(data[i].accountNumber)
}
},
error: function (e) {
var json = "<h4>Ajax Response</h4><pre>" + e.responseText + "</pre>";
$('#feedback').html(json);
console.log("ERROR: ", e);
$("#btn-search").prop("disabled", false);
}
});
How to refresh or show immediately in datagridview after inserting?
I don't know if you resolved your problem, but a simple way to resolve this is rebuilding the DataSource (it is a property) of your datagridview. For example:
_x000D_
_x000D_
grdPatient.DataSource = MethodThatReturnList();
_x000D_
_x000D_
_x000D_
So, in that MethodThatReturnList() you can build a List (List is a class) with all the items you need. In my case, I have a method that return the values for two columns that I have on my datagridview.
Pasch.
Insert data into table with result from another select query
Below is an example of such a query:
INSERT INTO [93275].[93276].[93277].[93278] ( [Mobile Number], [Mobile Series], [Full Name], [Full Address], [Active Date], company ) IN 'I:\For Test\90-Mobile Series.accdb
SELECT [1].[Mobile Number], [1].[Mobile Series], [1].[Full Name], [1].[Full Address], [1].[Active Date], [1].[Company Name]
FROM 1
WHERE ((([1].[Mobile Series])="93275" Or ([1].[Mobile Series])="93276")) OR ((([1].[Mobile Series])="93277"));OR ((([1].[Mobile Series])="93278"));
How do I use an INSERT statement's OUTPUT clause to get the identity value?
You can either have the newly inserted ID being output to the SSMS console like this:
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar()
(instead of .ExecuteNonQuery()
) to read the resulting ID
back.
Or if you need to capture the newly inserted ID
inside T-SQL (e.g. for later further processing), you need to create a table variable:
DECLARE @OutputTbl TABLE (ID INT)
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
This way, you can put multiple values into @OutputTbl
and do further processing on those. You could also use a "regular" temporary table (#temp
) or even a "real" persistent table as your "output target" here.
Solutions for INSERT OR UPDATE on SQL Server
See my detailed answer to a very similar previous question
@Beau Crawford's is a good way in SQL 2005 and below, though if you're granting rep it should go to the first guy to SO it. The only problem is that for inserts it's still two IO operations.
MS Sql2008 introduces merge
from the SQL:2003 standard:
merge tablename with(HOLDLOCK) as target
using (values ('new value', 'different value'))
as source (field1, field2)
on target.idfield = 7
when matched then
update
set field1 = source.field1,
field2 = source.field2,
...
when not matched then
insert ( idfield, field1, field2, ... )
values ( 7, source.field1, source.field2, ... )
Now it's really just one IO operation, but awful code :-(
C linked list inserting node at the end
I know this is an old post but just for reference. Here is how to append without the special case check for an empty list, although at the expense of more complex looking code.
void Append(List * l, Node * n)
{
Node ** next = &list->Head;
while (*next != NULL) next = &(*next)->Next;
*next = n;
n->Next = NULL;
}
Insert an element at a specific index in a list and return the updated list
Use the Python list insert() method. Usage:
#Syntax
The syntax for the insert() method -
list.insert(index, obj)
#Parameters
- index - This is the Index where the object obj need to be inserted.
- obj - This is the Object to be inserted into the given list.
#Return Value
This method does not return any value, but it inserts the given element at the given index.
Example:
a = [1,2,4,5]
a.insert(2,3)
print(a)
Returns [1, 2, 3, 4, 5]
PostgreSQL function for last inserted ID
you can use RETURNING clause in INSERT statement,just like the following
wgzhao=# create table foo(id int,name text);
CREATE TABLE
wgzhao=# insert into foo values(1,'wgzhao') returning id;
id
----
1
(1 row)
INSERT 0 1
wgzhao=# insert into foo values(3,'wgzhao') returning id;
id
----
3
(1 row)
INSERT 0 1
wgzhao=# create table bar(id serial,name text);
CREATE TABLE
wgzhao=# insert into bar(name) values('wgzhao') returning id;
id
----
1
(1 row)
INSERT 0 1
wgzhao=# insert into bar(name) values('wgzhao') returning id;
id
----
2
(1 row)
INSERT 0
Java: How to insert CLOB into oracle database
You can very well do it with below code, i am giving you just the code to insert xml hope u are done with rest of other things..
import oracle.xdb.XMLType;
//now inside the class......
// this will be to convert xml into string
File file = new File(your file path);
FileReader fileR = new FileReader(file);
fileR.read(data);
String str = new String(data);
// now to enter it into db
conn = DriverManager.getConnection(serverName, userId, password);
XMLType objXml = XMLType.createXML(conn, str);
// inside the query statement put this code
objPreparedstatmnt.setObject(your value index, objXml);
I have done like this and it is working fine.
SQL - IF EXISTS UPDATE ELSE INSERT INTO
Try this:
INSERT INTO `center_course_fee` (`fk_course_id`,`fk_center_code`,`course_fee`) VALUES ('69', '4920153', '6000') ON DUPLICATE KEY UPDATE `course_fee` = '6000';
Open window in JavaScript with HTML inserted
When you create a new window using open
, it returns a reference to the new window, you can use that reference to write to the newly opened window via its document
object.
Here is an example:
var newWin = open('url','windowName','height=300,width=300');
newWin.document.write('html to write...');
How to do a batch insert in MySQL
Load data infile query is much better option but some servers like godaddy restrict this option on shared hosting so , only two options left then one is insert record on every iteration or batch insert , but batch insert has its limitaion of characters if your query exceeds this number of characters set in mysql then your query will crash , So I suggest insert data in chunks withs batch insert , this will minimize number of connections established with database.best of luck guys
How to insert multiple rows from array using CodeIgniter framework?
You can do it with several ways in codeigniter e.g.
First By loop
foreach($myarray as $row)
{
$data = array("first"=>$row->first,"second"=>$row->sec);
$this->db->insert('table_name',$data);
}
Second -- By insert batch
$data = array(
array(
'first' => $myarray[0]['first'] ,
'second' => $myarray[0]['sec'],
),
array(
'first' => $myarray[1]['first'] ,
'second' => $myarray[1]['sec'],
),
);
$this->db->insert_batch('table_name', $data);
Third way -- By multiple value pass
$sql = array();
foreach( $myarray as $row ) {
$sql[] = '("'.mysql_real_escape_string($row['first']).'", '.$row['sec'].')';
}
mysql_query('INSERT INTO table (first, second) VALUES '.implode(',', $sql));
ExecuteNonQuery: Connection property has not been initialized.
You need to assign the connection to the SqlCommand
, you can use the constructor or the property:
cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ");
cmd.InsertCommand.Connection = connection1;
I strongly recommend to use the using-statement
for any type implementing IDisposable
like SqlConnection
, it'll also close the connection:
using(var connection1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True"))
using(var cmd = new SqlDataAdapter())
using(var insertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) "))
{
insertCommand.Connection = connection1;
cmd.InsertCommand = insertCommand;
//.....
connection1.Open();
// .... you don't need to close the connection explicitely
}
Apart from that you don't need to create a new connection and DataAdapter
for every entry in the foreach
, even if creating, opening and closing a connection does not mean that ADO.NET will create, open and close a physical connection but just looks into the connection-pool for an available connection. Nevertheless it's an unnecessary overhead.
c# datatable insert column at position 0
//Example to define how to do :
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("FirstName");
dt.Columns.Add("LastName");
dt.Columns.Add("Address");
dt.Columns.Add("City");
// The table structure is:
//ID FirstName LastName Address City
//Now we want to add a PhoneNo column after the LastName column. For this we use the
//SetOrdinal function, as iin:
dt.Columns.Add("PhoneNo").SetOrdinal(3);
//3 is the position number and positions start from 0.`enter code here`
//Now the table structure will be:
// ID FirstName LastName PhoneNo Address City
insert data into database with codeigniter
It will be better for you to write your code like this.
In your Controller Write this code.
function new_blank_order_summary() {
$query = $this->sales_model->order_summary_insert();
if($query) {
$this->load->view('sales/new_blank_order_summary');
} else {
$this->load->view('sales/data_insertion_failed');
}
}
and in your Model
function order_summary_insert() {
$orderLines = trim(xss_clean($this->input->post('orderlines')));
$customerName = trim(xss_clean($this->input->post('customer')));
$data = array(
'OrderLines'=>$orderLines,
'CustomerName'=>$customerName
);
$this->db->insert('Customer_Orders',$data);
return ($this->db->affected_rows() != 1) ? false : true;
}
How to insert special characters into a database?
htmlspecialchars function is the best solution fellows. Today I was searching for how to insert strings with special characters and the google thrown so many Stackoverflow listings.None of them provided me solution. I found it in w3schools page. Yes I could solve my problem by using this function like this:
$abc = $POST['xyz'];
$abc = htmlspecialchars($abc);
MySQL date formats - difficulty Inserting a date
When using a string-typed variable in PHP containing a date, the variable must be enclosed in single quotes:
$NEW_DATE = '1997-07-15';
$sql = "INSERT INTO tbl (NEW_DATE, ...) VALUES ('$NEW_DATE', ...)";
Insert node at a certain position in a linked list C++
Just have something like this where you traverse till the given position and then insert:
void addNodeAtPos(int data, int pos)
{
Node* prev = new Node();
Node* curr = new Node();
Node* newNode = new Node();
newNode->data = data;
int tempPos = 0; // Traverses through the list
curr = head; // Initialize current to head;
if(head != NULL)
{
while(curr->next != NULL && tempPos != pos)
{
prev = curr;
curr = curr->next;
tempPos++;
}
if(pos==0)
{
cout << "Adding at Head! " << endl;
// Call function to addNode from head;
}
else if(curr->next == NULL && pos == tempPos+1)
{
cout << "Adding at Tail! " << endl;
// Call function to addNode at tail;
}
else if(pos > tempPos+1)
cout << " Position is out of bounds " << endl;
//Position not valid
else
{
prev->next = newNode;
newNode->next = curr;
cout << "Node added at position: " << pos << endl;
}
}
else
{
head = newNode;
newNode->next=NULL;
cout << "Added at head as list is empty! " << endl;
}
}
PostgreSQL: insert from another table
Just supply literal values in the SELECT:
INSERT INTO TABLE1 (id, col_1, col_2, col_3)
SELECT id, 'data1', 'data2', 'data3'
FROM TABLE2
WHERE col_a = 'something';
A select list can contain any value expression:
But the expressions in the select list do not have to reference any columns in the table expression of the FROM clause; they can be constant arithmetic expressions, for instance.
And a string literal is certainly a value expression.
Copy data from one existing row to another existing row in SQL?
Maybe I read the problem wrong, but I believe you already have inserted the course 11 records and simply need to update those that meet the criteria you listed with course 6's data.
If this is the case, you'll want to use an UPDATE
...FROM
statement:
UPDATE MyTable
SET
complete = 1,
complete_date = newdata.complete_date,
post_score = newdata.post_score
FROM
(
SELECT
userID,
complete_date,
post_score
FROM MyTable
WHERE
courseID = 6
AND complete = 1
AND complete_date > '8/1/2008'
) newdata
WHERE
CourseID = 11
AND userID = newdata.userID
See this related SO question for more info
insert data from one table to another in mysql
INSERT INTO destination_table (
Field_1,
Field_2,
Field_3)
SELECT Field_1,
Field_2,
Field_3
FROM source_table;
BUT this is a BAD MYSQL
Do this instead:
drop the destination table: DROP DESTINATION_TABLE;
CREATE TABLE DESTINATION_TABLE AS (SELECT * FROM SOURCE_TABLE);
Detect whether a Python string is a number or a letter
For a string of length 1 you can simply perform isdigit()
or isalpha()
If your string length is greater than 1, you can make a function something like..
def isinteger(a):
try:
int(a)
return True
except ValueError:
return False
Correct way to write line to file?
One can also use the io
module as in:
import io
my_string = "hi there"
with io.open("output_file.txt", mode='w', encoding='utf-8') as f:
f.write(my_string)
Passing parameters to click() & bind() event in jquery?
An alternative for the bind() method.
Use the click() method, do something like this:
commentbtn.click({id: 10, name: "João"}, onClickCommentBtn);
function onClickCommentBtn(event)
{
alert("Id=" + event.data.id + ", Name = " + event.data.name);
}
Or, if you prefer:
commentbtn.click({id: 10, name: "João"}, function (event) {
alert("Id=" + event.data.id + ", Nome = " + event.data.name);
});
It will show an alert box with the following infos:
Id = 10, Name = João
Non-static variable cannot be referenced from a static context
The static
keyword modifies the lifecycle of a method or variable within a class. A static
method or variable is created at the time a class is loaded. A method or variable that is not declared as static
is created only when the class is instantiated as an object for example by using the new
operator.
The lifecycle of a class, in broad terms, is:
- the source code for the class is written creating a template or
pattern or stamp which can then be used to
- create an object with the
new
operator using the class to make an instance of the class as an actual object and then when done with the object
- destroy the object reclaiming the resources it is holding such as memory during garbage collection.
In order to have an initial entry point for an application, Java has adopted the convention that the Java program must have a class that contains a method with an agreed upon or special name. This special method is called main()
. Since the method must exist whether the class containing the main method has been instantiated or not, the main()
method must be declared with the static
modifier so that as soon as the class is loaded, the main()
method is available.
The result is that when you start your Java application by a command line such as java helloworld
a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in the helloworld
class that is called main(String [] args)
. this method must be static
so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at the main()
method.
So you need to create an instance of your class as an object and then you can access the methods and variables of the class that have not been declared with the static
modifier. Once your Java program has started with the main()
function you can then use any variables or methods that have the modifier of static
since they exist as part of the class being loaded.
However, those variables and methods of the class which are outside of the main()
method which do not have the static
modifier can not be used until an instance of the class has been created as an object within the main()
method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have the static
modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error.
import java.io.*;
class HelloWorld {
int myInt; // this is a class variable that is unique to each object
static int myInt2; // this is a class variable shared by all objects of this class
static void main (String [] args) {
// this is the main entry point for this Java application
System.out.println ("Hello, World\n");
myInt2 = 14; // able to access the static int
HelloWorld myWorld = new HelloWorld();
myWorld.myInt = 32; // able to access non-static through an object
}
}
CodeIgniter - How to return Json response from controller
This is not your answer and this is an alternate way to process the form submission
$('.signinform').click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'index.php/user/signin', // target element(s) to be updated with server response
dataType:'json',
success : function(response){ console.log(response); alert(response)}
});
});
Git Cherry-pick vs Merge Workflow
In my opinion cherry-picking should be reserved for rare situations where it is required, for example if you did some fix on directly on 'master' branch (trunk, main development branch) and then realized that it should be applied also to 'maint'. You should base workflow either on merge, or on rebase (or "git pull --rebase").
Please remember that cherry-picked or rebased commit is different from the point of view of Git (has different SHA-1 identifier) than the original, so it is different than the commit in remote repository. (Rebase can usually deal with this, as it checks patch id i.e. the changes, not a commit id).
Also in git you can merge many branches at once: so called octopus merge. Note that octopus merge has to succeed without conflicts. Nevertheless it might be useful.
HTH.
How to mount the android img file under linux?
In Android file system, "system.img" and "userdata.img" are VMS Alpha executable. "system.img" and "userdata.img" have the contents of /system and /data directory on root file system. They are mapped on NAND devices with yaffs2 file system. Now, yaffs2 image file can not be mounted on linux PC. If you can, maybe you got some rom that not packed in yaffs2 file system. You can check those rom file by execute the command:
file <system.img/userdata.img>
If it show "VMS Alpha executable" then you can use "unyaffs" to extract it.
Python "string_escape" vs "unicode_escape"
According to my interpretation of the implementation of unicode-escape
and the unicode repr
in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string)
and unicode_string.encode('unicode-escape')
is the inclusion of wrapping quotes and escaping whichever quote was used.
They are both driven by the same function, unicodeescape_string
. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.
JPA 2.0, Criteria API, Subqueries, In Expressions
Late resurrection.
Your query seems very similar to the one at page 259 of the book Pro JPA 2:
Mastering the Java Persistence API, which in JPQL reads:
SELECT e
FROM Employee e
WHERE e IN (SELECT emp
FROM Project p JOIN p.employees emp
WHERE p.name = :project)
Using EclipseLink + H2 database, I couldn't get neither the book's JPQL nor the respective criteria working. For this particular problem I have found that if you reference the id directly instead of letting the persistence provider figure it out everything works as expected:
SELECT e
FROM Employee e
WHERE e.id IN (SELECT emp.id
FROM Project p JOIN p.employees emp
WHERE p.name = :project)
Finally, in order to address your question, here is an equivalent strongly typed criteria query that works:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
Root<Employee> emp = c.from(Employee.class);
Subquery<Integer> sq = c.subquery(Integer.class);
Root<Project> project = sq.from(Project.class);
Join<Project, Employee> sqEmp = project.join(Project_.employees);
sq.select(sqEmp.get(Employee_.id)).where(
cb.equal(project.get(Project_.name),
cb.parameter(String.class, "project")));
c.select(emp).where(
cb.in(emp.get(Employee_.id)).value(sq));
TypedQuery<Employee> q = em.createQuery(c);
q.setParameter("project", projectName); // projectName is a String
List<Employee> employees = q.getResultList();
Get difference between 2 dates in JavaScript?
Here is a solution using moment.js:
var a = moment('7/11/2010','M/D/YYYY');
var b = moment('12/12/2010','M/D/YYYY');
var diffDays = b.diff(a, 'days');
alert(diffDays);
I used your original input values, but you didn't specify the format so I assumed the first value was July 11th. If it was intended to be November 7th, then adjust the format to D/M/YYYY
instead.
Spring Boot War deployed to Tomcat
I think you're confused by different paradigms here. First, war files and server deployment -- those things belong to Java Enterprise Edition (Java EE). These concepts have no real place in a spring-boot application, which follows a different model.
Spring-boot is responsible for creating an embedded container and running your services within it directly from standard jar files (although it can do a lot more). I think the intent of this model is to support micro-service development -- where each service has its own container and is completely self contained. You can use your code to generate Java EE apps too, but that would be silly considering that spring-boot is a lot easier (for certain types of application/service).
So, given this information you now have to decide what paradigm you're going to follow, and you need to follow that and only that.
Spring-boot is executable -- you just have to run the main method in the App class which you can do from the command line or using your favourite IDE or maven or gradle (tip: maven is the right answer). This will bring up a tomcat server (by default) and your service will be available within it. Given the configuration you posted above your service should be available at: http://localhost:7777/context/help
-- the context
is meant to be replaced with your context name, which you haven't shared.
You aren't meant to be creating a war, running tomcat, or deploying anything. None of that is necessary in spring-boot. The packaging in your pom should be jar
, not war
and the scope
of the spring-boot-starter-tomcat
should be removed -- it certainly isn't provided.
When you run your main method, the console output should tell you the context that you've registered; use that to get the URL right.
Having said all that, spring-boot has to exist in a JEE world for now (until it is widely adopted). For that reason, the spring people have documented an approach to building a war rather than an executable jar, for deployment to a servlet or JEE container. This allows a lot of the spring-boot tech to be used in environments where there are restrictions against using anything but wars (or ears). However, this is a just a response to the fact that such environments are quite common, and is not seen as a necessary, or even desirable, part of the solution.
Class has no objects member
@tieuminh2510 answer is perfect. But in newer versions of VSC you will not find thhe option to edit or paste that command in User Settings.
Now in newer version to add that code follow this steps :
Press ctr+sft+P to open the the Command Palette. Now in command palette type Preferences: Configure Language Specific Settings.
Now select Python. Here in right side paste this code
"python.linting.pylintArgs": [
"--load-plugins=pylint_django",
]
Inside the first curly braces.
Make sure that pylint-django is also installed.
Hope this will help!
Android EditText for password with android:hint
android:hint="Enter your question" or something like this must work. I am using Relative layout with EditText as
If you want to use password,say android:inputType="textPassword" for hiding characters and "textVisiblePassword" for showing what you enter as password.
Is there a way to get the git root directory in one command?
Here is a script that I've written that handles both cases: 1) repository with a workspace, 2) bare repository.
https://gist.github.com/jdsumsion/6282953
git-root
(executable file in your path):
#!/bin/bash
GIT_DIR=`git rev-parse --git-dir` &&
(
if [ `basename $GIT_DIR` = ".git" ]; then
# handle normal git repos (with a .git dir)
cd $GIT_DIR/..
else
# handle bare git repos (the repo IS a xxx.git dir)
cd $GIT_DIR
fi
pwd
)
Hopefully this is helpful.
Laravel: getting a a single value from a MySQL query
Edit:
Sorry i forgot about pluck()
as many have commented :
Easiest way is :
return DB::table('users')->where('username', $username)->pluck('groupName');
Which will directly return the only the first result for the requested row as a string.
Using the fluent query builder you will obtain an array anyway.
I mean The Query Builder has no idea how many rows will come back from that query.
Here is what you can do to do it a bit cleaner
$result = DB::table('users')->select('groupName')->where('username', $username)->first();
The first()
tells the queryBuilder to return only one row so no array, so you can do :
return $result->groupName;
Hope it helps
Remove a specific character using awk or sed
tr
can be more concise for removing characters than sed
or awk
, especially when you want to remove different characters from a string.
Removing double quotes:
echo '"Hi"' | tr -d \"
# Produces Hi without quotes
Removing different kinds of brackets:
echo '[{Hi}]' | tr -d {}[]
# Produces Hi without brackets
-d
stands for "delete".
Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?
Please set your form action attribute as below it will solve your problem.
<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">
jQuery code:
$(document).ready(function () {
$("#addProductForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = $(this).serialize();
$.ajax({
url: 'addProduct.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
});
Pretty-print a Map in Java
String result = objectMapper.writeValueAsString(map)
- as simple as this!
Result:
{"2019-07-04T03:00":1,"2019-07-04T04:00":1,"2019-07-04T01:00":1,"2019-07-04T02:00":1,"2019-07-04T13:00":1,"2019-07-04T06:00":1 ...}
P.S. add Jackson JSON to your classpath.
How to replace DOM element in place using Javascript?
by using replaceChild():
<html>
<head>
</head>
<body>
<div>
<a id="myAnchor" href="http://www.stackoverflow.com">StackOverflow</a>
</div>
<script type="text/JavaScript">
var myAnchor = document.getElementById("myAnchor");
var mySpan = document.createElement("span");
mySpan.innerHTML = "replaced anchor!";
myAnchor.parentNode.replaceChild(mySpan, myAnchor);
</script>
</body>
</html>
how to use math.pi in java
Your diameter variable won't work because you're trying to store a String into a variable that will only accept a double. In order for it to work you will need to parse it
Ex:
diameter = Double.parseDouble(JOptionPane.showInputDialog("enter the diameter of a sphere.");
Rails find_or_create_by more than one attribute?
By passing a block to find_or_create
, you can pass additional parameters that will be added to the object if it is created new. This is useful if you are validating the presence of a field that you aren't searching by.
Assuming:
class GroupMember < ActiveRecord::Base
validates_presence_of :name
end
then
GroupMember.where(:member_id => 4, :group_id => 7).first_or_create { |gm| gm.name = "John Doe" }
will create a new GroupMember with the name "John Doe" if it doesn't find one with member_id 4
and group_id 7
How to List All Redis Databases?
Or you can just run the following command and you will see all databases of the Redis instance without firing up redis-cli
:
$ redis-cli INFO | grep ^db
db0:keys=1500,expires=2
db1:keys=200000,expires=1
db2:keys=350003,expires=1
Excel date to Unix timestamp
Windows and Mac Excel (2011):
Unix Timestamp = (Excel Timestamp - 25569) * 86400
Excel Timestamp = (Unix Timestamp / 86400) + 25569
MAC OS X (2007):
Unix Timestamp = (Excel Timestamp - 24107) * 86400
Excel Timestamp = (Unix Timestamp / 86400) + 24107
For Reference:
86400 = Seconds in a day
25569 = Days between 1970/01/01 and 1900/01/01 (min date in Windows Excel)
24107 = Days between 1970/01/01 and 1904/01/02 (min date in Mac Excel 2007)
ListView item background via custom selector
The solution by dglmtn doesn't work when you have a 9-patch drawable with padding as background. Strange things happen, I don't even want to talk about it, if you have such a problem, you know them.
Now, If you want to have a listview with different states and 9-patch drawables (it would work with any drawables and colors, I think) you have to do 2 things:
- Set the selector for the items in the list.
- Get rid of the default selector for the list.
What you should do is first set the row_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" android:drawable="@drawable/list_item_bg_pressed" />
<item android:state_enabled="true"
android:state_focused="true" android:drawable="@drawable/list_item_bg_focused" />
<item android:state_enabled="true"
android:state_selected="true" android:drawable="@drawable/list_item_bg_focused" />
<item
android:drawable="@drawable/list_item_bg_normal" />
</selector>
Don't forget the android:state_selected
. It works like android:state_focused
for the list, but it's applied for the list item.
Now apply the selector to the items (row.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@drawable/row_selector"
>
...
</RelativeLayout>
Make a transparent selector for the list:
<ListView
android:id="@+id/android:list"
...
android:listSelector="@android:color/transparent"
/>
This should do the thing.
Error handling with try and catch in Laravel
You are inside a namespace
so you should use \Exception
to specify the global namespace:
try {
$this->buildXMLHeader();
} catch (\Exception $e) {
return $e->getMessage();
}
In your code you've used catch (Exception $e)
so Exception
is being searched in/as:
App\Services\PayUService\Exception
Since there is no Exception
class inside App\Services\PayUService
so it's not being triggered. Alternatively, you can use a use
statement at the top of your class like use Exception;
and then you can use catch (Exception $e)
.
CUDA incompatible with my gcc version
I had to install the older versions of gcc, g++.
sudo apt-get install gcc-4.4
sudo apt-get install g++-4.4
Check that gcc-4.4 is in /usr/bin/, and same for g++
Then I could use the solution above:
sudo ln -s /usr/bin/gcc-4.4 /opt/cuda/bin/gcc
sudo ln -s /usr/bin/g++-4.4 /opt/cuda/bin/g++
How to write an async method with out parameter?
One nice feature of out
parameters is that they can be used to return data even when a function throws an exception. I think the closest equivalent to doing this with an async
method would be using a new object to hold the data that both the async
method and caller can refer to. Another way would be to pass a delegate as suggested in another answer.
Note that neither of these techniques will have any of the sort of enforcement from the compiler that out
has. I.e., the compiler won’t require you to set the value on the shared object or call a passed in delegate.
Here’s an example implementation using a shared object to imitate ref
and out
for use with async
methods and other various scenarios where ref
and out
aren’t available:
class Ref<T>
{
// Field rather than a property to support passing to functions
// accepting `ref T` or `out T`.
public T Value;
}
async Task OperationExampleAsync(Ref<int> successfulLoopsRef)
{
var things = new[] { 0, 1, 2, };
var i = 0;
while (true)
{
// Fourth iteration will throw an exception, but we will still have
// communicated data back to the caller via successfulLoopsRef.
things[i] += i;
successfulLoopsRef.Value++;
i++;
}
}
async Task UsageExample()
{
var successCounterRef = new Ref<int>();
// Note that it does not make sense to access successCounterRef
// until OperationExampleAsync completes (either fails or succeeds)
// because there’s no synchronization. Here, I think of passing
// the variable as “temporarily giving ownership” of the referenced
// object to OperationExampleAsync. Deciding on conventions is up to
// you and belongs in documentation ^^.
try
{
await OperationExampleAsync(successCounterRef);
}
finally
{
Console.WriteLine($"Had {successCounterRef.Value} successful loops.");
}
}
Make a link open a new window (not tab)
That will open a new window, not tab (with JavaScript, but quite laconically):
<a href="print.html"
onclick="window.open('print.html',
'newwindow',
'width=300,height=250');
return false;"
>Print</a>
Create XML in Javascript
Only works in IE
$(function(){
var xml = '<?xml version="1.0"?><foo><bar>bar</bar></foo>';
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(xml);
alert(xmlDoc.xml);
});
Then push xmlDoc.xml to your java code.
addEventListener in Internet Explorer
Here's something for those who like beautiful code.
function addEventListener(obj,evt,func){
if ('addEventListener' in window){
obj.addEventListener(evt,func, false);
} else if ('attachEvent' in window){//IE
obj.attachEvent('on'+evt,func);
}
}
Shamelessly stolen from Iframe-Resizer.
Python strptime() and timezones?
I recommend using python-dateutil. Its parser has been able to parse every date format I've thrown at it so far.
>>> from dateutil import parser
>>> parser.parse("Tue Jun 22 07:46:22 EST 2010")
datetime.datetime(2010, 6, 22, 7, 46, 22, tzinfo=tzlocal())
>>> parser.parse("Fri, 11 Nov 2011 03:18:09 -0400")
datetime.datetime(2011, 11, 11, 3, 18, 9, tzinfo=tzoffset(None, -14400))
>>> parser.parse("Sun")
datetime.datetime(2011, 12, 18, 0, 0)
>>> parser.parse("10-11-08")
datetime.datetime(2008, 10, 11, 0, 0)
and so on. No dealing with strptime()
format nonsense... just throw a date at it and it Does The Right Thing.
Update: Oops. I missed in your original question that you mentioned that you used dateutil
, sorry about that. But I hope this answer is still useful to other people who stumble across this question when they have date parsing questions and see the utility of that module.
const vs constexpr on variables
No difference here, but it matters when you have a type that has a constructor.
struct S {
constexpr S(int);
};
const S s0(0);
constexpr S s1(1);
s0
is a constant, but it does not promise to be initialized at compile-time. s1
is marked constexpr
, so it is a constant and, because S
's constructor is also marked constexpr
, it will be initialized at compile-time.
Mostly this matters when initialization at runtime would be time-consuming and you want to push that work off onto the compiler, where it's also time-consuming, but doesn't slow down execution time of the compiled program
How to use the DropDownList's SelectedIndexChanged event
The most basic way you can do this in SelectedIndexChanged events of DropDownLists. Check this code..
<asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="224px"
AutoPostBack="True" AppendDataBoundItems="true">
<asp:DropDownList ID="DropDownList2" runat="server"
onselectedindexchanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList2
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList3
}
CSS: Creating textured backgrounds
You should try slicing the image if possible into a smaller piece which could be repeated. I have sliced that image to a 101x101px image.
CSS:
body{
background-image: url(SO_texture_bg.jpg);
background-repeat:repeat;
}
But in some cases, we wouldn't be able to slice the image to a smaller one. In that case, I would use the whole image. But you could also use the CSS3 methods like what Mustafa Kamal had mentioned.
Wish you good luck.
HTML 5 Geo Location Prompt in Chrome
if you're hosting behind a server, and still facing issues:
try changing localhost to 127.0.0.1 e.g. http://localhost:8080/ to http://127.0.0.1:8080/
The issue I was facing was that I was serving a site using apache tomcat within an eclipse IDE (eclipse luna).
For my sanity check I was using Remy Sharp's demo:
https://github.com/remy/html5demos/blob/eae156ca2e35efbc648c381222fac20d821df494/demos/geo.html
and was getting the error after making minor tweaks to the error function despite hosting the code on the server (was only working on firefox and failing on chrome and safari):
"User denied Geolocation"
I made the following change to get more detailed error message:
function error(msg) {
var s = document.querySelector('#status');
msg = msg.message ? msg.message : msg; //add this line
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
// console.log(arguments);
}
failing on internet explorer behind virtualbox IE10 on http://10.0.2.2:8080 :
"The current location cannot be determined"
PostgreSQL CASE ... END with multiple conditions
This kind of code perhaps should work for You
SELECT
*,
CASE
WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
ELSE '00'
END AS modifiedpvc
FROM my_table;
gid | datepose | pvc | modifiedpvc
-----+----------+-----+-------------
1 | 1961 | 01 | 00
2 | 1949 | | 01
3 | 1990 | 02 | 00
1 | 1981 | | 02
1 | | 03 | 00
1 | | | 03
(6 rows)
jQuery get selected option value (not the text, but the attribute 'value')
04/2020: Corrected old answer
Use :selected pseudo selector on the selected options and then use the .val function to get the value of the option.
$('select[name=selector] option').filter(':selected').val()
Side note: Using filter is better then using :selected
selector directly in the first query.
If inside a change handler, you could use simply this.value
to get the selected option value. See demo for more options.
_x000D_
_x000D_
//ways to retrieve selected option and text outside handler
console.log('Selected option value ' + $('select option').filter(':selected').val());
console.log('Selected option value ' + $('select option').filter(':selected').text());
$('select').on('change', function () {
//ways to retrieve selected option and text outside handler
console.log('Changed option value ' + this.value);
console.log('Changed option text ' + $(this).find('option').filter(':selected').text());
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<select>
<option value="1" selected>1 - Text</option>
<option value="2">2 - Text</option>
<option value="3">3 - Text</option>
<option value="4">4 - Text</option>
</select>
_x000D_
_x000D_
_x000D_
Old answer:
Edit: As many pointed out, this does not returns the selected option value.
~~Use .val to get the value of the selected option. See below,
$('select[name=selector]').val()~~
Use of contains in Java ArrayList<String>
ArrayList<String> newlyAddedTypes=new ArrayList<String>();
.....
newlyAddedTypes.add("test1");
newlyAddedTypes.add("test1");
newlyAddedTypes.add("test2");
if(newlyAddedTypes.contain("test"){
//called here
}
else{
}
How to iterate through SparseArray?
Seems I found the solution. I hadn't properly noticed the keyAt(index)
function.
So I'll go with something like this:
for(int i = 0; i < sparseArray.size(); i++) {
int key = sparseArray.keyAt(i);
// get the object by the key.
Object obj = sparseArray.get(key);
}
Two column div layout with fluid left and fixed right column
The following examples are source ordered i.e. column 1 appears before column 2 in the HTML source. Whether a column appears on left or right is controlled by CSS:
Fixed Right
_x000D_
_x000D_
#wrapper {_x000D_
margin-right: 200px;_x000D_
}_x000D_
#content {_x000D_
float: left;_x000D_
width: 100%;_x000D_
background-color: #CCF;_x000D_
}_x000D_
#sidebar {_x000D_
float: right;_x000D_
width: 200px;_x000D_
margin-right: -200px;_x000D_
background-color: #FFA;_x000D_
}_x000D_
#cleared {_x000D_
clear: both;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="content">Column 1 (fluid)</div>_x000D_
<div id="sidebar">Column 2 (fixed)</div>_x000D_
<div id="cleared"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Fixed Left
_x000D_
_x000D_
#wrapper {_x000D_
margin-left: 200px;_x000D_
}_x000D_
#content {_x000D_
float: right;_x000D_
width: 100%;_x000D_
background-color: #CCF;_x000D_
}_x000D_
#sidebar {_x000D_
float: left;_x000D_
width: 200px;_x000D_
margin-left: -200px;_x000D_
background-color: #FFA;_x000D_
}_x000D_
#cleared {_x000D_
clear: both;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="content">Column 1 (fluid)</div>_x000D_
<div id="sidebar">Column 2 (fixed)</div>_x000D_
<div id="cleared"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Alternate solution is to use display: table-cell; which results in equal height columns.
How do I remove all null and empty string values from an object?
Here is the optimized code snippet to remove empty arrays/objects as well:
function removeNullsInObject(obj) {
if( typeof obj === 'string' ){ return; }
$.each(obj, function(key, value){
if (value === "" || value === null){
delete obj[key];
} else if ($.isArray(value)) {
if( value.length === 0 ){ delete obj[key]; return; }
$.each(value, function (k,v) {
removeNullsInObject(v);
});
} else if (typeof value === 'object') {
if( Object.keys(value).length === 0 ){
delete obj[key]; return;
}
removeNullsInObject(value);
}
});
}
Thanks @Alexis king :)
HTML form submit to PHP script
<form method="POST" action="chk_kw.php">
<select name="website_string">
<option selected="selected"></option>
<option value="abc">abc</option>
<option value="def">def</option>
<option value="hij">hij</option>
</select>
<input type="submit">
</form>
python pip on Windows - command 'cl.exe' failed
You need to have cl.exe
(the Microsoft C Compiler) installed on your computer and in your PATH
. PATH
is an environment variable that tells Windows where to find executable files.
First, ensure the C++ build tools for Visual Studio are installed. You can download Build Tools for Visual Studio separately from the Visual Studio downloads page, then choose C++ build tools from the installer. If you already have Visual Studio, you can also install Desktop development with C++ from the Visual Studio Installer which you should have in Start Menu.
Then, instead of the normal Command Prompt or PowerShell, use one of the special command prompts in the Visual Studio folder in Start Menu. For 32-bit Python, you're probably looking for x86 Native Tools Command Prompt. This sets up PATH
automatically, so that cl.exe
can be found.
How to get a file directory path from file path?
On a related note, if you only have the filename or relative path, dirname
on its own won't help. For me, the answer ended up being readlink
.
fname='txtfile'
echo $(dirname "$fname") # output: .
echo $(readlink -f "$fname") # output: /home/me/work/txtfile
You can then combine the two to get just the directory.
echo $(dirname $(readlink -f "$fname")) # output: /home/me/work
Convert JSON String to Pretty Print JSON output using Jackson
You can achieve this using bellow ways:
1. Using Jackson from Apache
String formattedData=new ObjectMapper().writerWithDefaultPrettyPrinter()
.writeValueAsString(YOUR_JSON_OBJECT);
Import bellow class:
import com.fasterxml.jackson.databind.ObjectMapper;
It's gradle dependency is :
compile 'com.fasterxml.jackson.core:jackson-core:2.7.3'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.3'
compile 'com.fasterxml.jackson.core:jackson-databind:2.7.3'
2. Using Gson from Google
String formattedData=new GsonBuilder().setPrettyPrinting()
.create().toJson(YOUR_OBJECT);
Import bellow class:
import com.google.gson.Gson;
It's gradle is:
compile 'com.google.code.gson:gson:2.8.2'
Here, you can also download correct updated version from repository.
What do pty and tty mean?
A tty
is a physical terminal-teletype port on a computer (usually a serial port).
The word teletype is a shorting of the telegraph typewriter, or teletypewriter device from the 1930s - itself an electromagnetic device which replaced the telegraph encoding machines of the 1830s and 1840s.
TTY - Teletypewriter 1930s
A pty
is a pseudo-teletype port provided by a computer Operating System Kernel to connect software programs emulating terminals, such as ssh, xterm, or screen.
PTY - PseudoTeletype
A terminal is simply a computer's user interface that uses text for input and output.
OS Implementations
These use pseudo-teletype ports however, their naming and implementations have diverged a little.
Linux mounts a special file system devpts on /dev (the 's' presumably standing for serial) that creates a corresponding entry in /dev/pts
for every new terminal window you open, e.g. /dev/pts/0
macOS/FreeBSD also use the /dev file structure however, they use a numbered TTY
naming convention ttys
for every new terminal window you open e.g. /dev/ttys002
Microsoft Windows still has the concept of an LPT
port for Line Printer Terminals within it's Command Shell for output to a printer.
Android toolbar center title and custom font
You can have a custom TextView
in the toolbar like this:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="@color/action_bar_bkgnd"
app:theme="@style/ToolBarTheme" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:layout_gravity="center"
android:id="@+id/toolbar_title" />
</android.support.v7.widget.Toolbar>
So, this will center the text. If you want to add custom font to a normal Toolbar
, make a <style>
:
<style android:name="ToolbarFont">
<item android:fontFamily = "@font/fontName" />
</style>
And add it to the toolbar:
toolbar.setTitleTextAppearance(this, R.style.ToolbarFont);
For the textview in the toolbar, you can define it with the fontFamily
attribute:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="@color/action_bar_bkgnd"
app:theme="@style/ToolBarTheme" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:layout_gravity="center"
android:id="@+id/toolbar_title"
android:fontFamily="@font/fontFamily" />
</android.support.v7.widget.Toolbar>
SET NOCOUNT ON usage
Ok now I've done my research, here is the deal:
In TDS protocol, SET NOCOUNT ON
only saves 9-bytes per query while the text "SET NOCOUNT ON" itself is a whopping 14 bytes. I used to think that 123 row(s) affected
was returned from server in plain text in a separate network packet but that's not the case. It's in fact a small structure called DONE_IN_PROC
embedded in the response. It's not a separate network packet so no roundtrips are wasted.
I think you can stick to default counting behavior almost always without worrying about the performance. There are some cases though, where calculating the number of rows beforehand would impact the performance, such as a forward-only cursor. In that case NOCOUNT might be a necessity. Other than that, there is absolutely no need to follow "use NOCOUNT wherever possible" motto.
Here is a very detailed analysis about insignificance of SET NOCOUNT
setting: http://daleburnett.com/2014/01/everything-ever-wanted-know-set-nocount/
MySQL Query - Records between Today and Last 30 Days
For the current date activity and complete activity for previous 30 days use this, since the SYSDATE is variable in a day the previous 30th day will not have the whole data for that day.
SELECT DATE_FORMAT(create_date, '%m/%d/%Y')
FROM mytable
WHERE create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND SYSDATE()
embedding image in html email
If you are using Outlook to send a static image with hyperlink, an easy way would be to use Word.
- Open MS Word
- Copy the image onto a blank page
- Add hyperlink to the image (Ctrl + K)
- Copy the image to your email
nginx - client_max_body_size has no effect
Had the same issue that the client_max_body_size
directive was ignored.
My silly error was, that I put a file inside /etc/nginx/conf.d
which did not end with .conf
. Nginx will not load these by default.
How to dynamically create CSS class in JavaScript and apply?
Found a better solution, which works across all browsers.
Uses document.styleSheet to add or replace rules. Accepted answer is short and handy but this works across IE8 and less too.
function createCSSSelector (selector, style) {
if (!document.styleSheets) return;
if (document.getElementsByTagName('head').length == 0) return;
var styleSheet,mediaType;
if (document.styleSheets.length > 0) {
for (var i = 0, l = document.styleSheets.length; i < l; i++) {
if (document.styleSheets[i].disabled)
continue;
var media = document.styleSheets[i].media;
mediaType = typeof media;
if (mediaType === 'string') {
if (media === '' || (media.indexOf('screen') !== -1)) {
styleSheet = document.styleSheets[i];
}
}
else if (mediaType=='object') {
if (media.mediaText === '' || (media.mediaText.indexOf('screen') !== -1)) {
styleSheet = document.styleSheets[i];
}
}
if (typeof styleSheet !== 'undefined')
break;
}
}
if (typeof styleSheet === 'undefined') {
var styleSheetElement = document.createElement('style');
styleSheetElement.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(styleSheetElement);
for (i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].disabled) {
continue;
}
styleSheet = document.styleSheets[i];
}
mediaType = typeof styleSheet.media;
}
if (mediaType === 'string') {
for (var i = 0, l = styleSheet.rules.length; i < l; i++) {
if(styleSheet.rules[i].selectorText && styleSheet.rules[i].selectorText.toLowerCase()==selector.toLowerCase()) {
styleSheet.rules[i].style.cssText = style;
return;
}
}
styleSheet.addRule(selector,style);
}
else if (mediaType === 'object') {
var styleSheetLength = (styleSheet.cssRules) ? styleSheet.cssRules.length : 0;
for (var i = 0; i < styleSheetLength; i++) {
if (styleSheet.cssRules[i].selectorText && styleSheet.cssRules[i].selectorText.toLowerCase() == selector.toLowerCase()) {
styleSheet.cssRules[i].style.cssText = style;
return;
}
}
styleSheet.insertRule(selector + '{' + style + '}', styleSheetLength);
}
}
Function is used as follows.
createCSSSelector('.mycssclass', 'display:none');
How do I change the owner of a SQL Server database?
to change the object owner try the following
EXEC sp_changedbowner 'sa'
that however is not your problem, to see diagrams the Da Vinci Tools objects have to be created (you will see tables and procs that start with dt_) after that
Jenkins CI: How to trigger builds on SVN commit
You can use a post-commit hook.
Put the post-commit hook script in the hooks
folder, create a wget_folder
in your C:\ drive, and put the wget.exe
file in this folder.
Add the following code in the file called post-commit.bat
SET REPOS=%1
SET REV=%2
FOR /f "tokens=*" %%a IN (
'svnlook uuid %REPOS%'
) DO (
SET UUID=%%a
)
FOR /f "tokens=*" %%b IN (
'svnlook changed --revision %REV% %REPOS%'
) DO (
SET POST=%%b
)
echo %REPOS% ----- 1>&2
echo %REV% -- 1>&2
echo %UUID% --1>&2
echo %POST% --1>&2
C:\wget_folder\wget ^
--header="Content-Type:text/plain" ^
--post-data="%POST%" ^
--output-document="-" ^
--timeout=2 ^
http://localhost:9090/job/Test/build/%UUID%/notifyCommit?rev=%REV%
where Test = name of the job
echo
is used to see the value and you can also add exit 2
at the end to know about the issue and whether the post-commit hook script is running or not.
Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'
Unfortunately, no approached mentioned here worked for me. I have to register couple PFX in a docker container and I need to pass the password via command line.
So I re-developed the
sn.exe -i <infile> <container>
command in C# using the RSACryptoServiceProvider. The source and the app are on GitHub in
the SnInstallPfx project.
The SnInstallPfx app accepts a PFX key and its password. It computes the key container name (VS_KEY_*) automatically (borrowed from MSBuild source code) and installs it to the strong name CSP.
Usage:
SnInstallPfx.exe <pfx_infile> <pfx_password>
// or pass a container name if the default is not what you need (e.g. C++)
SnInstallPfx.exe <pfx_infile> <pfx_password> <container_name>
Simplest way to serve static data from outside the application server in a Java web application
Requirement : Accessing the static Resources (images/videos., etc.,) from outside of WEBROOT directory or from local disk
Step 1 :
Create a folder under webapps of tomcat server., let us say the folder name is myproj
Step 2 :
Under myproj create a WEB-INF folder under this create a simple web.xml
code under web.xml
<web-app>
</web-app>
Directory Structure for the above two steps
c:\programfile\apachesoftwarefoundation\tomcat\...\webapps
|
|---myproj
| |
| |---WEB-INF
| |
|---web.xml
Step 3:
Now create a xml file with name myproj.xml under the following location
c:\programfile\apachesoftwarefoundation\tomcat\conf\catalina\localhost
CODE in myproj.xml:
<Context path="/myproj/images" docBase="e:/myproj/" crossContext="false" debug="0" reloadable="true" privileged="true" />
Step 4:
4 A) Now create a folder with name myproj in E drive of your hard disk and create a new
folder with name images and place some images in images folder (e:myproj\images\)
Let us suppose myfoto.jpg is placed under e:\myproj\images\myfoto.jpg
4 B) Now create a folder with name WEB-INF in e:\myproj\WEB-INF
and create a web.xml in WEB-INF folder
Code in web.xml
<web-app>
</web-app>
Step 5:
Now create a .html document with name index.html and place under e:\myproj
CODE under index.html
Welcome to Myproj
The Directory Structure for the above Step 4 and Step 5 is as follows
E:\myproj
|--index.html
|
|--images
| |----myfoto.jpg
|
|--WEB-INF
| |--web.xml
Step 6:
Now start the apache tomcat server
Step 7:
open the browser and type the url as follows
http://localhost:8080/myproj
then u display the content which is provided in index.html
Step 8:
To Access the Images under your local hard disk (outside of webroot)
http://localhost:8080/myproj/images/myfoto.jpg
Using SVG as background image
With my solution you're able to get something similar:
Here is bulletproff solution:
Your html:
<input class='calendarIcon'/>
Your SVG:
i used fa-calendar-alt
(any IDE may open svg image as shown below)
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M148 288h-40c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm108-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 96v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96-260v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V112c0-26.5 21.5-48 48-48h48V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h128V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h48c26.5 0 48 21.5 48 48zm-48 346V160H48v298c0 3.3 2.7 6 6 6h340c3.3 0 6-2.7 6-6z"/></svg>
To use it at css background-image you gotta encode the svg to address valid string. I used this tool
As far as you got all stuff you need, you're coming to css
.calendarIcon{
//your url will be something like this:
background-image: url("data:image/svg+xml,***<here place encoded svg>***");
background-repeat: no-repeat;
}
Note: these styling wont have any effect on encoded svg image
.{
fill: #f00; //neither this
background-color: #f00; //nor this
}
because all changes over the image must be applied directly to its svg code
<svg xmlns="" path="" fill="#f00"/></svg>
To achive the location righthand i copied some Bootstrap spacing and my final css get the next look:
.calendarIcon{
background-image: url("data:image/svg+xml,%3Csvg...svg%3E");
background-repeat: no-repeat;
padding-right: calc(1.5em + 0.75rem);
background-position: center right calc(0.375em + 0.1875rem);
background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}
Are these methods thread safe?
The only problem with threads is accessing the same object from different threads without synchronization.
If each function only uses parameters for reading and local variables, they don't need any synchronization to be thread-safe.
How to use a jQuery plugin inside Vue
I use it like this:
import jQuery from 'jQuery'
ready: function() {
var self = this;
jQuery(window).resize(function () {
self.$refs.thisherechart.drawChart();
})
},
Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"
The same problem when I export the library httclient-4.3.5 in Android Studio 0.8.6
I need include this:
packagingOptions{
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
}
The library zip content the next jar:
commons-codec-1.6.jar
commons-logging-1.1.3.jar
fluent-hc-4.3.5.jar
httpclient-4.3.5.jar
httpclient-cache-4.3.5.jar
httpcore-4.3.2.jar
httpmime-4.3.5.jar
Are there benefits of passing by pointer over passing by reference in C++?
Allen Holub's "Enough Rope to Shoot Yourself in the Foot" lists the following 2 rules:
120. Reference arguments should always be `const`
121. Never use references as outputs, use pointers
He lists several reasons why references were added to C++:
- they are necessary to define copy constructors
- they are necessary for operator overloads
const
references allow you to have pass-by-value semantics while avoiding a copy
His main point is that references should not be used as 'output' parameters because at the call site there's no indication of whether the parameter is a reference or a value parameter. So his rule is to only use const
references as arguments.
Personally, I think this is a good rule of thumb as it makes it more clear when a parameter is an output parameter or not. However, while I personally agree with this in general, I do allow myself to be swayed by the opinions of others on my team if they argue for output parameters as references (some developers like them immensely).
MySQL INNER JOIN select only one row from second table
@John Woo's answer helped me solve a similar problem. I've improved upon his answer by setting the correct ordering as well. This has worked for me:
SELECT a.*, c.*
FROM users a
INNER JOIN payments c
ON a.id = c.user_ID
INNER JOIN (
SELECT user_ID, MAX(date) as maxDate FROM
(
SELECT user_ID, date
FROM payments
ORDER BY date DESC
) d
GROUP BY user_ID
) b ON c.user_ID = b.user_ID AND
c.date = b.maxDate
WHERE a.package = 1
I'm not sure how efficient this is, though.
"The semaphore timeout period has expired" error for USB connection
Okay, I am now connecting without the semaphore timeout problem.
If anyone reading ever encounters the same thing, I hope that this procedure works for you; but no promises; hey, it's windows.
In my case this was Windows 7
I got a little hint from This page on eHow; not sure if that might help anyone or not.
So anyway, this was the simple twenty three step procedure that worked for me
Click on start button
Choose Control Panel
From Control Panel, choose Device Manger
From Device Manager, choose Universal Serial Bus Controllers
From Universal Serial Bus Controllers, click the little sideways triangle
I cannot predict what you'll see on your computer, but on mine I get a long drop-down list
Begin the investigation to figure out which one of these members of this list is the culprit...
On each member of the drop-down list, right-click on the name
A list will open, choose Properties
Guesswork time: using the various tabs near the top of the resulting window which opens, make a guess if this is the USB adapter driver which is choking your stuff with semaphore timeouts
Once you have made the proper guess, then close the USB Root Hub Properties window (but leave the Device Manager window open).
Physically disonnect anything and everything from that USB hub.
Unplug it.
Return your mouse pointer to that USB Root Hub in the list which you identified earlier.
Right click again
Choose Uninstall
Let Windows do its thing
Wait a little while
Power Down the whole computer if you have the time; some say this is required. I think I got away without it.
Plug the USB hub back into a USB connector on the PC
If the list in the device manager blinks and does a few flash-bulbs, it's okay.
Plug the BlueTooth connector back into the USB hub
Let windows do its thing some more
Within two minutes, I had a working COM port again, no semaphore timeouts.
Hope it works for anyone else who may be having a similar problem.
Auto margins don't center image in page
Under some circumstances (such as earlier versions of IE, Gecko, Webkit) and inheritance, elements with position:relative;
will prevent margin:0 auto;
from working, even if top
, right
, bottom
, and left
aren't set.
Setting the element to position:static;
(the default) may fix it under these circumstances. Generally, block level elements with a specified width will respect margin:0 auto;
using either relative
or static
positioning.
How can get the text of a div tag using only javascript (no jQuery)
You can use innerHTML
(then parse text from HTML) or use innerText
.
let textContentWithHTMLTags = document.querySelector('div').innerHTML;
let textContent = document.querySelector('div').innerText;
console.log(textContentWithHTMLTags, textContent);
innerHTML
and innerText
is supported by all browser(except FireFox < 44) including IE6.
Java Read Large Text File With 70million line of text
I actually did a research in this topic for months in my free time and came up with a benchmark and here is a code to benchmark all the different ways to read a File line by line.The individual performance may vary based on the underlying system.
I ran on a windows 10 Java 8 Intel i5 HP laptop:Here is the code.
import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class ReadComplexDelimitedFile {
private static long total = 0;
private static final Pattern FIELD_DELIMITER_PATTERN = Pattern.compile("\\^\\|\\^");
@SuppressWarnings("unused")
private void readFileUsingScanner() {
String s;
try (Scanner stdin = new Scanner(new File(this.getClass().getResource("input.txt").getPath()))) {
while (stdin.hasNextLine()) {
s = stdin.nextLine();
String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
total = total + fields.length;
}
} catch (Exception e) {
System.err.println("Error");
}
}
//Winner
private void readFileUsingCustomBufferedReader() {
try (CustomBufferedReader stdin = new CustomBufferedReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
String s;
while ((s = stdin.readLine()) != null) {
String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
total += fields.length;
}
} catch (Exception e) {
System.err.println("Error");
}
}
private void readFileUsingBufferedReader() {
try (BufferedReader stdin = new BufferedReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
String s;
while ((s = stdin.readLine()) != null) {
String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
total += fields.length;
}
} catch (Exception e) {
System.err.println("Error");
}
}
private void readFileUsingLineReader() {
try (LineNumberReader stdin = new LineNumberReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
String s;
while ((s = stdin.readLine()) != null) {
String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
total += fields.length;
}
} catch (Exception e) {
System.err.println("Error");
}
}
private void readFileUsingStreams() {
try (Stream<String> stream = Files.lines((new File(this.getClass().getResource("input.txt").getPath())).toPath())) {
total += stream.mapToInt(s -> FIELD_DELIMITER_PATTERN.split(s, 0).length).sum();
} catch (IOException e1) {
e1.printStackTrace();
}
}
private void readFileUsingBufferedReaderFileChannel() {
try (FileInputStream fis = new FileInputStream(this.getClass().getResource("input.txt").getPath())) {
try (FileChannel inputChannel = fis.getChannel()) {
try (CustomBufferedReader stdin = new CustomBufferedReader(Channels.newReader(inputChannel, "UTF-8"))) {
String s;
while ((s = stdin.readLine()) != null) {
String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
total = total + fields.length;
}
}
} catch (Exception e) {
System.err.println("Error");
}
} catch (Exception e) {
System.err.println("Error");
}
}
public static void main(String args[]) {
//JVM wamrup
for (int i = 0; i < 100000; i++) {
total += i;
}
// We know scanner is slow-Still warming up
ReadComplexDelimitedFile readComplexDelimitedFile = new ReadComplexDelimitedFile();
List<Long> longList = new ArrayList<>(50);
for (int i = 0; i < 50; i++) {
total = 0;
long startTime = System.nanoTime();
//readComplexDelimitedFile.readFileUsingScanner();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingScanner");
longList.forEach(System.out::println);
// Actual performance test starts here
longList = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
total = 0;
long startTime = System.nanoTime();
readComplexDelimitedFile.readFileUsingBufferedReaderFileChannel();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingBufferedReaderFileChannel");
longList.forEach(System.out::println);
longList.clear();
for (int i = 0; i < 10; i++) {
total = 0;
long startTime = System.nanoTime();
readComplexDelimitedFile.readFileUsingBufferedReader();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingBufferedReader");
longList.forEach(System.out::println);
longList.clear();
for (int i = 0; i < 10; i++) {
total = 0;
long startTime = System.nanoTime();
readComplexDelimitedFile.readFileUsingStreams();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingStreams");
longList.forEach(System.out::println);
longList.clear();
for (int i = 0; i < 10; i++) {
total = 0;
long startTime = System.nanoTime();
readComplexDelimitedFile.readFileUsingCustomBufferedReader();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingCustomBufferedReader");
longList.forEach(System.out::println);
longList.clear();
for (int i = 0; i < 10; i++) {
total = 0;
long startTime = System.nanoTime();
readComplexDelimitedFile.readFileUsingLineReader();
long stopTime = System.nanoTime();
long timeDifference = stopTime - startTime;
longList.add(timeDifference);
}
System.out.println("Time taken for readFileUsingLineReader");
longList.forEach(System.out::println);
}
}
I had to rewrite BufferedReader to avoid synchronized and a couple of boundary conditions that is not needed.(Atleast that's what I felt.It is not unit tested so use it at your own risk.)
import com.sun.istack.internal.NotNull;
import java.io.*;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* Reads text from a character-input stream, buffering characters so as to
* provide for the efficient reading of characters, arrays, and lines.
* <p>
* <p> The buffer size may be specified, or the default size may be used. The
* default is large enough for most purposes.
* <p>
* <p> In general, each read request made of a Reader causes a corresponding
* read request to be made of the underlying character or byte stream. It is
* therefore advisable to wrap a CustomBufferedReader around any Reader whose read()
* operations may be costly, such as FileReaders and InputStreamReaders. For
* example,
* <p>
* <pre>
* CustomBufferedReader in
* = new CustomBufferedReader(new FileReader("foo.in"));
* </pre>
* <p>
* will buffer the input from the specified file. Without buffering, each
* invocation of read() or readLine() could cause bytes to be read from the
* file, converted into characters, and then returned, which can be very
* inefficient.
* <p>
* <p> Programs that use DataInputStreams for textual input can be localized by
* replacing each DataInputStream with an appropriate CustomBufferedReader.
*
* @author Mark Reinhold
* @see FileReader
* @see InputStreamReader
* @see java.nio.file.Files#newBufferedReader
* @since JDK1.1
*/
public class CustomBufferedReader extends Reader {
private final Reader in;
private char cb[];
private int nChars, nextChar;
private static final int INVALIDATED = -2;
private static final int UNMARKED = -1;
private int markedChar = UNMARKED;
private int readAheadLimit = 0; /* Valid only when markedChar > 0 */
/**
* If the next character is a line feed, skip it
*/
private boolean skipLF = false;
/**
* The skipLF flag when the mark was set
*/
private boolean markedSkipLF = false;
private static int defaultCharBufferSize = 8192;
private static int defaultExpectedLineLength = 80;
private ReadWriteLock rwlock;
/**
* Creates a buffering character-input stream that uses an input buffer of
* the specified size.
*
* @param in A Reader
* @param sz Input-buffer size
* @throws IllegalArgumentException If {@code sz <= 0}
*/
public CustomBufferedReader(@NotNull final Reader in, int sz) {
super(in);
if (sz <= 0)
throw new IllegalArgumentException("Buffer size <= 0");
this.in = in;
cb = new char[sz];
nextChar = nChars = 0;
rwlock = new ReentrantReadWriteLock();
}
/**
* Creates a buffering character-input stream that uses a default-sized
* input buffer.
*
* @param in A Reader
*/
public CustomBufferedReader(@NotNull final Reader in) {
this(in, defaultCharBufferSize);
}
/**
* Fills the input buffer, taking the mark into account if it is valid.
*/
private void fill() throws IOException {
int dst;
if (markedChar <= UNMARKED) {
/* No mark */
dst = 0;
} else {
/* Marked */
int delta = nextChar - markedChar;
if (delta >= readAheadLimit) {
/* Gone past read-ahead limit: Invalidate mark */
markedChar = INVALIDATED;
readAheadLimit = 0;
dst = 0;
} else {
if (readAheadLimit <= cb.length) {
/* Shuffle in the current buffer */
System.arraycopy(cb, markedChar, cb, 0, delta);
markedChar = 0;
dst = delta;
} else {
/* Reallocate buffer to accommodate read-ahead limit */
char ncb[] = new char[readAheadLimit];
System.arraycopy(cb, markedChar, ncb, 0, delta);
cb = ncb;
markedChar = 0;
dst = delta;
}
nextChar = nChars = delta;
}
}
int n;
do {
n = in.read(cb, dst, cb.length - dst);
} while (n == 0);
if (n > 0) {
nChars = dst + n;
nextChar = dst;
}
}
/**
* Reads a single character.
*
* @return The character read, as an integer in the range
* 0 to 65535 (<tt>0x00-0xffff</tt>), or -1 if the
* end of the stream has been reached
* @throws IOException If an I/O error occurs
*/
public char readChar() throws IOException {
for (; ; ) {
if (nextChar >= nChars) {
fill();
if (nextChar >= nChars)
return (char) -1;
}
return cb[nextChar++];
}
}
/**
* Reads characters into a portion of an array, reading from the underlying
* stream if necessary.
*/
private int read1(char[] cbuf, int off, int len) throws IOException {
if (nextChar >= nChars) {
/* If the requested length is at least as large as the buffer, and
if there is no mark/reset activity, and if line feeds are not
being skipped, do not bother to copy the characters into the
local buffer. In this way buffered streams will cascade
harmlessly. */
if (len >= cb.length && markedChar <= UNMARKED && !skipLF) {
return in.read(cbuf, off, len);
}
fill();
}
if (nextChar >= nChars) return -1;
int n = Math.min(len, nChars - nextChar);
System.arraycopy(cb, nextChar, cbuf, off, n);
nextChar += n;
return n;
}
/**
* Reads characters into a portion of an array.
* <p>
* <p> This method implements the general contract of the corresponding
* <code>{@link Reader#read(char[], int, int) read}</code> method of the
* <code>{@link Reader}</code> class. As an additional convenience, it
* attempts to read as many characters as possible by repeatedly invoking
* the <code>read</code> method of the underlying stream. This iterated
* <code>read</code> continues until one of the following conditions becomes
* true: <ul>
* <p>
* <li> The specified number of characters have been read,
* <p>
* <li> The <code>read</code> method of the underlying stream returns
* <code>-1</code>, indicating end-of-file, or
* <p>
* <li> The <code>ready</code> method of the underlying stream
* returns <code>false</code>, indicating that further input requests
* would block.
* <p>
* </ul> If the first <code>read</code> on the underlying stream returns
* <code>-1</code> to indicate end-of-file then this method returns
* <code>-1</code>. Otherwise this method returns the number of characters
* actually read.
* <p>
* <p> Subclasses of this class are encouraged, but not required, to
* attempt to read as many characters as possible in the same fashion.
* <p>
* <p> Ordinarily this method takes characters from this stream's character
* buffer, filling it from the underlying stream as necessary. If,
* however, the buffer is empty, the mark is not valid, and the requested
* length is at least as large as the buffer, then this method will read
* characters directly from the underlying stream into the given array.
* Thus redundant <code>CustomBufferedReader</code>s will not copy data
* unnecessarily.
*
* @param cbuf Destination buffer
* @param off Offset at which to start storing characters
* @param len Maximum number of characters to read
* @return The number of characters read, or -1 if the end of the
* stream has been reached
* @throws IOException If an I/O error occurs
*/
public int read(char cbuf[], int off, int len) throws IOException {
int n = read1(cbuf, off, len);
if (n <= 0) return n;
while ((n < len) && in.ready()) {
int n1 = read1(cbuf, off + n, len - n);
if (n1 <= 0) break;
n += n1;
}
return n;
}
/**
* Reads a line of text. A line is considered to be terminated by any one
* of a line feed ('\n'), a carriage return ('\r'), or a carriage return
* followed immediately by a linefeed.
*
* @param ignoreLF If true, the next '\n' will be skipped
* @return A String containing the contents of the line, not including
* any line-termination characters, or null if the end of the
* stream has been reached
* @throws IOException If an I/O error occurs
* @see java.io.LineNumberReader#readLine()
*/
String readLine(boolean ignoreLF) throws IOException {
StringBuilder s = null;
int startChar;
bufferLoop:
for (; ; ) {
if (nextChar >= nChars)
fill();
if (nextChar >= nChars) { /* EOF */
if (s != null && s.length() > 0)
return s.toString();
else
return null;
}
boolean eol = false;
char c = 0;
int i;
/* Skip a leftover '\n', if necessary */
charLoop:
for (i = nextChar; i < nChars; i++) {
c = cb[i];
if ((c == '\n')) {
eol = true;
break charLoop;
}
}
startChar = nextChar;
nextChar = i;
if (eol) {
String str;
if (s == null) {
str = new String(cb, startChar, i - startChar);
} else {
s.append(cb, startChar, i - startChar);
str = s.toString();
}
nextChar++;
return str;
}
if (s == null)
s = new StringBuilder(defaultExpectedLineLength);
s.append(cb, startChar, i - startChar);
}
}
/**
* Reads a line of text. A line is considered to be terminated by any one
* of a line feed ('\n'), a carriage return ('\r'), or a carriage return
* followed immediately by a linefeed.
*
* @return A String containing the contents of the line, not including
* any line-termination characters, or null if the end of the
* stream has been reached
* @throws IOException If an I/O error occurs
* @see java.nio.file.Files#readAllLines
*/
public String readLine() throws IOException {
return readLine(false);
}
/**
* Skips characters.
*
* @param n The number of characters to skip
* @return The number of characters actually skipped
* @throws IllegalArgumentException If <code>n</code> is negative.
* @throws IOException If an I/O error occurs
*/
public long skip(long n) throws IOException {
if (n < 0L) {
throw new IllegalArgumentException("skip value is negative");
}
rwlock.readLock().lock();
long r = n;
try{
while (r > 0) {
if (nextChar >= nChars)
fill();
if (nextChar >= nChars) /* EOF */
break;
if (skipLF) {
skipLF = false;
if (cb[nextChar] == '\n') {
nextChar++;
}
}
long d = nChars - nextChar;
if (r <= d) {
nextChar += r;
r = 0;
break;
} else {
r -= d;
nextChar = nChars;
}
}
} finally {
rwlock.readLock().unlock();
}
return n - r;
}
/**
* Tells whether this stream is ready to be read. A buffered character
* stream is ready if the buffer is not empty, or if the underlying
* character stream is ready.
*
* @throws IOException If an I/O error occurs
*/
public boolean ready() throws IOException {
rwlock.readLock().lock();
try {
/*
* If newline needs to be skipped and the next char to be read
* is a newline character, then just skip it right away.
*/
if (skipLF) {
/* Note that in.ready() will return true if and only if the next
* read on the stream will not block.
*/
if (nextChar >= nChars && in.ready()) {
fill();
}
if (nextChar < nChars) {
if (cb[nextChar] == '\n')
nextChar++;
skipLF = false;
}
}
} finally {
rwlock.readLock().unlock();
}
return (nextChar < nChars) || in.ready();
}
/**
* Tells whether this stream supports the mark() operation, which it does.
*/
public boolean markSupported() {
return true;
}
/**
* Marks the present position in the stream. Subsequent calls to reset()
* will attempt to reposition the stream to this point.
*
* @param readAheadLimit Limit on the number of characters that may be
* read while still preserving the mark. An attempt
* to reset the stream after reading characters
* up to this limit or beyond may fail.
* A limit value larger than the size of the input
* buffer will cause a new buffer to be allocated
* whose size is no smaller than limit.
* Therefore large values should be used with care.
* @throws IllegalArgumentException If {@code readAheadLimit < 0}
* @throws IOException If an I/O error occurs
*/
public void mark(int readAheadLimit) throws IOException {
if (readAheadLimit < 0) {
throw new IllegalArgumentException("Read-ahead limit < 0");
}
rwlock.readLock().lock();
try {
this.readAheadLimit = readAheadLimit;
markedChar = nextChar;
markedSkipLF = skipLF;
} finally {
rwlock.readLock().unlock();
}
}
/**
* Resets the stream to the most recent mark.
*
* @throws IOException If the stream has never been marked,
* or if the mark has been invalidated
*/
public void reset() throws IOException {
rwlock.readLock().lock();
try {
if (markedChar < 0)
throw new IOException((markedChar == INVALIDATED)
? "Mark invalid"
: "Stream not marked");
nextChar = markedChar;
skipLF = markedSkipLF;
} finally {
rwlock.readLock().unlock();
}
}
public void close() throws IOException {
rwlock.readLock().lock();
try {
in.close();
} finally {
cb = null;
rwlock.readLock().unlock();
}
}
public Stream<String> lines() {
Iterator<String> iter = new Iterator<String>() {
String nextLine = null;
@Override
public boolean hasNext() {
if (nextLine != null) {
return true;
} else {
try {
nextLine = readLine();
return (nextLine != null);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@Override
public String next() {
if (nextLine != null || hasNext()) {
String line = nextLine;
nextLine = null;
return line;
} else {
throw new NoSuchElementException();
}
}
};
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
iter, Spliterator.ORDERED | Spliterator.NONNULL), false);
}
}
And now the results:
Time taken for readFileUsingBufferedReaderFileChannel
2902690903
1845190694
1894071377
1815161868
1861056735
1867693540
1857521371
1794176251
1768008762
1853089582
Time taken for readFileUsingBufferedReader
2022837353
1925901163
1802266711
1842689572
1899984555
1843101306
1998642345
1821242301
1820168806
1830375108
Time taken for readFileUsingStreams
1992855461
1930827034
1850876033
1843402533
1800378283
1863581324
1810857226
1798497108
1809531144
1796345853
Time taken for readFileUsingCustomBufferedReader
1759732702
1765987214
1776997357
1772999486
1768559162
1755248431
1744434555
1750349867
1740582606
1751390934
Time taken for readFileUsingLineReader
1845307174
1830950256
1829847321
1828125293
1827936280
1836947487
1832186310
1820276327
1830157935
1829171481
Process finished with exit code 0
Inference:
The test was run on a 200 MB file.
The test was repeated several times.
The data looked like this
Start Date^|^Start Time^|^End Date^|^End Time^|^Event Title ^|^All Day Event^|^No End Time^|^Event Description^|^Contact ^|^Contact Email^|^Contact Phone^|^Location^|^Category^|^Mandatory^|^Registration^|^Maximum^|^Last Date To Register
9/5/2011^|^3:00:00 PM^|^9/5/2011^|^^|^Social Studies Dept. Meeting^|^N^|^Y^|^Department meeting^|^Chris Gallagher^|^[email protected]^|^814-555-5179^|^High School^|^2^|^N^|^N^|^25^|^9/2/2011
Bottomline not much difference between BufferedReader and my CustomReader and it is very miniscule and hence you can use this to read your file.
Trust me you don't have to break your head.use BufferedReader with readLine,it is properly tested.At worst if you feel you can improve it just override and change it to StringBuilder instead of StringBuffer just to shave off half a second
Reloading a ViewController
If you know your database has been updated and you want to just refresh your ViewController (which was my case). I didn't find another solution but what I did was when my database updated, I called:
[self viewDidLoad];
again, and it worked. Remember if you override other viewWillAppear or loadView then call them too in same order.
like.
[self viewDidLoad];
[self viewWillAppear:YES];
I think there should be a more specific solution like refresh button in browser.
Nested ng-repeat
It's better to have a proper JSON format instead of directly using the one converted from XML.
[
{
"number": "2013-W45",
"days": [
{
"dow": "1",
"templateDay": "Monday",
"jobs": [
{
"name": "Wakeup",
"jobs": [
{
"name": "prepare breakfast",
}
]
},
{
"name": "work 9-5",
}
]
},
{
"dow": "2",
"templateDay": "Tuesday",
"jobs": [
{
"name": "Wakeup",
"jobs": [
{
"name": "prepare breakfast",
}
]
}
]
}
]
}
]
This will make things much easier and easy to loop through.
Now you can write the loop as -
<div ng-repeat="week in myData">
<div ng-repeat="day in week.days">
{{day.dow}} - {{day.templateDay}}
<b>Jobs:</b><br/>
<ul>
<li ng-repeat="job in day.jobs">
{{job.name}}
</li>
</ul>
</div>
</div>
alternative to "!is.null()" in R
To handle undefined variables as well as nulls, you can use substitute
with deparse
:
nullSafe <- function(x) {
if (!exists(deparse(substitute(x))) || is.null(x)) {
return(NA)
} else {
return(x)
}
}
nullSafe(my.nonexistent.var)
nodejs - first argument must be a string or Buffer - when using response.write with http.request
I get this error message and it mentions options.body
I had this originally
request.post({
url: apiServerBaseUrl + '/v1/verify',
body: {
email: req.user.email
}
});
I changed it to this:
request.post({
url: apiServerBaseUrl + '/v1/verify',
body: JSON.stringify({
email: req.user.email
})
});
and it seems to work now without the error message...seems like bug though.
I think this is the more official way to do it:
request.post({
url: apiServerBaseUrl + '/v1/verify',
json: true,
body: {
email: req.user.email
}
});
Error: [ng:areq] from angular controller
I ran into this issue when I had defined the module in the Angular controller but neglected to set the app name in my HTML file. For example:
<html ng-app>
instead of the correct:
<html ng-app="myApp">
when I had defined something like:
angular.module('myApp', []).controller(...
and referenced it in my HTML file.
How do I make a WinForms app go Full Screen
I recently made an Mediaplayer application and I used API-calls to make sure the taskbar was hidden when the program was running fullscreen and then restored the taskbar when the program was not in fullscreen or not had focus or was exited.
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Integer
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Integer, ByVal hWnd2 As Integer, ByVal lpsz1 As String, ByVal lpsz2 As String) As Integer
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Integer, ByVal nCmdShow As Integer) As Integer
Sub HideTrayBar()
Try
Dim tWnd As Integer = 0
Dim bWnd As Integer = 0
tWnd = FindWindow("Shell_TrayWnd", vbNullString)
bWnd = FindWindowEx(tWnd, bWnd, "BUTTON", vbNullString)
ShowWindow(tWnd, 0)
ShowWindow(bWnd, 0)
Catch ex As Exception
'Error hiding the taskbar, do what you want here..
End Try
End Sub
Sub ShowTraybar()
Try
Dim tWnd As Integer = 0
Dim bWnd As Integer = 0
tWnd = FindWindow("Shell_TrayWnd", vbNullString)
bWnd = FindWindowEx(tWnd, bWnd, "BUTTON", vbNullString)
ShowWindow(bWnd, 1)
ShowWindow(tWnd, 1)
Catch ex As Exception
'Error showing the taskbar, do what you want here..
End Try
End Sub
C++ How do I convert a std::chrono::time_point to long and back
std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
This is a great place for auto
:
auto now = std::chrono::system_clock::now();
Since you want to traffic at millisecond
precision, it would be good to go ahead and covert to it in the time_point
:
auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
now_ms
is a time_point
, based on system_clock
, but with the precision of milliseconds
instead of whatever precision your system_clock
has.
auto epoch = now_ms.time_since_epoch();
epoch
now has type std::chrono::milliseconds
. And this next statement becomes essentially a no-op (simply makes a copy and does not make a conversion):
auto value = std::chrono::duration_cast<std::chrono::milliseconds>(epoch);
Here:
long duration = value.count();
In both your and my code, duration
holds the number of milliseconds
since the epoch of system_clock
.
This:
std::chrono::duration<long> dur(duration);
Creates a duration
represented with a long
, and a precision of seconds
. This effectively reinterpret_cast
s the milliseconds
held in value
to seconds
. It is a logic error. The correct code would look like:
std::chrono::milliseconds dur(duration);
This line:
std::chrono::time_point<std::chrono::system_clock> dt(dur);
creates a time_point
based on system_clock
, with the capability of holding a precision to the system_clock
's native precision (typically finer than milliseconds). However the run-time value will correctly reflect that an integral number of milliseconds are held (assuming my correction on the type of dur
).
Even with the correction, this test will (nearly always) fail though:
if (dt != now)
Because dt
holds an integral number of milliseconds
, but now
holds an integral number of ticks finer than a millisecond
(e.g. microseconds
or nanoseconds
). Thus only on the rare chance that system_clock::now()
returned an integral number of milliseconds
would the test pass.
But you can instead:
if (dt != now_ms)
And you will now get your expected result reliably.
Putting it all together:
int main ()
{
auto now = std::chrono::system_clock::now();
auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
auto value = now_ms.time_since_epoch();
long duration = value.count();
std::chrono::milliseconds dur(duration);
std::chrono::time_point<std::chrono::system_clock> dt(dur);
if (dt != now_ms)
std::cout << "Failure." << std::endl;
else
std::cout << "Success." << std::endl;
}
Personally I find all the std::chrono
overly verbose and so I would code it as:
int main ()
{
using namespace std::chrono;
auto now = system_clock::now();
auto now_ms = time_point_cast<milliseconds>(now);
auto value = now_ms.time_since_epoch();
long duration = value.count();
milliseconds dur(duration);
time_point<system_clock> dt(dur);
if (dt != now_ms)
std::cout << "Failure." << std::endl;
else
std::cout << "Success." << std::endl;
}
Which will reliably output:
Success.
Finally, I recommend eliminating temporaries to reduce the code converting between time_point
and integral type to a minimum. These conversions are dangerous, and so the less code you write manipulating the bare integral type the better:
int main ()
{
using namespace std::chrono;
// Get current time with precision of milliseconds
auto now = time_point_cast<milliseconds>(system_clock::now());
// sys_milliseconds is type time_point<system_clock, milliseconds>
using sys_milliseconds = decltype(now);
// Convert time_point to signed integral type
auto integral_duration = now.time_since_epoch().count();
// Convert signed integral type to time_point
sys_milliseconds dt{milliseconds{integral_duration}};
// test
if (dt != now)
std::cout << "Failure." << std::endl;
else
std::cout << "Success." << std::endl;
}
The main danger above is not interpreting integral_duration
as milliseconds
on the way back to a time_point
. One possible way to mitigate that risk is to write:
sys_milliseconds dt{sys_milliseconds::duration{integral_duration}};
This reduces risk down to just making sure you use sys_milliseconds
on the way out, and in the two places on the way back in.
And one more example: Let's say you want to convert to and from an integral which represents whatever duration system_clock
supports (microseconds, 10th of microseconds or nanoseconds). Then you don't have to worry about specifying milliseconds as above. The code simplifies to:
int main ()
{
using namespace std::chrono;
// Get current time with native precision
auto now = system_clock::now();
// Convert time_point to signed integral type
auto integral_duration = now.time_since_epoch().count();
// Convert signed integral type to time_point
system_clock::time_point dt{system_clock::duration{integral_duration}};
// test
if (dt != now)
std::cout << "Failure." << std::endl;
else
std::cout << "Success." << std::endl;
}
This works, but if you run half the conversion (out to integral) on one platform and the other half (in from integral) on another platform, you run the risk that system_clock::duration
will have different precisions for the two conversions.
CSS: fixed position on x-axis but not y?
$(window).scroll(function(){
$('#header').css({
'left': $(this).scrollLeft() + 15
//Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
});
});
Thanks
Run JavaScript in Visual Studio Code
I would suggest you to use a simple and easy plugin called as Quokka which is very popular these days and helps you debug your code on the go.
Quokka.js. One biggest advantage in using this plugin is that you save a lot of time to go on web browser and evaluate your code, with help of this you can see everything happening in VS code, which saves a lot of time.
CSV API for Java
For the last enterprise application I worked on that needed to handle a notable amount of CSV -- a couple of months ago -- I used SuperCSV at sourceforge and found it simple, robust and problem-free.
How to set "style=display:none;" using jQuery's attr method?
Why not just use $('#msform').hide()
? Behind the scene jQuery's hide
and show
just set display: none
or display: block
.
hide()
will not change the style if already hidden.
based on the comment below, you are removing all style with removeAttr("style")
, in which case call hide()
immediately after that.
e.g.
$("#msform").removeAttr("style").hide();
The reverse of this is of course show()
as in
$("#msform").show();
Or, more interestingly, toggle()
, which effective flips between hide()
and show()
based on the current state.
How to resolve "git did not exit cleanly (exit code 128)" error on TortoiseGit?
I was having this same issue and I resolved it in the following way...
I have the NVIDIA "Tegra Android Development Pack" installed and it seems to also have a version of mysysgit.exe with it. TortoiseGit automatically found that installation location (instead of the standard git installation) and auto-populated it in the settings menu.
To correct this, go to: "Settings -> General" and there is a field for the path to mysysgit.exe. Make sure this is pointing to the correct installation.
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
Setting background color for a JFrame
using:
setBackground(Color.red);
doesn't work properly.
use
Container c = JFrame.getContentPane();
c.setBackground(Color.red);
or
myJFrame.getContentPane().setBackground( Color.red );
Bloomberg Open API
The API's will provide full access to LIVE data, and developers can thus provide applications and develop against the API without paying licencing fees. Consumers will pay for any data received from the apps provided by third party developers, and so BB will grow their audience and revenue in that way.
NOTE: Bloomberg is offering this programming interface (BLPAPI) under a free-use license. This license does not include nor provide access to any Bloomberg data or content.
Source: http://www.openbloomberg.com/open-api/
Can you recommend a free light-weight MySQL GUI for Linux?
Try Adminer. The whole application is in one PHP file, which means that the deployment is as easy as it can get. It's more powerful than phpMyAdmin; it can edit views, procedures, triggers, etc.
Adminer is also a universal tool, it can connect to MySQL, PostgreSQL, SQLite, MS SQL, Oracle, SimpleDB, Elasticsearch and MongoDB.
You should definitely give it a try.
You can install on Ubuntu with sudo apt-get install adminer
or you can also download the latest version from adminer.org
Query EC2 tags from within instance
Install AWS CLI:
curl "https://s3.amazonaws.com/aws-cli/awscli-bundle.zip" -o "awscli-bundle.zip"
sudo apt-get install unzip
unzip awscli-bundle.zip
sudo ./awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws
Get the tags for the current instance:
aws ec2 describe-tags --filters "Name=resource-id,Values=`ec2metadata --instance-id`"
Outputs:
{
"Tags": [
{
"ResourceType": "instance",
"ResourceId": "i-6a7e559d",
"Value": "Webserver",
"Key": "Name"
}
]
}
Use a bit of perl to extract the tags:
aws ec2 describe-tags --filters \
"Name=resource-id,Values=`ec2metadata --instance-id`" | \
perl -ne 'print "$1\n" if /\"Value\": \"(.*?)\"/'
Returns:
Webserver
Java check to see if a variable has been initialized
Instance variables or fields, along with static variables, are assigned default values based on the variable type:
- int:
0
- char:
\u0000
or 0
- double:
0.0
- boolean:
false
- reference:
null
Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.
Share data between html pages
I know this is an old post, but figured I'd share my two cents. @Neji is correct in that you can use sessionStorage.getItem('label')
, and sessionStorage.setItem('label', 'value')
(although he had the setItem
parameters backwards, not a big deal). I much more prefer the following, I think it's more succinct:
var val = sessionStorage.myValue
in place of getItem
and
sessionStorage.myValue = 'value'
in place of setItem
.
Also, it should be noted that in order to store JavaScript objects, they must be stringified to set them, and parsed to get them, like so:
sessionStorage.myObject = JSON.stringify(myObject); //will set object to the stringified myObject
var myObject = JSON.parse(sessionStorage.myObject); //will parse JSON string back to object
The reason is that sessionStorage stores everything as a string, so if you just say sessionStorage.object = myObject
all you get is [object Object], which doesn't help you too much.
Sqlite convert string to date
The UDF approach is my preference compared to brittle substr
values.
#!/usr/bin/env python3
import sqlite3
from dateutil import parser
from pprint import pprint
def date_parse(s):
''' Converts a string to a date '''
try:
t = parser.parse(s, parser.parserinfo(dayfirst=True))
return t.strftime('%Y-%m-%d')
except:
return None
def dict_factory(cursor, row):
''' Helper for dict row results '''
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def main():
''' Demonstrate UDF '''
with sqlite3.connect(":memory:") as conn:
conn.row_factory = dict_factory
setup(conn)
##################################################
# This is the code that matters. The rest is setup noise.
conn.create_function("date_parse", 1, date_parse)
cur = conn.cursor()
cur.execute(''' select "date", date_parse("date") as parsed from _test order by 2; ''')
pprint(cur.fetchall())
##################################################
def setup(conn):
''' Setup some values to parse '''
cur = conn.cursor()
# Make a table
sql = '''
create table _test (
"id" integer primary key,
"date" text
);
'''
cur.execute(sql)
# Fill the table
dates = [
'2/1/03', '03/2/04', '4/03/05', '05/04/06',
'6/5/2007', '07/6/2008', '8/07/2009', '09/08/2010',
'2-1-03', '03-2-04', '4-03-05', '05-04-06',
'6-5-2007', '07-6-2008', '8-07-2009', '09-08-2010',
'31/12/20', '31-12-2020',
'BOMB!',
]
params = [(x,) for x in dates]
cur.executemany(''' insert into _test ("date") values(?); ''', params)
if __name__ == "__main__":
main()
This will give you these results:
[{'date': 'BOMB!', 'parsed': None},
{'date': '2/1/03', 'parsed': '2003-01-02'},
{'date': '2-1-03', 'parsed': '2003-01-02'},
{'date': '03/2/04', 'parsed': '2004-02-03'},
{'date': '03-2-04', 'parsed': '2004-02-03'},
{'date': '4/03/05', 'parsed': '2005-03-04'},
{'date': '4-03-05', 'parsed': '2005-03-04'},
{'date': '05/04/06', 'parsed': '2006-04-05'},
{'date': '05-04-06', 'parsed': '2006-04-05'},
{'date': '6/5/2007', 'parsed': '2007-05-06'},
{'date': '6-5-2007', 'parsed': '2007-05-06'},
{'date': '07/6/2008', 'parsed': '2008-06-07'},
{'date': '07-6-2008', 'parsed': '2008-06-07'},
{'date': '8/07/2009', 'parsed': '2009-07-08'},
{'date': '8-07-2009', 'parsed': '2009-07-08'},
{'date': '09/08/2010', 'parsed': '2010-08-09'},
{'date': '09-08-2010', 'parsed': '2010-08-09'},
{'date': '31/12/20', 'parsed': '2020-12-31'},
{'date': '31-12-2020', 'parsed': '2020-12-31'}]
The SQLite equivalent of anything this robust is a tangled weave of substr
and instr
calls that you should avoid.
How can I see if a Perl hash already has a certain key?
Well, your whole code can be limited to:
foreach $line (@lines){
$strings{$1}++ if $line =~ m|my regex|;
}
If the value is not there, ++ operator will assume it to be 0 (and then increment to 1). If it is already there - it will simply be incremented.
How can I get the current date and time in UTC or GMT in Java?
tl;dr
Instant.now() // Capture the current moment in UTC.
Generate a String to represent that value:
Instant.now().toString()
2016-09-13T23:30:52.123Z
Details
As the correct answer by Jon Skeet stated, a java.util.Date object has no time zone†. But its toString
implementation applies the JVM’s default time zone when generating the String representation of that date-time value. Confusingly to the naïve programmer, a Date seems to have a time zone but does not.
The java.util.Date
, j.u.Calendar
, and java.text.SimpleDateFormat
classes bundled with Java are notoriously troublesome. Avoid them. Instead, use either of these competent date-time libraries:
java.time (Java 8)
Java 8 brings an excellent new java.time.* package to supplant the old java.util.Date/Calendar classes.
Getting current time in UTC/GMT is a simple one-liner…
Instant instant = Instant.now();
That Instant
class is the basic building block in java.time, representing a moment on the timeline in UTC with a resolution of nanoseconds.
In Java 8, the current moment is captured with only up to milliseconds resolution. Java 9 brings a fresh implementation of Clock
captures the current moment in up to the full nanosecond capability of this class, depending on the ability of your host computer’s clock hardware.
It’s toString
method generates a String representation of its value using one specific ISO 8601 format. That format outputs zero, three, six or nine digits digits (milliseconds, microseconds, or nanoseconds) as necessary to represent the fraction-of-second.
If you want more flexible formatting, or other additional features, then apply an offset-from-UTC of zero, for UTC itself (ZoneOffset.UTC
constant) to get a OffsetDateTime
.
OffsetDateTime now = OffsetDateTime.now( ZoneOffset.UTC );
Dump to console…
System.out.println( "now.toString(): " + now );
When run…
now.toString(): 2014-01-21T23:42:03.522Z
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Joda-Time
UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
Using the Joda-Time 3rd-party open-source free-of-cost library, you can get the current date-time in just one line of code.
Joda-Time inspired the new java.time.* classes in Java 8, but has a different architecture. You may use Joda-Time in older versions of Java. Joda-Time continues to work in Java 8 and continues to be actively maintained (as of 2014). However, the Joda-Time team does advise migration to java.time.
System.out.println( "UTC/GMT date-time in ISO 8601 format: " + new org.joda.time.DateTime( org.joda.time.DateTimeZone.UTC ) );
More detailed example code (Joda-Time 2.3)…
org.joda.time.DateTime now = new org.joda.time.DateTime(); // Default time zone.
org.joda.time.DateTime zulu = now.toDateTime( org.joda.time.DateTimeZone.UTC );
Dump to console…
System.out.println( "Local time in ISO 8601 format: " + now );
System.out.println( "Same moment in UTC (Zulu): " + zulu );
When run…
Local time in ISO 8601 format: 2014-01-21T15:34:29.933-08:00
Same moment in UTC (Zulu): 2014-01-21T23:34:29.933Z
For more example code doing time zone work, see my answer to a similar question.
Time Zone
I recommend you always specify a time zone rather than relying implicitly on the JVM’s current default time zone (which can change at any moment!). Such reliance seems to be a common cause of confusion and bugs in date-time work.
When calling now()
pass the desired/expected time zone to be assigned. Use the DateTimeZone
class.
DateTimeZone zoneMontréal = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zoneMontréal );
That class holds a constant for UTC time zone.
DateTime now = DateTime.now( DateTimeZone.UTC );
If you truly want to use the JVM’s current default time zone, make an explicit call so your code is self-documenting.
DateTimeZone zoneDefault = DateTimeZone.getDefault();
ISO 8601
Read about ISO 8601 formats. Both java.time and Joda-Time use that standard’s sensible formats as their defaults for both parsing and generating strings.
† Actually, java.util.Date does have a time zone, buried deep under layers of source code. For most practical purposes, that time zone is ignored. So, as shorthand, we say java.util.Date has no time zone. Furthermore, that buried time zone is not the one used by Date’s toString
method; that method uses the JVM’s current default time zone. All the more reason to avoid this confusing class and stick with Joda-Time and java.time.
Socket.io + Node.js Cross-Origin Request Blocked
After read a lot of subjetcs on StakOverflow and other forums, I found the working solution for me. This solution is for working without Express.
here are the prerequisites.
SERVER SIDE
// DEPENDENCIES
var fs = require('fs'),
winston = require('winston'),
path = require('path');
// LOGS
const logger = winston.createLogger({
level : 'info',
format : winston.format.json(),
transports: [
new winston.transports.Console({ level: 'debug' }),
new winston.transports.File({ filename: 'err.log', level: 'err' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
// CONSTANTS
const Port = 9000,
certsPath = '/etc/letsencrypt/live/my.domain.com/';
// STARTING HTTPS SERVER
var server = require('https').createServer({
key: fs.readFileSync(certsPath + 'privkey.pem'),
cert: fs.readFileSync(certsPath + 'cert.pem'),
ca: fs.readFileSync(certsPath + 'chain.pem'),
requestCert: false,
rejectUnauthorized: false
},
(req, res) => {
var filePath = '.' + req.url;
logger.info('FILE ASKED : ' + filePath);
// Default page for visitor calling directly URL
if (filePath == './')
filePath = './index.html';
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.json':
contentType = 'application/json';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
contentType = 'image/jpg';
break;
case '.wav':
contentType = 'audio/wav';
break;
}
var headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
'Access-Control-Max-Age': 2592000, // 30 days
'Content-Type': contentType
};
fs.readFile(filePath, function(err, content) {
if (err) {
if(err.code == 'ENOENT'){
fs.readFile('./errpages/404.html', function(err, content) {
res.writeHead(404, headers);
res.end(content, 'utf-8');
});
}
else {
fs.readFile('./errpages/500.html', function(err, content) {
res.writeHead(500, headers);
res.end(content, 'utf-8');
});
}
}
else {
res.writeHead(200, headers);
res.end(content, 'utf-8');
}
});
if (req.method === 'OPTIONS') {
res.writeHead(204, headers);
res.end();
}
}).listen(port);
//OPENING SOCKET
var io = require('socket.io')(server).on('connection', function(s) {
logger.info("SERVER > Socket opened from client");
//... your code here
});
CLIENT SIDE
<script src="https://my.domain.com:port/js/socket.io.js"></script>
<script>
$(document).ready(function() {
$.socket = io.connect('https://my.domain.com:port', {
secure: true // for SSL
});
//... your code here
});
</script>
How to add Web API to an existing ASP.NET MVC 4 Web Application project?
NOTE : this is just an abbreviation of this answer above
Open NuGet Package manager console and run
PM> Install-Package Microsoft.AspNet.WebApi
Add references to System.Web.Routing
, System.Web.Net
and System.Net.Http
dlls if not there already
Add the following class
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Add Application_Start
method if not there already (in global.asax.cs file)
protected void Application_Start()
{
//this should be line #1 in this method
GlobalConfiguration.Configure(WebApiConfig.Register);
}
Right click controllers folder > add new item > web > Add Web API controller
namespace <Your.NameSpace.Here>
{
public class VSController : ApiController
{
// GET api/<controller> : url to use => api/vs
public string Get()
{
return "Hi from web api controller";
}
}
}
How to concatenate two MP4 files using FFmpeg?
After various tries below script worked for me on windows 10 powershell.
$files=Get-ChildItem -path e:\ -Filter *.mp4
$files| ForEach-Object {"file '$($_.FullName)'"}| Out-File -FilePath e:\temp.txt -Encoding ASCII
if (-not (test-path "e:\ffmpeg\bin\ffmpeg.exe")) {throw "e:\ffmpeg\bin\ffmpeg.exe needed"}
E:\ffmpeg\bin\ffmpeg.exe -safe 0 -f concat -i "e:\temp.txt" -c copy -bsf:v hevc_mp4toannexb -an e:\joined.mp4
# Conversion Cleanup
Remove-Item e:\temp.txt
Here first two lines create a text file temp.txt which has following content
file 'e:\first.mp4'
file 'e:\second.mp4'
3rd, 4th lines checks if ffmpeg is available at path and create the "joined.mp4"
The key differences from other answers are as below
usage of -bsf:v hevc_mp4toannexb -an
for my mp4 file above worked, you may need to use other alternatives like below depending on your video encoding.
h264_mp4toannexb
All such possible Bitstream filters can be found at https://ffmpeg.org/ffmpeg-bitstream-filters.html
Close virtual keyboard on button press
You use this code in your button click event
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
Can I run multiple programs in a Docker container?
There can be only one ENTRYPOINT, but that target is usually a script that launches as many programs that are needed. You can additionally use for example Supervisord or similar to take care of launching multiple services inside single container. This is an example of a docker container running mysql, apache and wordpress within a single container.
Say, You have one database that is used by a single web application. Then it is probably easier to run both in a single container.
If You have a shared database that is used by more than one application, then it would be better to run the database in its own container and the applications each in their own containers.
There are at least two possibilities how the applications can communicate with each other when they are running in different containers:
- Use exposed IP ports and connect via them.
- Recent docker versions support linking.
Get Category name from Post ID
doesn't
<?php get_the_category( $id ) ?>
do just that, inside the loop?
For outside:
<?php
global $post;
$categories = get_the_category($post->ID);
var_dump($categories);
?>
Settings to Windows Firewall to allow Docker for Windows to share drive
What did it for me (after several hours of trial-n-error) was changing the Subnet Mask from 255.255.255.240
to 255.255.255.0
(which should not change anything).
As part of the trial-n-error, I had done everything else listed on article, but without any success .. but this last step did it .. and reverting back to 255.255.255.240
does not break the good cycle.
I admit, it makes no sense .. but it might be related to an internal state only being triggered by the network change.
Anyway, if i have helped just one, then it was worth the effort.
Docker Desktop edge, 2.0.4.1 (34207)
Java Error opening registry key
There are 3 locations to check
- Registry HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.8.0_xxx\JavaHome
- Java Control Panel- Java tab - View - Path
- Environment Variables - Path ($env:Path)
All 3 have to align (if you have multiple entires just remove the wrong ones) - thats all
Get the current time in C
#include <stdio.h>
#include <time.h>
void main()
{
time_t t;
time(&t);
clrscr();
printf("Today's date and time : %s",ctime(&t));
getch();
}
iOS UIImagePickerController result image orientation after upload
Here is a Swift version of the answer by @an0:
func normalizedImage() -> UIImage {
if (self.imageOrientation == UIImageOrientation.Up) {
return self;
}
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
self.drawInRect(rect)
let normalizedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return normalizedImage;
}
Also in a more general function:
func fixOrientation(img:UIImage) -> UIImage {
if (img.imageOrientation == UIImageOrientation.Up) {
return img;
}
UIGraphicsBeginImageContextWithOptions(img.size, false, img.scale);
let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
img.drawInRect(rect)
let normalizedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return normalizedImage;
}
Swift 3 version:
func fixOrientation(img: UIImage) -> UIImage {
if (img.imageOrientation == .up) {
return img
}
UIGraphicsBeginImageContextWithOptions(img.size, false, img.scale)
let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
img.draw(in: rect)
let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return normalizedImage
}
Why can't I have "public static const string S = "stuff"; in my Class?
A const member is considered static by the compiler, as well as implying constant value semantics, which means references to the constant might be compiled into the using code as the value of the constant member, instead of a reference to the member.
In other words, a const member containing the value 10, might get compiled into code that uses it as the number 10, instead of a reference to the const member.
This is different from a static readonly field, which will always be compiled as a reference to the field.
Note, this is pre-JIT. When the JIT'ter comes into play, it might compile both these into the target code as values.
If file exists then delete the file
IF both POS_History_bim_data_*.zip and POS_History_bim_data_*.zip.trg exists in Y:\ExternalData\RSIDest\ Folder then Delete File Y:\ExternalData\RSIDest\Target_slpos_unzip_done.dat
Jquery how to find an Object by attribute in an Array
No need for jQuery.
JavaScript arrays have a find method, so you can achieve that in one line:
array.find((o) => { return o[propertyName] === propertyValue }
Example
const purposeObjects = [
{purpose: "daily"},
{purpose: "weekly"},
{purpose: "monthly"}
];
purposeObjects.find((o) => { return o["purpose"] === "weekly" }
// output -> {purpose: "weekly"}
If you need IE compatibility, import this polyfill in your code.
Add Text on Image using PIL
Even more minimal example (draws "Hello world!" in black and with the default font in the top-left of the image):
...
from PIL import ImageDraw
...
ImageDraw.Draw(
image # Image
).text(
(0, 0), # Coordinates
'Hello world!', # Text
(0, 0, 0) # Color
)
How to stop a vb script running in windows
Start Task Manager, click on the Processes tab, right-click on wscript.exe and select End Process, and confirm in the dialog that follows. This will terminate the wscript.exe that is executing your script.
apt-get for Cygwin?
You can use Chocolatey to install cyg-get
and then install your packages with it.
For example:
choco install cyg-get
Then:
cyg-get install my-package
How to bind Events on Ajax loaded Content?
If the content is appended after .on() is called, you'll need to create a delegated event on a parent element of the loaded content. This is because event handlers are bound when .on() is called (i.e. usually on page load). If the element doesn't exist when .on() is called, the event will not be bound to it!
Because events propagate up through the DOM, we can solve this by creating a delegated event on a parent element (.parent-element
in the example below) that we know exists when the page loads. Here's how:
$('.parent-element').on('click', '.mylink', function(){
alert ("new link clicked!");
})
Some more reading on the subject:
Path.Combine for URLs?
Both of these work:
Uri final = new Uri(Regex.Replace(baseUrl + "/" + relativePath, "(?<!http:)/{2,}", "/"));
Or
Uri final =new Uri(string.Format("{0}/{1}", baseUrl.ToString().TrimEnd('/'), relativePath.ToString().TrimStart('/')));
I.e. if
baseUrl = "http://tesrurl.test.com/Int18"
and
relativePath = "To_Folder"
output = http://tesrurl.test.com/Int18/To_Folder
Some errors will appear for the code below:
// If you use the below code, some issues will be there in the final URI
Uri final = new Uri(baseUrl, relativePath);
percentage of two int?
Two options:
Do the division after the multiplication:
int n = 25;
int v = 100;
int percent = n * 100 / v;
Convert an int
to a float
before dividing
int n = 25;
int v = 100;
float percent = n * 100f / v;
//Or:
// float percent = (float) n * 100 / v;
// float percent = n * 100 / (float) v;
IDEA: javac: source release 1.7 requires target release 1.7
IntelliJ 15, 2016 & 2017
Similar to that discussed below for IntelliJ 13 & 14, but with an extra level in the Settings/Preferences panel: Settings > Build, Execution, Deployment > Compiler > Java Compiler.
IntelliJ 13 & 14
In IntelliJ 13 and 14, check the Settings > Compiler > Java Compiler UI to ensure you're not targeting a different bytecode version in your module.
What are the differences between a pointer variable and a reference variable in C++?
References are very similar to pointers, but they are specifically crafted to be helpful to optimizing compilers.
- References are designed such that it is substantially easier for the compiler to trace which reference aliases which variables. Two major features are very important: no "reference arithmetic" and no reassigning of references. These allow the compiler to figure out which references alias which variables at compile time.
- References are allowed to refer to variables which do not have memory addresses, such as those the compiler chooses to put into registers. If you take the address of a local variable, it is very hard for the compiler to put it in a register.
As an example:
void maybeModify(int& x); // may modify x in some way
void hurtTheCompilersOptimizer(short size, int array[])
{
// This function is designed to do something particularly troublesome
// for optimizers. It will constantly call maybeModify on array[0] while
// adding array[1] to array[2]..array[size-1]. There's no real reason to
// do this, other than to demonstrate the power of references.
for (int i = 2; i < (int)size; i++) {
maybeModify(array[0]);
array[i] += array[1];
}
}
An optimizing compiler may realize that we are accessing a[0] and a[1] quite a bunch. It would love to optimize the algorithm to:
void hurtTheCompilersOptimizer(short size, int array[])
{
// Do the same thing as above, but instead of accessing array[1]
// all the time, access it once and store the result in a register,
// which is much faster to do arithmetic with.
register int a0 = a[0];
register int a1 = a[1]; // access a[1] once
for (int i = 2; i < (int)size; i++) {
maybeModify(a0); // Give maybeModify a reference to a register
array[i] += a1; // Use the saved register value over and over
}
a[0] = a0; // Store the modified a[0] back into the array
}
To make such an optimization, it needs to prove that nothing can change array[1] during the call. This is rather easy to do. i is never less than 2, so array[i] can never refer to array[1]. maybeModify() is given a0 as a reference (aliasing array[0]). Because there is no "reference" arithmetic, the compiler just has to prove that maybeModify never gets the address of x, and it has proven that nothing changes array[1].
It also has to prove that there are no ways a future call could read/write a[0] while we have a temporary register copy of it in a0. This is often trivial to prove, because in many cases it is obvious that the reference is never stored in a permanent structure like a class instance.
Now do the same thing with pointers
void maybeModify(int* x); // May modify x in some way
void hurtTheCompilersOptimizer(short size, int array[])
{
// Same operation, only now with pointers, making the
// optimization trickier.
for (int i = 2; i < (int)size; i++) {
maybeModify(&(array[0]));
array[i] += array[1];
}
}
The behavior is the same; only now it is much harder to prove that maybeModify does not ever modify array[1], because we already gave it a pointer; the cat is out of the bag. Now it has to do the much more difficult proof: a static analysis of maybeModify to prove it never writes to &x + 1. It also has to prove that it never saves off a pointer that can refer to array[0], which is just as tricky.
Modern compilers are getting better and better at static analysis, but it is always nice to help them out and use references.
Of course, barring such clever optimizations, compilers will indeed turn references into pointers when needed.
EDIT: Five years after posting this answer, I found an actual technical difference where references are different than just a different way of looking at the same addressing concept. References can modify the lifespan of temporary objects in a way that pointers cannot.
F createF(int argument);
void extending()
{
const F& ref = createF(5);
std::cout << ref.getArgument() << std::endl;
};
Normally temporary objects such as the one created by the call to createF(5)
are destroyed at the end of the expression. However, by binding that object to a reference, ref
, C++ will extend the lifespan of that temporary object until ref
goes out of scope.
how to convert a string to date in mysql?
The following illustrates the syntax of the STR_TO_DATE()
function:
STR_TO_DATE(str,fmt);
The STR_TO_DATE()
converts the str string into a date value based on the fmt format string. The STR_TO_DATE()
function may return a DATE , TIME, or DATETIME value based on the input and format strings. If the input string is illegal, the STR_TO_DATE()
function returns NULL.
The following statement converts a string into a DATE value.
SELECT STR_TO_DATE('21,5,2013','%d,%m,%Y');
Based on the format string ‘%d, %m, %Y’, the STR_TO_DATE()
function scans the ‘21,5,2013’ input string.
- First, it attempts to find a match for the %d format specifier, which
is a day of the month (01…31), in the input string. Because the
number 21 matches with the %d specifier, the function takes 21 as the
day value.
- Second, because the comma (,) literal character in the format string
matches with the comma in the input string, the function continues to
check the second format specifier %m , which is a month (01…12), and
finds that the number 5 matches with the %m format specifier. It
takes the number 5 as the month value.
- Third, after matching the second comma (,), the
STR_TO_DATE()
function keeps finding a match for the third format specifier %Y ,
which is four-digit year e.g., 2012,2013, etc., and it takes the
number 2013 as the year value.
The STR_TO_DATE()
function ignores extra characters at the end of the input string when it parses the input string based on the format string. See the following example:
SELECT STR_TO_DATE('21,5,2013 extra characters','%d,%m,%Y');
More Details : Reference
Correctly Parsing JSON in Swift 3
The problem is with the API interaction method. The JSON parsing is changed only in syntax. The main problem is with the way of fetching data. What you are using is a synchronous way of getting data. This doesn't work in every case. What you should be using is an asynchronous way to fetch data. In this way, you have to request data through the API and wait for it to respond with data. You can achieve this with URL session and third party libraries like Alamofire
. Below is the code for URL Session method.
let urlString = "https://api.forecast.io/forecast/apiKey/37.5673776,122.048951"
let url = URL.init(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
guard error == nil else {
print(error)
}
do {
let Data = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
// Note if your data is coming in Array you should be using [Any]()
//Now your data is parsed in Data variable and you can use it normally
let currentConditions = Data["currently"] as! [String:Any]
print(currentConditions)
let currentTemperatureF = currentConditions["temperature"] as! Double
print(currentTemperatureF)
} catch let error as NSError {
print(error)
}
}.resume()
Swift - Integer conversion to Hours/Minutes/Seconds
Define
func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
Use
> secondsToHoursMinutesSeconds(27005)
(7,30,5)
or
let (h,m,s) = secondsToHoursMinutesSeconds(27005)
The above function makes use of Swift tuples to return three values at once. You destructure the tuple using the let (var, ...)
syntax or can access individual tuple members, if need be.
If you actually need to print it out with the words Hours
etc then use something like this:
func printSecondsToHoursMinutesSeconds (seconds:Int) -> () {
let (h, m, s) = secondsToHoursMinutesSeconds (seconds)
print ("\(h) Hours, \(m) Minutes, \(s) Seconds")
}
Note that the above implementation of secondsToHoursMinutesSeconds()
works for Int
arguments. If you want a Double
version you'll need to decide what the return values are - could be (Int, Int, Double)
or could be (Double, Double, Double)
. You could try something like:
func secondsToHoursMinutesSeconds (seconds : Double) -> (Double, Double, Double) {
let (hr, minf) = modf (seconds / 3600)
let (min, secf) = modf (60 * minf)
return (hr, min, 60 * secf)
}
The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe
Just adding here that [[
also is equipped for recursive indexing.
This was hinted at in the answer by @JijoMatthew but not explored.
As noted in ?"[["
, syntax like x[[y]]
, where length(y) > 1
, is interpreted as:
x[[ y[1] ]][[ y[2] ]][[ y[3] ]] ... [[ y[length(y)] ]]
Note that this doesn't change what should be your main takeaway on the difference between [
and [[
-- namely, that the former is used for subsetting, and the latter is used for extracting single list elements.
For example,
x <- list(list(list(1), 2), list(list(list(3), 4), 5), 6)
x
# [[1]]
# [[1]][[1]]
# [[1]][[1]][[1]]
# [1] 1
#
# [[1]][[2]]
# [1] 2
#
# [[2]]
# [[2]][[1]]
# [[2]][[1]][[1]]
# [[2]][[1]][[1]][[1]]
# [1] 3
#
# [[2]][[1]][[2]]
# [1] 4
#
# [[2]][[2]]
# [1] 5
#
# [[3]]
# [1] 6
To get the value 3, we can do:
x[[c(2, 1, 1, 1)]]
# [1] 3
Getting back to @JijoMatthew's answer above, recall r
:
r <- list(1:10, foo=1, far=2)
In particular, this explains the errors we tend to get when mis-using [[
, namely:
r[[1:3]]
Error in r[[1:3]]
: recursive indexing failed at level 2
Since this code actually tried to evaluate r[[1]][[2]][[3]]
, and the nesting of r
stops at level one, the attempt to extract through recursive indexing failed at [[2]]
, i.e., at level 2.
Error in r[[c("foo", "far")]]
: subscript out of bounds
Here, R was looking for r[["foo"]][["far"]]
, which doesn't exist, so we get the subscript out of bounds error.
It probably would be a bit more helpful/consistent if both of these errors gave the same message.
Windows batch: formatted date into variable
Check this one..
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%" & set "MS=%dt:~15,3%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" & set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%-%MS%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
html5: display video inside canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var video = document.getElementById('video');
video.addEventListener('play', function () {
var $this = this; //cache
(function loop() {
if (!$this.paused && !$this.ended) {
ctx.drawImage($this, 0, 0);
setTimeout(loop, 1000 / 30); // drawing at 30fps
}
})();
}, 0);
I guess the above code is self Explanatory, If not drop a comment below, I will try to explain the above few lines of code
Edit :
here's an online example, just for you :)
Demo
_x000D_
_x000D_
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
var video = document.getElementById('video');_x000D_
_x000D_
// set canvas size = video size when known_x000D_
video.addEventListener('loadedmetadata', function() {_x000D_
canvas.width = video.videoWidth;_x000D_
canvas.height = video.videoHeight;_x000D_
});_x000D_
_x000D_
video.addEventListener('play', function() {_x000D_
var $this = this; //cache_x000D_
(function loop() {_x000D_
if (!$this.paused && !$this.ended) {_x000D_
ctx.drawImage($this, 0, 0);_x000D_
setTimeout(loop, 1000 / 30); // drawing at 30fps_x000D_
}_x000D_
})();_x000D_
}, 0);
_x000D_
<div id="theater">_x000D_
<video id="video" src="http://upload.wikimedia.org/wikipedia/commons/7/79/Big_Buck_Bunny_small.ogv" controls="false"></video>_x000D_
<canvas id="canvas"></canvas>_x000D_
<label>_x000D_
<br />Try to play me :)</label>_x000D_
<br />_x000D_
</div>
_x000D_
_x000D_
_x000D_
Regular expression that matches valid IPv6 addresses
For PHP 5.2+ users filter_var
works great.
I know this doesn't answer the original question (specifically a regex solution), but I post this in the hope it may help someone else in the future.
$is_ip4address = (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== FALSE);
$is_ip6address = (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== FALSE);
Export table data from one SQL Server to another
Just for the kicks.
Since I wasnt able to create linked server and since just connecting to production server was not enough to use INSERT INTO
i did the following:
- created a backup of production server database
- restored the database on my test server
- executed the insert into statements
Its a backdoor solution, but since i had problems it worked for me.
Since i have created empty tables using SCRIPT TABLE AS / CREATE
in order to transfer all the keys and indexes I couldnt use SELECT INTO
. SELECT INTO
only works if the tables do not exist on the destination location but it does not copy keys and indexes, so you have to do that manualy. The downside of using INSERT INTO
statement is that you have to manualy provide with all the column names, plus it might give you some problems if some foreign key constraints fail.
Thanks to all anwsers, there are some great solutions but i have decided to accept marc_s anwser.
What is move semantics?
To illustrate the need for move semantics, let's consider this example without move semantics:
Here's a function that takes an object of type T
and returns an object of the same type T
:
T f(T o) { return o; }
//^^^ new object constructed
The above function uses call by value which means that when this function is called an object must be constructed to be used by the function.
Because the function also returns by value, another new object is constructed for the return value:
T b = f(a);
//^ new object constructed
Two new objects have been constructed, one of which is a temporary object that's only used for the duration of the function.
When the new object is created from the return value, the copy constructor is called to copy the contents of the temporary object to the new object b. After the function completes, the temporary object used in the function goes out of scope and is destroyed.
Now, let's consider what a copy constructor does.
It must first initialize the object, then copy all the relevant data from the old object to the new one.
Depending on the class, maybe its a container with very much data, then that could represent much time and memory usage
// Copy constructor
T::T(T &old) {
copy_data(m_a, old.m_a);
copy_data(m_b, old.m_b);
copy_data(m_c, old.m_c);
}
With move semantics it's now possible to make most of this work less unpleasant by simply moving the data rather than copying.
// Move constructor
T::T(T &&old) noexcept {
m_a = std::move(old.m_a);
m_b = std::move(old.m_b);
m_c = std::move(old.m_c);
}
Moving the data involves re-associating the data with the new object. And no copy takes place at all.
This is accomplished with an rvalue
reference.
An rvalue
reference works pretty much like an lvalue
reference with one important difference:
an rvalue reference can be moved and an lvalue cannot.
From cppreference.com:
To make strong exception guarantee possible, user-defined move constructors should not throw exceptions. In fact, standard containers typically rely on std::move_if_noexcept to choose between move and copy when container elements need to be relocated.
If both copy and move constructors are provided, overload resolution selects the move constructor if the argument is an rvalue (either a prvalue such as a nameless temporary or an xvalue such as the result of std::move), and selects the copy constructor if the argument is an lvalue (named object or a function/operator returning lvalue reference). If only the copy constructor is provided, all argument categories select it (as long as it takes a reference to const, since rvalues can bind to const references), which makes copying the fallback for moving, when moving is unavailable.
In many situations, move constructors are optimized out even if they would produce observable side-effects, see copy elision.
A constructor is called a 'move constructor' when it takes an rvalue reference as a parameter. It is not obligated to move anything, the class is not required to have a resource to be moved and a 'move constructor' may not be able to move a resource as in the allowable (but maybe not sensible) case where the parameter is a const rvalue reference (const T&&).
Description for event id from source cannot be found
You need to create an event source and a message file for it. Code looks something like this:
var data = new EventSourceCreationData("yourApp", "Application");
data.MessageResourceFile = pathToYourMessageFile;
EventLog.CreateEventSource(data);
Then you will need to create a message file. There is also this article that explains things (I did not read it all but it seems fairly complete).
Histogram using gnuplot?
yes, and its quick and simple though very hidden:
binwidth=5
bin(x,width)=width*floor(x/width)
plot 'datafile' using (bin($1,binwidth)):(1.0) smooth freq with boxes
check out help smooth freq
to see why the above makes a histogram
to deal with ranges just set the xrange variable.
How to sort a HashMap in Java
In Java 8:
Comparator<Entry<String, Item>> valueComparator =
(e1, e2) -> e1.getValue().getField().compareTo(e2.getValue().getField());
Map<String, Item> sortedMap =
unsortedMap.entrySet().stream().
sorted(valueComparator).
collect(Collectors.toMap(Entry::getKey, Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
Using Guava:
Map<String, Item> map = ...;
Function<Item, Integer> getField = new Function<Item, Integer>() {
public Integer apply(Item item) {
return item.getField(); // the field to sort on
}
};
comparatorFunction = Functions.compose(getField, Functions.forMap(map));
comparator = Ordering.natural().onResultOf(comparatorFunction);
Map<String, Item> sortedMap = ImmutableSortedMap.copyOf(map, comparator);
Should Gemfile.lock be included in .gitignore?
A little late to the party, but answers still took me time and foreign reads to understand this problem. So I want to summarize what I have find out about the Gemfile.lock.
When you are building a Rails App, you are using certain versions of gems in your local machine. If you want to avoid errors in the production mode and other branches, you have to use that one Gemfile.lock file everywhere and tell bundler to bundle
for rebuilding gems every time it changes.
If Gemfile.lock
has changed on your production machine and Git doesn't let you git pull
, you should write git reset --hard
to avoid that file change and write git pull
again.
mysql query result into php array
I think you wanted to do this:
while( $row = mysql_fetch_assoc( $result)){
$new_array[] = $row; // Inside while loop
}
Or maybe store id as key too
$new_array[ $row['id']] = $row;
Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5]
.
how to add value to combobox item
Although this question is 5 years old I have come across a nice solution.
Use the 'DictionaryEntry' object to pair keys and values.
Set the 'DisplayMember' and 'ValueMember' properties to:
Me.myComboBox.DisplayMember = "Key"
Me.myComboBox.ValueMember = "Value"
To add items to the ComboBox:
Me.myComboBox.Items.Add(New DictionaryEntry("Text to be displayed", 1))
To retreive items like this:
MsgBox(Me.myComboBox.SelectedItem.Key & " " & Me.myComboBox.SelectedItem.Value)
How to add new line into txt file
No new line:
File.AppendAllText("file.txt", DateTime.Now.ToString());
and then to get a new line after OK:
File.AppendAllText("file.txt", string.Format("{0}{1}", "OK", Environment.NewLine));
Overwriting txt file in java
Your code works fine for me. It replaced the text in the file as expected and didn't append.
If you wanted to append, you set the second parameter in
new FileWriter(fnew,false);
to true;
What's the best way to get the last element of an array without deleting it?
One way to avoid pass-by-reference errors (eg. "end(array_values($foo))") is to use call_user_func or call_user_func_array:
// PHP Fatal error: Only variables can be passed by reference
// No output (500 server error)
var_dump(end(array(1, 2, 3)));
// No errors, but modifies the array's internal pointer
// Outputs "int(3)"
var_dump(call_user_func('end', array(1, 2, 3)));
// PHP Strict standards: Only variables should be passed by reference
// Outputs "int(3)"
var_dump(end(array_values(array(1, 2, 3))));
// No errors, doesn't change the array
// Outputs "int(3)"
var_dump(call_user_func('end', array_values(array(1, 2, 3))));
JavaScript - Getting HTML form values
Here is an example from W3Schools:
function myFunction() {
var elements = document.getElementById("myForm").elements;
var obj ={};
for(var i = 0 ; i < elements.length ; i++){
var item = elements.item(i);
obj[item.name] = item.value;
}
document.getElementById("demo").innerHTML = JSON.stringify(obj);
}
The demo can be found here.
Java heap terminology: young, old and permanent generations?
Memory in SunHotSpot JVM is organized into three generations: young generation, old generation and permanent generation.
- Young Generation : the newly created objects are allocated to the young gen.
- Old Generation : If the new object requests for a larger heap space, it gets allocated directly into the old gen. Also objects which have survived a few GC cycles gets promoted to the old gen i.e long lived objects house in old gen.
- Permanent Generation : The permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects describing classes and methods, as well as the classes and methods themselves.
FYI: The permanent gen is not considered a part of the Java heap.
How does the three generations interact/relate to each other?
Objects(except the large ones) are first allocated to the young generation. If an object remain alive after x no. of garbage collection cycles it gets promoted to the old/tenured gen. Hence we can say that the young gen contains the short lived objects while the old gen contains the objects having a long life. The permanent gen does not interact with the other two generations.