You could get first rows of Spark DataFrame with head and then create Pandas DataFrame:
l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df_pandas = pd.DataFrame(df.head(3), columns=df.columns)
In [4]: df_pandas
Out[4]:
name age
0 Alice 1
1 Jim 2
2 Sandra 3
Use sortedWith
to sort a list with Comparator
.
You can then construct a comparator using several ways:
In spark 2.2 there are two ways to add constant value in a column in DataFrame:
1) Using lit
2) Using typedLit
.
The difference between the two is that typedLit
can also handle parameterized scala types e.g. List, Seq, and Map
Sample DataFrame:
val df = spark.createDataFrame(Seq((0,"a"),(1,"b"),(2,"c"))).toDF("id", "col1")
+---+----+
| id|col1|
+---+----+
| 0| a|
| 1| b|
+---+----+
1) Using lit
: Adding constant string value in new column named newcol:
import org.apache.spark.sql.functions.lit
val newdf = df.withColumn("newcol",lit("myval"))
Result:
+---+----+------+
| id|col1|newcol|
+---+----+------+
| 0| a| myval|
| 1| b| myval|
+---+----+------+
2) Using typedLit
:
import org.apache.spark.sql.functions.typedLit
df.withColumn("newcol", typedLit(("sample", 10, .044)))
Result:
+---+----+-----------------+
| id|col1| newcol|
+---+----+-----------------+
| 0| a|[sample,10,0.044]|
| 1| b|[sample,10,0.044]|
| 2| c|[sample,10,0.044]|
+---+----+-----------------+
You can also achieve this through aggregate pipeline.
db.collection.aggregate([{$sort:{age:-1}}, {$limit:1}])
Add it to providers not injectables
@Component({
selector:'my-app',
providers: [NameService]
})
According to the pytest docs, pytest --capture=sys
should work. If you want to capture standard out inside a test, refer to the capsys fixture.
Adding to the other answers and doing nothing more of what @Maleta explained in a comment on https://stackoverflow.com/a/28481374/1626594, doing alpha*255 then round then to hex. Here's a quick converter http://jsfiddle.net/8ajxdLap/4/
function rgb2hex(rgb) {_x000D_
var rgbm = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?((?:[0-9]*[.])?[0-9]+)[\s+]?\)/i);_x000D_
if (rgbm && rgbm.length === 5) {_x000D_
return "#" +_x000D_
('0' + Math.round(parseFloat(rgbm[4], 10) * 255).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[1], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[2], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[3], 10).toString(16).toUpperCase()).slice(-2);_x000D_
} else {_x000D_
var rgbm = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);_x000D_
if (rgbm && rgbm.length === 4) {_x000D_
return "#" +_x000D_
("0" + parseInt(rgbm[1], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[2], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[3], 10).toString(16).toUpperCase()).slice(-2);_x000D_
} else {_x000D_
return "cant parse that";_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
$('button').click(function() {_x000D_
var hex = rgb2hex($('#in_tb').val());_x000D_
$('#in_tb_result').html(hex);_x000D_
});
_x000D_
body {_x000D_
padding: 20px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
Convert RGB/RGBA to hex #RRGGBB/#AARRGGBB:<br>_x000D_
<br>_x000D_
<input id="in_tb" type="text" value="rgba(200, 90, 34, 0.75)"> <button>Convert</button><br>_x000D_
<br> Result: <span id="in_tb_result"></span>
_x000D_
<style type="text/css">
div {
text-align: center;
}
.img1{
width: 150px;
height: 150px;
border-radius: 50%;
}
span{
display: block;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type='password' class='secondInput mt-4 mr-1' placeholder="Password">
<span class='dif'></span>
<br>
<button>ADD</button>
</div>
<script type="text/javascript">
$('button').click(function() {
$('.dif').html("<img/>");
})
Surprised no one mentioned a simple if
statement can make sure your loop only gets executed once per format (on the first column, of the first row).
private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// once per format
if (e.ColumnIndex == 0 && e.RowIndex == 0)
{
foreach (DataGridViewRow row in dgv.Rows)
if (row != null)
row.DefaultCellStyle.BackColor = Color.Red;
}
}
One of the easiest solution is
$objectData = (object) $arrayData
The main reason why the error has been generated is because there is already an existing value of 1
for the column ID
in which you define it as PRIMARY KEY
(values are unique) in the table you are inserting.
Why not set the column ID
as AUTO_INCREMENT
?
CREATE TABLE IF NOT EXISTS `PROGETTO`.`UFFICIO-INFORMAZIONI` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`viale` VARCHAR(45) NULL ,
.....
and when you are inserting record, you can now skip the column ID
INSERT INTO `PROGETTO`.`UFFICIO-INFORMAZIONI` (`viale`, `num_civico`, ...)
VALUES ('Viale Cogel ', '120', ...)
For listing only directories:
ls -l | grep ^d
For listing only files:
ls -l | grep -v ^d
Or also you can do as:
ls -ld */
Simply, this should do the task:
import pandas as pd
grouped_df = df1.groupby( [ "Name", "City"] )
pd.DataFrame(grouped_df.size().reset_index(name = "Group_Count"))
Here, grouped_df.size()
pulls up the unique groupby count, and reset_index()
method resets the name of the column you want it to be.
Finally, the pandas Dataframe()
function is called upon to create a DataFrame object.
Starting with Requests version 2.4.2, you can use the json=
parameter (which takes a dictionary) instead of data=
(which takes a string) in the call:
>>> import requests
>>> r = requests.post('http://httpbin.org/post', json={"key": "value"})
>>> r.status_code
200
>>> r.json()
{'args': {},
'data': '{"key": "value"}',
'files': {},
'form': {},
'headers': {'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'close',
'Content-Length': '16',
'Content-Type': 'application/json',
'Host': 'httpbin.org',
'User-Agent': 'python-requests/2.4.3 CPython/3.4.0',
'X-Request-Id': 'xx-xx-xx'},
'json': {'key': 'value'},
'origin': 'x.x.x.x',
'url': 'http://httpbin.org/post'}
Our version of Oracle is running on Red Hat Enterprise Linux. We experimented with several different types of group permissions to no avail. The /defaultdir directory had a group that was a secondary group for the oracle user. When we updated the /defaultdir directory to have a group of "oinstall" (oracle's primary group), I was able to select from the external tables underneath that directory with no problem.
So, for others that come along and might have this issue, make the directory have oracle's primary group as the group and it might resolve it for you as it did us. We were able to set the permissions to 770 on the directory and files and selecting on the external tables works fine now.
example:
AliceBlue
AntiqueWhite
Aqua
Aquamarine
Beige
Replcae \n with ","
AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
Now append "(double-quote) at the start and end
"AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
If your text contains blank lines in between you can use regular expression \n+ instead of \n
example:
AliceBlue
AntiqueWhite
Aqua
Aquamarine
Beige
Replcae \n+ with "," (in regex mode)
AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
Now append "(double-quote) at the start and end
"AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
In C++ a class with at least one pure virtual function is called abstract class. You can not create objects of that class, but may only have pointers or references to it.
If you are deriving from an abstract class, then make sure you override and define all pure virtual functions for your class.
From your snippet Your class AliceUniversity
seems to be an abstract class. It needs to override and define all the pure virtual functions of the classes Graduate
and UniversityGraduate
.
Pure virtual functions are the ones with = 0;
at the end of declaration.
Example: virtual void doSomething() = 0;
For a specific answer, you will need to post the definition of the class for which you get the error and the classes from which that class is deriving.
Yes, the problem is that there are no commits in "bare". This is a problem with the first commit only, if you create the repos in the order (bare,alice). Try doing:
git push --set-upstream origin master
This would only be required the first time. Afterwards it should work normally.
As Chris Johnsen pointed out, you would not have this problem if your push.default was customized. I like upstream/tracking.
slightly modified from top reply:
declare @TableName sysname = 'HistoricCommand'
declare @Result varchar(max) = '[System.Data.Linq.Mapping.Table(Name = "' + @TableName + '")]
public class Dbo' + @TableName + '
{'
select @Result = @Result + '
[System.Data.Linq.Mapping.Column(Name = "' + t.ColumnName + '", IsPrimaryKey = ' + pkk.ISPK + ')]
public ' + ColumnType + NullableSign + ' ' + t.ColumnName + ' { get; set; }
'
from
(
select
replace(col.name, ' ', '_') ColumnName,
column_id ColumnId,
case typ.name
when 'bigint' then 'long'
when 'binary' then 'byte[]'
when 'bit' then 'bool'
when 'char' then 'string'
when 'date' then 'DateTime'
when 'datetime' then 'DateTime'
when 'datetime2' then 'DateTime'
when 'datetimeoffset' then 'DateTimeOffset'
when 'decimal' then 'decimal'
when 'float' then 'float'
when 'image' then 'byte[]'
when 'int' then 'int'
when 'money' then 'decimal'
when 'nchar' then 'string'
when 'ntext' then 'string'
when 'numeric' then 'decimal'
when 'nvarchar' then 'string'
when 'real' then 'double'
when 'smalldatetime' then 'DateTime'
when 'smallint' then 'short'
when 'smallmoney' then 'decimal'
when 'text' then 'string'
when 'time' then 'TimeSpan'
when 'timestamp' then 'DateTime'
when 'tinyint' then 'byte'
when 'uniqueidentifier' then 'Guid'
when 'varbinary' then 'byte[]'
when 'varchar' then 'string'
else 'UNKNOWN_' + typ.name
end ColumnType,
case
when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier')
then '?'
else ''
end NullableSign
from sys.columns col
join sys.types typ on
col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
where object_id = object_id(@TableName)
) t,
(
SELECT c.name AS 'ColumnName', CASE WHEN dd.pk IS NULL THEN 'false' ELSE 'true' END ISPK
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
LEFT JOIN (SELECT K.COLUMN_NAME , C.CONSTRAINT_TYPE as pk
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
ON K.TABLE_NAME = C.TABLE_NAME
AND K.CONSTRAINT_NAME = C.CONSTRAINT_NAME
AND K.CONSTRAINT_CATALOG = C.CONSTRAINT_CATALOG
AND K.CONSTRAINT_SCHEMA = C.CONSTRAINT_SCHEMA
WHERE K.TABLE_NAME = @TableName) as dd
ON dd.COLUMN_NAME = c.name
WHERE t.name = @TableName
) pkk
where pkk.ColumnName = t.ColumnName
order by ColumnId
set @Result = @Result + '
}'
print @Result
which makes output needed for full LINQ in C# declaration
[System.Data.Linq.Mapping.Table(Name = "HistoricCommand")]
public class DboHistoricCommand
{
[System.Data.Linq.Mapping.Column(Name = "HistoricCommandId", IsPrimaryKey = true)]
public int HistoricCommandId { get; set; }
[System.Data.Linq.Mapping.Column(Name = "PHCloudSoftwareInstanceId", IsPrimaryKey = true)]
public int PHCloudSoftwareInstanceId { get; set; }
[System.Data.Linq.Mapping.Column(Name = "CommandType", IsPrimaryKey = false)]
public int CommandType { get; set; }
[System.Data.Linq.Mapping.Column(Name = "InitiatedDateTime", IsPrimaryKey = false)]
public DateTime InitiatedDateTime { get; set; }
[System.Data.Linq.Mapping.Column(Name = "CompletedDateTime", IsPrimaryKey = false)]
public DateTime CompletedDateTime { get; set; }
[System.Data.Linq.Mapping.Column(Name = "WasSuccessful", IsPrimaryKey = false)]
public bool WasSuccessful { get; set; }
[System.Data.Linq.Mapping.Column(Name = "Message", IsPrimaryKey = false)]
public string Message { get; set; }
[System.Data.Linq.Mapping.Column(Name = "ResponseData", IsPrimaryKey = false)]
public string ResponseData { get; set; }
[System.Data.Linq.Mapping.Column(Name = "Message_orig", IsPrimaryKey = false)]
public string Message_orig { get; set; }
[System.Data.Linq.Mapping.Column(Name = "Message_XX", IsPrimaryKey = false)]
public string Message_XX { get; set; }
}
Good example for Iterable to compute factorial
FactorialIterable fi = new FactorialIterable(10);
Iterator<Integer> iterator = fi.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
Short code for Java 1.8
new FactorialIterable(5).forEach(System.out::println);
Custom Iterable class
public class FactorialIterable implements Iterable<Integer> {
private final FactorialIterator factorialIterator;
public FactorialIterable(Integer value) {
factorialIterator = new FactorialIterator(value);
}
@Override
public Iterator<Integer> iterator() {
return factorialIterator;
}
@Override
public void forEach(Consumer<? super Integer> action) {
Objects.requireNonNull(action);
Integer last = 0;
for (Integer t : this) {
last = t;
}
action.accept(last);
}
}
Custom Iterator class
public class FactorialIterator implements Iterator<Integer> {
private final Integer mNumber;
private Integer mPosition;
private Integer mFactorial;
public FactorialIterator(Integer number) {
this.mNumber = number;
this.mPosition = 1;
this.mFactorial = 1;
}
@Override
public boolean hasNext() {
return mPosition <= mNumber;
}
@Override
public Integer next() {
if (!hasNext())
return 0;
mFactorial = mFactorial * mPosition;
mPosition++;
return mFactorial;
}
}
When I used Apache HTTP Client 4.3, I was using the Pooled or Basic Connection Managers to the HTTP Client. I noticed, from using java SSL debugging, that these classes loaded the cacerts trust store and not the one I had specified programmatically.
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager();
builder.setConnectionManager( cm );
I wanted to use them but ended up removing them and creating an HTTP Client without them. Note that builder is an HttpClientBuilder.
I confirmed when running my program with the Java SSL debug flags, and stopped in the debugger. I used -Djavax.net.debug=ssl as a VM argument. I stopped my code in the debugger and when either of the above *ClientConnectionManager were constructed, the cacerts file would be loaded.
Though I tend to agree with @AlekDavis' comment, there are nonetheless several ways to do this in the NT shell.
The approach I would take advantage of the SHIFT command and IF conditional branching, something like this...
@ECHO OFF
SET man1=%1
SET man2=%2
SHIFT & SHIFT
:loop
IF NOT "%1"=="" (
IF "%1"=="-username" (
SET user=%2
SHIFT
)
IF "%1"=="-otheroption" (
SET other=%2
SHIFT
)
SHIFT
GOTO :loop
)
ECHO Man1 = %man1%
ECHO Man2 = %man2%
ECHO Username = %user%
ECHO Other option = %other%
REM ...do stuff here...
:theend
One I used with my kids is CEEBot. It's not python, but it teaches C / Java style programming in a fun, robot-programming kind of game. It is aimed at 10-15 year olds, but it is a really good one.
Use URLSearchParams
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
var data = new URLSearchParams();
data.append('userName', '[email protected]');
data.append('password', 'Password');
data.append('grant_type', 'password');
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
Here's an alternate solution, without using dblink
.
Suppose B represents the source database and A represents the target database: Then,
Copy table from source DB to target DB:
pg_dump -t <source_table> <source_db> | psql <target_db>
Open psql prompt, connect to target_db, and use a simple insert
:
psql
# \c <target_db>;
# INSERT INTO <target_table>(id, x, y) SELECT id, x, y FROM <source_table>;
At the end, delete the copy of source_table that you created in target_table.
# DROP TABLE <source_table>;
I had this error returned after using the commit id from a pull request commit id tab. That commit was subsequently squashed and merged. In the github pull request, look for this text: "merged commit xxxxxxx into..." instead of attempting to use the commit ids from the commits tab.
const
is for compile-time constants. You could just make it static readonly
, but that would only apply to the METRICS
variable itself (which should typically be Metrics instead, by .NET naming conventions). It wouldn't make the list immutable - so someone could call METRICS.Add("shouldn't be here");
You may want to use a ReadOnlyCollection<T>
to wrap it. For example:
public static readonly IList<String> Metrics = new ReadOnlyCollection<string>
(new List<String> {
SourceFile.LoC, SourceFile.McCabe, SourceFile.NoM,
SourceFile.NoA, SourceFile.FanOut, SourceFile.FanIn,
SourceFile.Par, SourceFile.Ndc, SourceFile.Calls });
ReadOnlyCollection<T>
just wraps a potentially-mutable collection, but as nothing else will have access to the List<T>
afterwards, you can regard the overall collection as immutable.
(The capitalization here is mostly guesswork - using fuller names would make them clearer, IMO.)
Whether you declare it as IList<string>
, IEnumerable<string>
, ReadOnlyCollection<string>
or something else is up to you... if you expect that it should only be treated as a sequence, then IEnumerable<string>
would probably be most appropriate. If the order matters and you want people to be able to access it by index, IList<T>
may be appropriate. If you want to make the immutability apparent, declaring it as ReadOnlyCollection<T>
could be handy - but inflexible.
if you want to disable the values of the dropdown
$('select option:not(selected)').prop('disabled', true);
$('select').prop('disabled', true);
HTC One m7 running fresh Cyanogenmod 11.
Phone is connected USB and tethering my data connection.
Then I get this surprise:
cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb shell
error: insufficient permissions for device
cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
???????????? no permissions
SOLUTION: Turn tethering OFF on phone.
cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
HT36AW908858 device
You need to fetch the data from each row of the resultset obtained from the query. You can use mysql_fetch_array()
for this.
// Process all rows
while($row = mysql_fetch_array($result)) {
echo $row['column_name']; // Print a single column data
echo print_r($row); // Print the entire row data
}
Change your code to this :
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) ) FROM modul1open)
ORDER BY idM1O LIMIT 1"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo $row['fieldname'];
}
There should be no \0
in text files.
#include<iostream>
#include<fstream>
using namespace std;
int main(){
fstream f(FILENAME, fstream::in );
string s;
getline( f, s, '\0');
cout << s << endl;
f.close();
}
You don't need to use regex, LIKE
is sufficient:
WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'
Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.
Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]
. [a-z]
may exclude A
or Z
. [A-Z]
may exclude a
or z
.
BComp.exe works in multiple-tabbed scenario as well, so there is no need to add /solo unless you really want separate windows for each file comparison. Tested/verified on Beyond Compare 3 and 4. Moral: use BComp.exe, not BCompare.exe, for VS external compare tool configuration.
In addition to DCookie's answer above, you can also use chr(39) for a single quote.
I find this particularly useful when I have to create a number of insert/update statements based on a large amount of existing data.
Here's a very quick example:
Lets say we have a very simple table, Customers, that has 2 columns, FirstName and LastName. We need to move the data into Customers2, so we need to generate a bunch of INSERT statements.
Select 'INSERT INTO Customers2 (FirstName, LastName) ' ||
'VALUES (' || chr(39) || FirstName || chr(39) ',' ||
chr(39) || LastName || chr(39) || ');' From Customers;
I've found this to be very useful when moving data from one environment to another, or when rebuilding an environment quickly.
On submitting, you would get an array as if created like this:
$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );
However, I would suggest changing your form names to this format instead:
name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...
Using that format, it's much easier to loop through the values.
if ( isset( $_POST['diameters'] ) )
{
echo '<table>';
foreach ( $_POST['diameters'] as $diam )
{
// here you have access to $diam['top'] and $diam['bottom']
echo '<tr>';
echo ' <td>', $diam['top'], '</td>';
echo ' <td>', $diam['bottom'], '</td>';
echo '</tr>';
}
echo '</table>';
}
Using following T-SQL:
SELECT filename FROM master.sys.sysaltfiles WHERE dbid = DB_ID('db_name');
Using T-SQL continuously:
RESTORE DATABASE FROM DISK = 'DB_path' WITH RESTART, REPLACE;
Hope this help!
SpringBoot developers recommend to locate your main application class in a root package above other classes. Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute. Detailed info But be sure that the custom root package exists.
I use this code:
<?php
{
//foreach (glob("images/*.jpg") as $large)
foreach (glob("*.xml") as $filename) {
//echo "$filename\n";
//echo str_replace("","","$filename\n");
echo str_replace("","","<a href='$filename'>$filename</a>\n");
}
}
?>
You need to delete it by order There are dependency in the tables
Andrew Willem's solutions are not mobile device compatible.
Here's a modification of his second solution that works in Edge, IE, Opera, FF, Chrome, iOS Safari and mobile equivalents (that I could test):
Update 1: Removed "requestAnimationFrame" portion, as I agree it's not necessary:
var listener = function() {
// do whatever
};
slider1.addEventListener("input", function() {
listener();
slider1.addEventListener("change", listener);
});
slider1.addEventListener("change", function() {
listener();
slider1.removeEventListener("input", listener);
});
Update 2: Response to Andrew's 2nd Jun 2016 updated answer:
Thanks, Andrew - that appears to work in every browser I could find (Win desktop: IE, Chrome, Opera, FF; Android Chrome, Opera and FF, iOS Safari).
Update 3: if ("oninput in slider) solution
The following appears to work across all the above browsers. (I cannot find the original source now.) I was using this, but it subsequently failed on IE and so I went looking for a different one, hence I ended up here.
if ("oninput" in slider1) {
slider1.addEventListener("input", function () {
// do whatever;
}, false);
}
But before I checked your solution, I noticed this was working again in IE - perhaps there was some other conflict.
Updated answer for Swift 2.0+:
toInt()
method gives an error, as it was removed from String
in Swift 2.x. Instead, the Int
type now has an initializer that accepts a String
:
let a: Int? = Int(firstTextField.text)
let b: Int? = Int(secondTextField.text)
execve()
replaces the current executable image with another one loaded from an executable file.fork()
creates a child process.vfork()
is a historical optimized version of fork()
, meant to be used when execve()
is called directly after fork()
. It turned out to work well in non-MMU systems (where fork()
cannot work in an efficient manner) and when fork()
ing processes with a huge memory footprint to run some small program (think Java's Runtime.exec()
). POSIX has standardized the posix_spawn()
to replace these latter two more modern uses of vfork()
.posix_spawn()
does the equivalent of a fork()/execve()
, and also allows some fd juggling in between. It's supposed to replace fork()/execve()
, mainly for non-MMU platforms.pthread_create()
creates a new thread.clone()
is a Linux-specific call, which can be used to implement anything from fork()
to pthread_create()
. It gives a lot of control. Inspired on rfork()
.rfork()
is a Plan-9 specific call. It's supposed to be a generic call, allowing several degrees of sharing, between full processes and threads.$.ajax({ type: "GET", url: "/Home/Downloadexcel/", contentType: "application/json; charset=utf-8", data: null, success: function (Rdata) { debugger; var bytes = new Uint8Array(Rdata.FileContents); var blob = new Blob([bytes], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }); var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = "myFileName.xlsx"; link.click(); }, error: function (err) { } });
array
is a slightly misleading name. For a dynamically allocated array of pointers, malloc
will return a pointer to a block of memory. You need to use Chess*
and not Chess[]
to hold the pointer to your array.
Chess *array = malloc(size * sizeof(Chess));
array[i] = NULL;
and perhaps later:
/* create new struct chess */
array[i] = malloc(sizeof(struct chess));
/* set up its members */
array[i]->size = 0;
/* etc. */
Plus, you should make sure the MySQL server's config (/etc/mysql/my.cnf, /etc/default/mysql on Debian) doesn't have "skip-networking" activated and is not binded exclusively to the loopback interface (127.0.0.1) but also to the interface/IP address you want connect to.
In case of Select2 Version 4+
it has changed syntax and you need to write like this:
// clear all option
$('#select_with_blank_data').html('').select2({data: [{id: '', text: ''}]});
// clear and add new option
$("#select_with_data").html('').select2({data: [
{id: '', text: ''},
{id: '1', text: 'Facebook'},
{id: '2', text: 'Youtube'},
{id: '3', text: 'Instagram'},
{id: '4', text: 'Pinterest'}]});
Reference link: http://www.programering.com/a/MTNyUDMwATA.html
Steps I followed
1) Execute the command adb nodaemon server
in command prompt
Output at command prompt will be: The following error occurred cannot bind 'tcp:5037'
The original ADB server port binding failed
2) Enter the following command query which using port 5037
netstat -ano | findstr "5037"
The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288
3) View the task manager, close all adb.exe
4) Restart eclipse or other IDE
The above steps worked for me.
It's a little tricky because of the nested IFs but here is my answer (confirmed in Google Spreadsheets):
=IF(AND(A2>=0, A2<500), "Less than 500",
IF(AND(A2>=500, A2<1000), "Between 500 and 1000",
IF(AND(A2>=1000, A2<1500), "Between 1000 and 1500",
IF(AND(A2>=1500, A2<2000), "Between 1500 and 2000", "Undefined"))))
Just to close this
foreach (KeyValuePair<DateTime, string> kvp in dictionary)
{
//textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
Changes to this
foreach (KeyValuePair<DateTime, string> kvp in dictionary)
{
//textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
textBox3.Text += string.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
Because it's more common to call range(0, 10)
which returns [0,1,2,3,4,5,6,7,8,9]
which contains 10 elements which equals len(range(0, 10))
. Remember that programmers prefer 0-based indexing.
Also, consider the following common code snippet:
for i in range(len(li)):
pass
Could you see that if range()
went up to exactly len(li)
that this would be problematic? The programmer would need to explicitly subtract 1. This also follows the common trend of programmers preferring for(int i = 0; i < 10; i++)
over for(int i = 0; i <= 9; i++)
.
If you are calling range with a start of 1 frequently, you might want to define your own function:
>>> def range1(start, end):
... return range(start, end+1)
...
>>> range1(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
JPA is a layered API, the different levels have their own annotations. The highest level is the (1) Entity level which describes persistent classes then you have the (2) relational database level which assume the entities are mapped to a relational database and (3) the java model.
Level 1 annotations: @Entity
, @Id
, @OneToOne
, @OneToMany
, @ManyToOne
, @ManyToMany
.
You can introduce persistency in your application using these high level annotations alone. But then you have to create your database according to the assumptions JPA makes. These annotations specify the entity/relationship model.
Level 2 annotations: @Table
, @Column
, @JoinColumn
, ...
Influence the mapping from entities/properties to the relational database tables/columns if you are not satisfied with JPA's defaults or if you need to map to an existing database. These annotations can be seen as implementation annotations, they specify how the mapping should be done.
In my opinion it is best to stick as much as possible to the high level annotations and then introduce the lower level annotations as needed.
To answer the questions: the @OneToMany
/mappedBy
is nicest because it only uses the annotations from the entity domain. The @oneToMany
/@JoinColumn
is also fine but it uses an implementation annotation where this is not strictly necessary.
To anyone else having this particular issue. You have an ImageView
that you want to have a width of fill_parent
and a height scaled proportionately:
Add these two attributes to your ImageView
:
android:adjustViewBounds="true"
android:scaleType="centerCrop"
And set the ImageView
width to fill_parent
and height to wrap_content
.
Also, if you don't want your image to be cropped, try this:
android:adjustViewBounds="true"
android:layout_centerInParent="true"
var checkbox = $( "#checkbox" );
checkbox.val( checkbox[0].checked ? "true" : "false" );
This will set the value
of the checkbox to "true"
or "false"
(value property
is a string)
, depending whether it's unchecked
or checked
.
Works in jQuery >= 1.0
It can be as follows:
UPDATE A
SET A.`id` = (SELECT id from B WHERE A.title = B.title)
There's a -f option to umount that you can try:
umount -f /mnt/fileshare
Are you specifying the '-t cifs' option to mount? Also make sure you're not specifying the 'hard' option to mount.
You may also want to consider fusesmb, since the filesystem will be running in userspace you can kill it just like any other process.
Use loggers and print statements in the Development Environment, you can go for sentry in case of production environments.
df[df['B']==3]['A']
, assuming df is your pandas.DataFrame.
Not possible in Java.
Here's the Scala way:
val m = List(5, 4, 2, 89)
for((el, i) <- m.zipWithIndex)
println(el +" "+ i)
Not as a command, but this information is in the registry:
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
CurrentVersion
REG_SZJava Runtime Environment
named with the CurrentVersion
valueJavaHome
REG_SZ to get the pathFor example on my workstation i have
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
CurrentVersion = "1.6"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5
JavaHome = "C:\Program Files\Java\jre1.5.0_20"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6
JavaHome = "C:\Program Files\Java\jre6"
So my current JRE is in C:\Program Files\Java\jre6
You can actually handle all of this with just a simple template tag. See http://jsfiddle.net/m4ve9/ for an example. Note that I actually didn't need a compile or link property on the super-directive definition.
During the compilation process, Angular pulls in the template values before compiling, so you can attach any further directives there and Angular will take care of it for you.
If this is a super directive that needs to preserve the original internal content, you can use transclude : true
and replace the inside with <ng-transclude></ng-transclude>
Hope that helps, let me know if anything is unclear
Alex
you can do this with annotations like this
@Value("#{T(java.util.Arrays).asList('${my.list.of.strings:a,b,c}')}")
private List<String> mylist;
here my.list.of.strings will be picked from the properties file, if its not there, then the defaults a,b,c will be used
and in your properties file, you can have something like this
my.list.of.strings=d,e,f
For the following, All I had to do was navigate to the current project solution directory > .vs > config to delete applicationhost.config, then restart VS and run as usual without problem.
.vs is a hidden folder
I had the same problem with python3 and pip3. Decision: solving all conflicts with links and other stuff when do
brew doctor
After that
brew reinstall python3
Given a list:
var list = new List<Child>()
{
new Child()
{School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "John"},
new Child()
{School = "School2", FavoriteColor = "blue", Friend = "Bob", Name = "Pete"},
new Child()
{School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "Fred"},
new Child()
{School = "School2", FavoriteColor = "blue", Friend = "Fred", Name = "Bob"},
};
The query would look like:
var newList = list
.GroupBy(x => new {x.School, x.Friend, x.FavoriteColor})
.Select(y => new ConsolidatedChild()
{
FavoriteColor = y.Key.FavoriteColor,
Friend = y.Key.Friend,
School = y.Key.School,
Children = y.ToList()
}
);
Test code:
foreach(var item in newList)
{
Console.WriteLine("School: {0} FavouriteColor: {1} Friend: {2}", item.School,item.FavoriteColor,item.Friend);
foreach(var child in item.Children)
{
Console.WriteLine("\t Name: {0}", child.Name);
}
}
Result:
School: School1 FavouriteColor: blue Friend: Bob
Name: John
Name: Fred
School: School2 FavouriteColor: blue Friend: Bob
Name: Pete
School: School2 FavouriteColor: blue Friend: Fred
Name: Bob
Since the behavior is kind of strange, I have done some testing on the behavior, and here's my result:
If you are:
form
, andonclick="xxx()"
on an elementid="xxx"
or name="xxx"
to that element
Here's are some test and their result:
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
<button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
<button id="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
<button name="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
<input type="button" value="totalbandwidth" onclick="totalbandwidth()" />SUCCESS
</form>
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<button id="totalbandwidth" onclick="totalbandwidth()">SUCCESS</button>
_x000D_
function totalbandwidth(){ alert("The answer is no, the span will not affect button"); }
_x000D_
<form onsubmit="return false;">
<span name="totalbandwidth" >Will this span affect button? </span>
<button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
If you mean "change workspace" go to File -> Switch Workspace
This worked for me:
.dropdown, .dropdown-menu {
z-index:2;
}
.navbar {
position: static;
z-index: 1;
}
This should do the trick:
<table width="400" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="50" height="40" valign="top" rowspan="3">
<img alt="" src="" width="40" height="40" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
<td width="350" height="40" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">LAST FIRST</a><br>
REALTOR | P 123.456.789
</td>
</tr>
<tr>
<td width="350" height="70" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="" src="" width="200" height="60" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
</tr>
<tr>
<td width="350" height="20" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
</td>
</tr>
</table>
UPDATE: Adjusted code per the comments:
After viewing your jsFiddle, an important thing to note about tables is that table cell widths in each additional row all have to be the same width as the first, and all cells must add to the total width of your table.
Here is an example that will NOT WORK:
<table width="600" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="200" bgcolor="#252525">
</td>
<td width="400" bgcolor="#454545">
</td>
</tr>
<tr>
<td width="300" bgcolor="#252525">
</td>
<td width="300" bgcolor="#454545">
</td>
</tr>
</table>
Although the 2nd row does add up to 600, it (and any additional rows) must have the same 200-400 split as the first row, unless you are using colspans. If you use a colspan, you could have one row, but it needs to have the same width as the cells it is spanning, so this works:
<table width="600" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="200" bgcolor="#252525">
</td>
<td width="400" bgcolor="#454545">
</td>
</tr>
<tr>
<td width="600" colspan="2" bgcolor="#353535">
</td>
</tr>
</table>
Not a full tutorial, but I hope that helps steer you in the right direction in the future.
Here is the code you are after:
<table width="900" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="57" height="43" valign="top" rowspan="2">
<img alt="Rashel Adragna" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_head.png" width="47" height="43" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
<td width="843" height="43" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">RASHEL ADRAGNA</a><br>
REALTOR | P 855.900.24KW
</td>
</tr>
<tr>
<td width="843" height="64" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="Zopa Realty Group logo" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_logo.png" width="177" height="54" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
</tr>
<tr>
<td width="843" colspan="2" height="20" valign="bottom" align="center" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
</td>
</tr>
</table>
You'll note that I've added an extra 10px to some of your table cells. This in combination with align/valigns act as padding between your cells. It is a clever way to aviod actually having to add padding, margins or empty padding cells.
try
std::fill
and also
std::size siz = vec.size();
//no memory allocating
vec.resize(0);
vec.resize(siz, 0);
As stated in an article by Slicehost:
User setup
So let's start by adding the main user to the Apache user group:
sudo usermod -a -G www-data demo
That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.
You will need to log out and log back in again to enable the group change.
Check the groups now:
groups ... # demo www-data
So now I am a member of two groups: My own (demo) and the Apache group (www-data).
Folder setup
Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).
Let's set that up:
sudo chgrp -R www-data /home/demo/public_html
As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.
If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.
Setgid
Good so far, but remember the command we just gave only affects existing folders. What about anything new?
We can set the ownership so anything new is also in the 'www-data' group.
The first command will change the permissions for the public_html directory to include the "setgid" bit:
sudo chmod 2750 /home/demo/public_html
That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.
If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:
sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads
The permissions only need to be set once as new files will automatically be assigned the correct ownership.
You can manual disable ssl verfiy, and try again. :)
git config --global http.sslverify false
keyboardType: TextInputType.number
would open a num pad on focus, I would clear the text field when the user enters/past anything else.
keyboardType: TextInputType.number,
onChanged: (String newVal) {
if(!isNumber(newVal)) {
editingController.clear();
}
}
// Function to validate the number
bool isNumber(String value) {
if(value == null) {
return true;
}
final n = num.tryParse(value);
return n!= null;
}
Something that is now available in maven as well is
mvn goal --no-snapshot-updates
or in short
mvn goal -nsu
You can use the expression pipeline to achieve this:
public static Func<object, object> Caster(Type type)
{
var inputObject = Expression.Parameter(typeof(object));
return Expression.Lambda<Func<object,object>>(Expression.Convert(inputObject, type), inputPara).Compile();
}
which you can invoke like:
object objAsDesiredType = Caster(desiredType)(obj);
Drawbacks: The compilation of this lambda is slower than nearly all other methods mentioned already
Advantages: You can cache the lambda, then this should be actually the fastest method, it is identical to handwritten code at compile time
Just pick up the TDM-GCC 64x package. (It constains both the 32 and 64 bit versions of the MinGW toolchain and comes within a neat installer.) More importantly, it contains something called the "winpthread" library.
It comprises of the pthread.h
header, libwinpthread.a
, libwinpthread.dll.a
static libraries for both 32-bit and 64-bit and the required .dlls libwinpthread-1.dll
and libwinpthread_64-1.dll
(this, as of 01-06-2016).
You'll need to link to the libwinpthread.a
library during build. Other than that, your code can be the same as for native Pthread code on Linux. I've so far successfully used it to compile a few basic Pthread programs in 64-bit on windows.
Alternatively, you can use the following library which wraps the windows threading API into the pthreads API: pthreads-win32.
The above two seem to be the most well known ways for this.
Hope this helps.
Solution for WebForms UpdatePanel:
Add a setting to Web.config:
<configuration>
<appSettings>
<add key="aspnet:UpdatePanelMaxScriptLength" value="2147483647" />
</appSettings>
</configuration>
https://support.microsoft.com/en-us/kb/981884
ScriptRegistrationManager
class contains following code:
// Serialize the attributes to JSON and write them out
JavaScriptSerializer serializer = new JavaScriptSerializer();
// Dev10# 877767 - Allow configurable UpdatePanel script block length
// The default is JavaScriptSerializer.DefaultMaxJsonLength
if (AppSettings.UpdatePanelMaxScriptLength > 0) {
serializer.MaxJsonLength = AppSettings.UpdatePanelMaxScriptLength;
}
string attrText = serializer.Serialize(attrs);
You need to tell npm that "tsc" exists as a local project package (via the "scripts" property in your package.json) and then run it via npm run tsc
. To do that (at least on Mac) I had to add the path for the actual compiler within the package, like this
{
"name": "foo"
"scripts": {
"tsc": "./node_modules/typescript/bin/tsc"
},
"dependencies": {
"typescript": "^2.3.3",
"typings": "^2.1.1"
}
}
After that you can run any TypeScript command like npm run tsc -- --init
(the arguments come after the first --
).
In my case, I changed the android section in build.gradle
and the problem faded away:
android {
compileSdkVersion 28
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "app.ozel"
minSdkVersion 16
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}
If you use maven and this piece of code is located in the main
folder, try relocating it to the test
folder.
You can manually place a check in your code. Like this -
if result != []:
for face in result:
bounding_box = face['box']
x, y, w, h = bounding_box[0], bounding_box[1], bounding_box[2], bounding_box[3]
rect_face = cv2.rectangle(frame, (x, y), (x+w, y+h), (46, 204, 113), 2)
face = rgb[y:y+h, x:x+w]
#CHECK FACE SIZE (EXIST OR NOT)
if face.shape[0]*face.shape[1] > 0:
predicted_name, class_probability = face_recognition(face)
print("Result: ", predicted_name, class_probability)
`
I think you want the selected item of the spinner when button is clicked..
Try getSelectedItem():
spinner.getSelectedItem()
You need convert list
to numpy array
and then reshape
:
df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
a b c
0 1 2 3
1 4 5 6
2 7 8 9
You can do like this basically:
int[] ints = new[] { 10, 20, 10, 34, 113 };
this is your array, and than you can call your new list like this:
var newList = new List<int>(ints);
You can do this for complex object too.
If your parameter value is not fixed or your value can be null based on business you can try the following approach.
DECLARE @DrugClassstring VARCHAR(MAX);
SET @DrugClassstring = 'C3,C2'; -- You can pass null also
---------------------------------------------
IF @DrugClassstring IS NULL
SET @DrugClassstring = 'C3,C2,C4,C5,RX,OT'; -- If null you can set your all conditional case that will return for all
SELECT dn.drugclass_FK , dn.cdrugname
FROM drugname AS dn
INNER JOIN dbo.SplitString(@DrugClassstring, ',') class ON dn.drugclass_FK = class.[Name] -- SplitString is a a function
SplitString function
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
ALTER FUNCTION [dbo].[SplitString](@stringToSplit VARCHAR(MAX),
@delimeter CHAR(1) = ',')
RETURNS @returnList TABLE([Name] [NVARCHAR](500))
AS
BEGIN
--It's use in report sql, before any change concern to everyone
DECLARE @name NVARCHAR(255);
DECLARE @pos INT;
WHILE CHARINDEX(@delimeter, @stringToSplit) > 0
BEGIN
SELECT @pos = CHARINDEX(@delimeter, @stringToSplit);
SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1);
INSERT INTO @returnList
SELECT @name;
SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos);
END;
INSERT INTO @returnList
SELECT @stringToSplit;
RETURN;
END;
In Addition to the above answers, there probably should be noted that there is a legacy way to implement the initialization. There is an interface called Initializable from the fxml library.
import javafx.fxml.Initializable;
class MyController implements Initializable {
@FXML private TableView<MyModel> tableView;
@Override
public void initialize(URL location, ResourceBundle resources) {
tableView.getItems().addAll(getDataFromSource());
}
}
Parameters:
location - The location used to resolve relative paths for the root object, or null if the location is not known.
resources - The resources used to localize the root object, or null if the root object was not localized.
And the note of the docs why the simple way of using @FXML public void initialize()
works:
NOTE
This interface has been superseded by automatic injection of location and resources properties into the controller. FXMLLoader will now automatically call any suitably annotated no-arg initialize() method defined by the controller. It is recommended that the injection approach be used whenever possible.
Presuming you're talking about dynamic runtime loading of DLLs, you're looking for LoadLibrary and GetProAddress. There's an example on MSDN.
Use ROW_NUMBER()
instead. ROWNUM
is a pseudocolumn and ROW_NUMBER()
is a function. You can read about difference between them and see the difference in output of below queries:
SELECT * FROM (SELECT rownum, deptno, ename
FROM scott.emp
ORDER BY deptno
)
WHERE rownum <= 3
/
ROWNUM DEPTNO ENAME
---------------------------
7 10 CLARK
14 10 MILLER
9 10 KING
SELECT * FROM
(
SELECT deptno, ename
, ROW_NUMBER() OVER (ORDER BY deptno) rno
FROM scott.emp
ORDER BY deptno
)
WHERE rno <= 3
/
DEPTNO ENAME RNO
-------------------------
10 CLARK 1
10 MILLER 2
10 KING 3
You like to set charset and unescaped unicode
header('Content-Type: application/json;charset=utf-8');
json_encode($data,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
In TCP there is only one way to detect an orderly disconnect, and that is by getting zero as a return value from read()/recv()/recvXXX()
when reading.
There is also only one reliable way to detect a broken connection: by writing to it. After enough writes to a broken connection, TCP will have done enough retries and timeouts to know that it's broken and will eventually cause write()/send()/sendXXX()
to return -1 with an errno/WSAGetLastError()
value of ECONNRESET,
or in some cases 'connection timed out'. Note that the latter is different from 'connect timeout', which can occur in the connect phase.
You should also set a reasonable read timeout, and drop connections that fail it.
The answer here about ioctl()
and FIONREAD
is compete nonsense. All that does is tell you how many bytes are presently in the socket receive buffer, available to be read without blocking. If a client doesn't send you anything for five minutes that doesn't constitute a disconnect, but it does cause FIONREAD
to be zero. Not the same thing: not even close.
Someone here has just suggested sudoing tee:
sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null
This could also be used to redirect any command, to a directory that you do not have access to. It works because the tee program is effectively an "echo to a file" program, and the redirect to /dev/null is to stop it also outputting to the screen to keep it the same as the original contrived example above.
wait until this call is finish its executing
You will need to call AsyncTask.get() method for getting result back and make wait until doInBackground
execution is not complete. but this will freeze Main UI thread if you not call get method inside a Thread.
To get result back in UI Thread start AsyncTask
as :
String str_result= new RunInBackGround().execute().get();
try this:
var result = from r in myDataTable.AsEnumerable()
where r.Field<string>("Name") != "n/a" &&
r.Field<string>("Name") != "" select r;
DataTable dtResult = result.CopyToDataTable();
Yes, you can delete data from iOS device support by the symbols of the operating system, one for each version for each architecture. It's used for debugging. If you don't need to support those devices any more, you can delete the directory without ill effect
Hey, I just needed such a trick - I solved it in a different way, maybe it'll work for you. Note this is not a scalable solution and will be very bad for large data sets.
Split your query into two parts -
first, select the ids of the rows you want to update and store them in a temporary table.
secondly, do the original update with the condition in the update statement changed to where id in temp_table
.
And to ensure concurrency, you need to lock the table before this two steps and then release the lock at the end.
Again, this works for me, for a query which ends with limit 1
, so I don't even use a temp table, but instead simply a variable to store the result of the first select
.
I prefer this method since I know I will always update only one row, and the code is straightforward.
SET
SET @var_name = value
OR
SET @var := value
both operators = and := are accepted
SELECT
SELECT col1, @var_name := col2 from tb_name WHERE "conditon";
if multiple record sets found only the last value in col2 is keep (override);
SELECT col1, col2 INTO @var_name, col3 FROM .....
in this case the result of select is not containing col2 values
Ex both methods used
-- TRIGGER_BEFORE_INSERT --- setting a column value from calculations
...
SELECT count(*) INTO @NR FROM a_table WHERE a_condition;
SET NEW.ord_col = IFNULL( @NR, 0 ) + 1;
...
function getIntersection(arr1, arr2){
var result = [];
arr1.forEach(function(elem){
arr2.forEach(function(elem2){
if(elem === elem2){
result.push(elem);
}
});
});
return result;
}
getIntersection([1,2,3], [2,3,4,5]); // [ 2, 3 ]
#include <algorithm> // std::search
#include <string>
using std::search; using std::count; using std::string;
int main() {
string mystring = "The needle in the haystack";
string str = "needle";
string::const_iterator it;
it = search(mystring.begin(), mystring.end(),
str.begin(), str.end()) != mystring.end();
// if string is found... returns iterator to str's first element in mystring
// if string is not found... returns iterator to mystring.end()
if (it != mystring.end())
// string is found
else
// not found
return 0;
}
Here is another suggestion. If you can prepend http:// to your url string you can do this
string path = "http://www.example.com/aaa/bbb.jpg";
Uri uri = new Uri(path);
string expectedString =
uri.PathAndQuery.Remove(uri.PathAndQuery.LastIndexOf("."));
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Uploader</title>
<script src="../Script/angular1.3.8.js"></script>
<script src="../Script/angular-route.js"></script>
<script src="../UserScript/MyApp.js"></script>
<script src="../UserScript/FileUploder.js"></script>
<>
.percent {
position: absolute;
width: 300px;
height: 14px;
z-index: 1;
text-align: center;
font-size: 0.8em;
color: white;
}
.progress-bar {
width: 300px;
height: 14px;
border-radius: 10px;
border: 1px solid #CCC;
background-image: -webkit-gradient(linear, left top, left bottom, from(#6666cc), to(#4b4b95));
border-image: initial;
}
.uploaded {
padding: 0;
height: 14px;
border-radius: 10px;
background-image: -webkit-gradient(linear, left top, left bottom, from(#66cc00), to(#4b9500));
border-image: initial;
}
</>
</head>
<body ng-app="MyApp" ng-controller="FileUploder">
<div>
<table ="width:100%;border:solid;">
<tr>
<td>Select File</td>
<td>
<input type="file" ng-model-instant id="fileToUpload" onchange="angular.element(this).scope().setFiles(this)" />
</td>
</tr>
<tr>
<td>File Size</td>
<td>
<div ng-repeat="file in files.slice(0)">
<span ng-switch="file.size > 1024*1024">
<span ng-switch-when="true">{{file.size / 1024 / 1024 | number:2}} MB</span>
<span ng-switch-default>{{file.size / 1024 | number:2}} kB</span>
</span>
</div>
</td>
</tr>
<tr>
<td>
File Attach Status
</td>
<td>{{AttachStatus}}</td>
</tr>
<tr>
<td>
<input type="button" value="Upload" ng-click="fnUpload();" />
</td>
<td>
<input type="button" value="DownLoad" ng-click="fnDownLoad();" />
</td>
</tr>
</table>
</div>
</body>
</html>
If you find yourself writing the above solution as often as I do then you could implement it as a generic:
public static int GetEnumEntries<T>() where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
throw new ArgumentException("T must be an enumerated type");
return Enum.GetNames(typeof(T)).Length;
}
I think the issue is here:
<template id="newtemp" :name ="{{user.name}}">
When you prefix the prop with :
you are indicating to Vue that it is a variable, not a string. So you don't need the {{}}
around user.name
. Try:
<template id="newtemp" :name ="user.name">
EDIT-----
The above is true, but the bigger issue here is that when you change the URL and go to a new route, the original component disappears. In order to have the second component edit the parent data, the second component would need to be a child component of the first one, or just a part of the same component.
First import these libraries
import AVFoundation
import AudioToolbox
set delegate like this
AVAudioPlayerDelegate
write this pretty code on button action or something action:
guard let url = Bundle.main.url(forResource: "ring", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
guard let player = player else { return }
player.play()
}catch let error{
print(error.localizedDescription)
}
100% working in my project and tested
If you have Powershell remoting and CredSSP setup then you can update your code to the following:
$Session = New-PSSession -ComputerName $Computer1 -Authentication CredSSP
$NetbackupVersion1 = Invoke-Command -Session $Session -ScriptBlock { $(Get-ItemProperty hklm:\SOFTWARE\Veritas\NetBackup\CurrentVersion).PackageVersion}
Remove-PSSession $Session
Try this :
Create anim folder inside your res folder and copy this four files :
slide_in_bottom.xml :
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="100%p"
android:duration="@android:integer/config_longAnimTime"/>
slide_out_bottom.xml :
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="0"
android:duration="@android:integer/config_longAnimTime" />
slide_in_top.xml :
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:toYDelta="0%p"
android:duration="@android:integer/config_longAnimTime" />
slide_out_top.xml :
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:toYDelta="100%p"
android:duration="@android:integer/config_longAnimTime" />
When you click on image view call:
overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom);
When you click on original place call:
overridePendingTransition(R.anim.slide_in_top, R.anim.slide_out_top);
Main Activity :
package com.example.animationtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, test.class));
}
});
}
}
activity_main.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
</LinearLayout>
test.java :
package com.example.animationtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class test extends Activity {
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
btn1 = (Button) findViewById(R.id.btn1);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_out_right);
startActivity(new Intent(test.this, MainActivity.class));
}
});
}
}
test.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
</LinearLayout>
Hope this helps.
Here is a code to draw a fill elipse, you can use the same method but replacing de xcenter and y center with radius
void drawFilledelipse(GLfloat x, GLfloat y, GLfloat xcenter,GLfloat ycenter) {
int i;
int triangleAmount = 20; //# of triangles used to draw circle
//GLfloat radius = 0.8f; //radius
GLfloat twicePi = 2.0f * PI;
glBegin(GL_TRIANGLE_FAN);
glVertex2f(x, y); // center of circle
for (i = 0; i <= triangleAmount; i++) {
glVertex2f(
x + ((xcenter+1)* cos(i * twicePi / triangleAmount)),
y + ((ycenter-1)* sin(i * twicePi / triangleAmount))
);
}
glEnd();
}
import re
if re.search('(?i)Mandy Pande:', line):
...
If you work with generics, use List instead of ArrayList. The List has exactly the GetEnumerator method you need.
List<MyObject> myList = new List<MyObject>();
You can try this from the console:
adb logcat --buffer=crash
More info on this option:
adb logcat --help
...
-b <buffer>, --buffer=<buffer> Request alternate ring buffer, 'main',
'system', 'radio', 'events', 'crash', 'default' or 'all'.
Multiple -b parameters or comma separated list of buffers are
allowed. Buffers interleaved. Default -b main,system,crash.
I just wanted to extend Alex's great answer to make it appropriate if you happen to want to duplicate an entire set of records:
SET @x=7;
CREATE TEMPORARY TABLE tmp SELECT * FROM invoices;
UPDATE tmp SET id=id+@x;
INSERT INTO invoices SELECT * FROM tmp;
I just had to do this and found Alex's answer a perfect jumping off point!. Of course, you have to set @x to the highest row number in the table (I'm sure you could grab that with a query). This is only useful in this very specific situation, so be careful using it when you don't wish to duplicate all rows. Adjust the math as necessary.
I recently ran into similar issues, and this is what worked for me.
If the variable is numeric, then a simple df$Var[df$Var == ""] <- NA
should suffice. But if the variable is a factor, then you need to convert it to the character first, then replace ""
cells with the value you want, and convert it back to factor. So case in point, your Sex
variable, I assume it would be a factor and if you want to replace the empty cell, I would do the following:
df$Var <- as.character(df$Var)
df$Var[df$Var==""] <- NA
df$Var <- as.factor(df$Var)
Actually we can not create an object of an abstract class directly. What we create is a reference variable of an abstract call. The reference variable is used to Refer to the object of the class which inherits the Abstract class i.e. the subclass of the abstract class.
With Ctrl + Shift + L you can open the "key assist", where you can find all the shortcuts.
It can be something as simple as typing the package name in the wrong case...
I had the same problem - turned out I was entering the package name in all lower case when the actual package name included upper case characters.
adb uninstall -k <packageName - eg. com.test.app>
( If you're explicitly uninstalling you probably don't want the -k which keeps the app data and cache directories around. )
Create an extension method?
Console.WriteLine(value.ToGBString());
// ...
public static class DoubleExtensions
{
public static string ToGBString(this double value)
{
return value.ToString(CultureInfo.GetCultureInfo("en-GB"));
}
}
You can reset your branch to the state it was in just before the merge if you find the commit it was on then.
One way is to use git reflog
, it will list all the HEADs you've had.
I find that git reflog --relative-date
is very useful as it shows how long ago each change happened.
Once you find that commit just do a git reset --hard <commit id>
and your branch will be as it was before.
If you have SourceTree, you can look up the <commit id>
there if git reflog
is too overwhelming.
When using LINQ extension methods (e.g. Select
, Where
), the lambda function might be converted to SQL that might not behave identically to your C# code. For instance, C#'s short-circuit evaluated &&
and ||
are converted to SQL's eager AND
and OR
. This can cause problems when you're checking for null in your lambda.
Example:
MyEnum? type = null;
Entities.Table.Where(a => type == null ||
a.type == (int)type).ToArray(); // Exception: Nullable object must have a value
I have found this problem across all objects (buttons,text boxes,etc). When I print/print preview multiple sheets, all the sheets except for the first in the sequence have moved or resized objects. After much testing, the simplest solution in to page zoom up or down and return to the original setting.
Use a GET request to download the image and save it to a web accessible directory on your server.
As you are using PHP, you can use curl
to download files from the other server.
This can also occur if you do something stupid (like I did) and place the api url in the "Project Url" (e.g. http://localhost:59088/api/Product) on the Project Properties->Web tab instead of specifying it in the "Specific Page" text box. This causes Visual Studio to go ahead and create an APP called ProjectName/api/Product, and this will expect a default page. The only way to undo this is to go to C:\Program Files (x86)\IIS Express and use appcmd.exe to delete it like so
>.\appcmd.exe delete APP "ProjectName/api/Product"
Passing user input to eval() is a security risk, but also each invocation of eval() creates a new instance of the JavaScript interpreter. This can be a resource hog.
I am using this and it is working fine.
{{1288323623006 | date:'medium'}}: Oct 29, 2010 9:10:23 AM
{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}: 2010-10-29 09:10:23 +0530
{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}: 10/29/2010 @ 9:10AM
{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}: 10/29/2010 at 9:10AM
Okay, first things first.
There is no such thing as "variable declaration" or "variable initialization" in Python.
There is simply what we call "assignment", but should probably just call "naming".
Assignment means "this name on the left-hand side now refers to the result of evaluating the right-hand side, regardless of what it referred to before (if anything)".
foo = 'bar' # the name 'foo' is now a name for the string 'bar'
foo = 2 * 3 # the name 'foo' stops being a name for the string 'bar',
# and starts being a name for the integer 6, resulting from the multiplication
As such, Python's names (a better term than "variables", arguably) don't have associated types; the values do. You can re-apply the same name to anything regardless of its type, but the thing still has behaviour that's dependent upon its type. The name is simply a way to refer to the value (object). This answers your second question: You don't create variables to hold a custom type. You don't create variables to hold any particular type. You don't "create" variables at all. You give names to objects.
Second point: Python follows a very simple rule when it comes to classes, that is actually much more consistent than what languages like Java, C++ and C# do: everything declared inside the class
block is part of the class. So, functions (def
) written here are methods, i.e. part of the class object (not stored on a per-instance basis), just like in Java, C++ and C#; but other names here are also part of the class. Again, the names are just names, and they don't have associated types, and functions are objects too in Python. Thus:
class Example:
data = 42
def method(self): pass
Classes are objects too, in Python.
So now we have created an object named Example
, which represents the class of all things that are Example
s. This object has two user-supplied attributes (In C++, "members"; in C#, "fields or properties or methods"; in Java, "fields or methods"). One of them is named data
, and it stores the integer value 42
. The other is named method
, and it stores a function object. (There are several more attributes that Python adds automatically.)
These attributes still aren't really part of the object, though. Fundamentally, an object is just a bundle of more names (the attribute names), until you get down to things that can't be divided up any more. Thus, values can be shared between different instances of a class, or even between objects of different classes, if you deliberately set that up.
Let's create an instance:
x = Example()
Now we have a separate object named x
, which is an instance of Example
. The data
and method
are not actually part of the object, but we can still look them up via x
because of some magic that Python does behind the scenes. When we look up method
, in particular, we will instead get a "bound method" (when we call it, x
gets passed automatically as the self
parameter, which cannot happen if we look up Example.method
directly).
What happens when we try to use x.data
?
When we examine it, it's looked up in the object first. If it's not found in the object, Python looks in the class.
However, when we assign to x.data
, Python will create an attribute on the object. It will not replace the class' attribute.
This allows us to do object initialization. Python will automatically call the class' __init__
method on new instances when they are created, if present. In this method, we can simply assign to attributes to set initial values for that attribute on each object:
class Example:
name = "Ignored"
def __init__(self, name):
self.name = name
# rest as before
Now we must specify a name
when we create an Example
, and each instance has its own name
. Python will ignore the class attribute Example.name
whenever we look up the .name
of an instance, because the instance's attribute will be found first.
One last caveat: modification (mutation) and assignment are different things!
In Python, strings are immutable. They cannot be modified. When you do:
a = 'hi '
b = a
a += 'mom'
You do not change the original 'hi ' string. That is impossible in Python. Instead, you create a new string 'hi mom'
, and cause a
to stop being a name for 'hi '
, and start being a name for 'hi mom'
instead. We made b
a name for 'hi '
as well, and after re-applying the a
name, b
is still a name for 'hi '
, because 'hi '
still exists and has not been changed.
But lists can be changed:
a = [1, 2, 3]
b = a
a += [4]
Now b
is [1, 2, 3, 4] as well, because we made b
a name for the same thing that a
named, and then we changed that thing. We did not create a new list for a
to name, because Python simply treats +=
differently for lists.
This matters for objects because if you had a list as a class attribute, and used an instance to modify the list, then the change would be "seen" in all other instances. This is because (a) the data is actually part of the class object, and not any instance object; (b) because you were modifying the list and not doing a simple assignment, you did not create a new instance attribute hiding the class attribute.
Since I don't find a simple answer just adding more this will be JSP page. save this content to a jsp file once you run you can see the values of the selected displayed.
Update: save the file as test.jsp and run it on any web/app server
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<%@ page import="java.lang.*" %>
<%@ page import="java.io.*" %>
<% String[] a = request.getParameterValues("multiple");
if(a!=null)
{
for(int i=0;i<a.length;i++){
//out.println(Integer.parseInt(a[i])); //If integer
out.println(a[i]);
}}
%>
<html>
<body>
<form action="test.jsp" method="get">
<select name="multiple" multiple="multiple"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>
<input type="submit">
</form>
</body>
</html>
After installing php5-gd
apache restart is needed.
I will explain you this with a practical example and no theory stuff:
A developer writes the code. No GUI is implemented yet. The testing at this level verifies that the functions work correctly and the data types are correct. This phase of testing is called Unit testing.
When a GUI is developed, and application is assigned to a tester, he verifies business requirements with a client and executes the different scenarios. This is called functional testing. Here we are mapping the client requirements with application flows.
Integration testing: let's say our application has two modules: HR and Finance. HR module was delivered and tested previously. Now Finance is developed and is available to test. The interdependent features are also available now, so in this phase, you will test communication points between the two and will verify they are working as requested in requirements.
Regression testing is another important phase, which is done after any new development or bug fixes. Its aim is to verify previously working functions.
SELECT StoreId
FROM StoreClients
WHERE StoreId NOT IN (
SELECT StoreId
FROM StoreClients
Where ClientId=5
)
If you have the IDs stored in a temp table (which can be done by some C# function or simple SQL) then the problem becomes easy and doable in SQL.
select "all exist"
where (select case when count(distinct t.id) = (select count(distinct id) from #products) then "true" else "false" end
from ProductTable t, #products p
where t.id = p.id) = "true"
This will return "all exists" when all the products in #products
exist in the target table (ProductTable
) and will not return a row if the above is not true.
If you are not willing to write to a temp table, then you need to feed in some parameter for the number of products you are attempting to find, and replace the temp table with an 'in'; clause so the subquery looks like this:
SELECT "All Exist"
WHERE(
SELECT case when count(distinct t.id) = @ProductCount then "true" else "false"
FROM ProductTable t
WHERE t.id in (1,100,10,20) -- example IDs
) = "true"
I used "save as" to copy the sheet to a new file as msdos text format. Doing this removes the formulas, replacing the cell contents with just the computed values. Then open the new file as tab delimited and sort after defining the columns. I needed to sort computed values by an associated text string (destination) for mileage log so that I could sum up the mileage for each destination.
date beginning ending distance destination
where in row 2 and successive rows beginning was the previous row ending and distance was ending minus beginning.
You can also have different urls for apps in one server configuration:
In /etc/nginx/sites-enabled/yourdomain:
server {
listen 80;
listen [::]:80;
server_name yourdomain.com;
location ^~ /app1/{
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://127.0.0.1:3000/;
}
location ^~ /app2/{
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://127.0.0.1:4000/;
}
}
Restart nginx:
sudo service nginx restart
Starting applications.
node app1.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello from app1!\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');
node app2.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello from app2!\n');
}).listen(4000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:4000/');
The following code assumes that your table has the ID 'MyTable'
<script language="JavaScript"> <!-- var oRows = document.getElementById('MyTable').getElementsByTagName('tr'); var iRowCount = oRows.length; alert('Your table has ' + iRowCount + ' rows.'); //--> </script>
Answer taken from : http://www.delphifaq.com/faq/f771.shtml, which is the first result on google for the query : "Get the number of rows in a HTML table" ;)
#!/bin/bash
file_location=/home/test/$1.json
if [ -e $policy ]; then
echo "File $1.json already exists!"
else
cat > $file_location <<EOF
{
"contact": {
"name": "xyz",
"phonenumber": "xxx-xxx-xxxx"
}
}
EOF
fi
This code checks if the given JSON file of the user is present in test home directory or not. If it's not present it will create it with the content. You can modify the file location and content according to your needs.
You just use this: if not exist "C:\VTS\" mkdir C:\VTS
it wll create a directory only if the folder does not exist.
Note that this existence test will return true only if VTS exists and is a directory. If it is not there, or is there as a file, the mkdir command will run, and should cause an error. You might want to check for whether VTS exists as a file as well.
Using join Another variation is to use join. Now the query could look like:
SELECT a.id, a.value, SUM(b.Value)FROM RunTotalTestData a,
RunTotalTestData b
WHERE b.id <= a.id
GROUP BY a.id, a.value
ORDER BY a.id;
for more you can visite this link http://askme.indianyouth.info/details/calculating-simple-running-totals-in-sql-server-12
Try this:
.circle {
height: 20px;
width: 20px;
padding: 5px;
text-align: center;
border-radius: 50%;
display: inline-block;
color:#fff;
font-size:1.1em;
font-weight:600;
background-color: rgba(0,0,0,0.1);
border: 1px solid rgba(0,0,0,0.2);
}
I'd just add that you don't need to implement a controller method for that as you can use the view-controller tag (Spring 3) in the servlet configuration file:
<mvc:view-controller path="/" view-name="/WEB-INF/jsp/index.html"/>
Please try as below to get the time difference in hh:mm:ss format
Select StartTime, EndTime, CAST((EndTime - StartTime) as time(0)) 'TotalTime' from [TableName]
With VLC i'm able to transcode a live RTSP stream (mpeg4) to an HTTP stream in a OGG format (Vorbis/Theora). The quality is poor but the video work in Chrome 9. I have also tested with a trancoding in WEBM (VP8) but it's don't seem to work (VLC have the option but i don't know if it's really implemented for now..)
The first to have a doc on this should notify us ;)
For Win32 DOS, you can:
c:> dir /s c:\directory\you\want
and the penultimate line will tell you how many bytes the files take up.
I know this reads all files and directories, but works faster in some situations.
Two ways.
i. You can put it in ApplicationController and add the filters in the controller
class ApplicationController < ActionController::Base def filter_method end end class FirstController < ApplicationController before_filter :filter_method end class SecondController < ApplicationController before_filter :filter_method end
But the problem here is that this method will be added to all the controllers since all of them extend from application controller
ii. Create a parent controller and define it there
class ParentController < ApplicationController def filter_method end end class FirstController < ParentController before_filter :filter_method end class SecondController < ParentController before_filter :filter_method end
I have named it as parent controller but you can come up with a name that fits your situation properly.
You can also define the filter method in a module and include it in the controllers where you need the filter
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!
=VLOOKUP(A2,IF(B1:B3="B",A1:C3,""),1,FALSE)
Ctrl+Shift+Enter
to enter.
Possibly too late to be of benefit now, but is this not the easiest way to do things?
SELECT empName, projIDs = replace
((SELECT Surname AS [data()]
FROM project_members
WHERE empName = a.empName
ORDER BY empName FOR xml path('')), ' ', REQUIRED SEPERATOR)
FROM project_members a
WHERE empName IS NOT NULL
GROUP BY empName
This blog explains your problem neatly Async Best Practices.
The gist of it being you shouldn't use void as return for an async method, unless it's an async event handler, this is bad practice because it doesn't allow exceptions to be caught ;-).
Best practice would be to change the return type to Task. Also, try to code async all the way trough, make every async method call and be called from async methods. Except for a Main method in a console, which can't be async (before C# 7.1).
You will run into deadlocks with GUI and ASP.NET applications if you ignore this best practice. The deadlock occurs because these applications runs on a context that allows only one thread and won't relinquish it to the async thread. This means the GUI waits synchronously for a return, while the async method waits for the context: deadlock.
This behaviour won't happen in a console application, because it runs on context with a thread pool. The async method will return on another thread which will be scheduled. This is why a test console app will work, but the same calls will deadlock in other applications...
Use onclick="foo(document.getElementById('formValueId').value)"
As Draemon says, the closest that Java comes to inline arrays is new String[]{"blah", "hey", "yo"}
however there is a neat trick that allows you to do something like
array("blah", "hey", "yo")
with the type automatically inferred.
I have been working on a useful API for augmenting the Java language to allow for inline arrays and collection types. For more details google project Espresso4J or check it out here
From other stackoverflow thread:
"Second. Make sure that you have MySQL JDBC Driver aka Connector/J in JMeter's classpath. If you don't - download it, unpack and drop mysql-connector-java-x.xx.xx-bin.jar to JMeter's /lib folder. JMeter restart will be required to pick the library up"
Please be sure that .jar file is added directly to the lib folder.
ax.set_title()
should set the titles for separate subplots:
import matplotlib.pyplot as plt
if __name__ == "__main__":
data = [1, 2, 3, 4, 5]
fig = plt.figure()
fig.suptitle("Title for whole figure", fontsize=16)
ax = plt.subplot("211")
ax.set_title("Title for first plot")
ax.plot(data)
ax = plt.subplot("212")
ax.set_title("Title for second plot")
ax.plot(data)
plt.show()
Can you check if this code works for you? Maybe something overwrites them later?
I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.
Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.
If you are using Kotlin and Kotlin android extensions, then there is a beautiful way of doing this.
val uri = myUriString.toUri()
To add Kotlin extensions (KTX) to your project add the following to your app module's build.gradle
repositories {
google()
}
dependencies {
implementation 'androidx.core:core-ktx:1.0.0-rc01'
}
This post is just to mention an additional option. In case you need to set custom R libs in your Linux shell script you may easily do so by
export R_LIBS="~/R/lib"
See R admin guide on complete list of options.
For me adding DOCTYPE_PUBLIC
worked:
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "10");
Instead of if-else condition use if in both conditions. it will work that way but not sure why.
sqlall
just prints the SQL, it doesn't execute it. syncdb
will create tables that aren't already created, but it won't modify existing tables.
In conf/extra/httpd-vhosts.conf, add the line AllowOverride All
for all the websites that you are having problem with
<VirtualHost example.site:80>
# rest of the stuff
<Directory "c:\Projects\example.site">
Require all granted
AllowOverride All <-----This line is required
</Directory>
</VirtualHost>
Your file has syntax error, so your file was not interpreted, so settings was not changed and you have blank page.
You can separate your file to two.
index.php
<?php
ini_set("display_errors", "1");
error_reporting(E_ALL);
include 'error.php';
error.php
<?
echo('catch this -> ' ;. $thisdoesnotexist);
Either I don't understand your question, or Enumerable#find is the thing you were looking for.
Here's your expected snippet which gives you the array of all the matched values -
var windowArray = new Array ("item","thing","id-3-text","class");_x000D_
_x000D_
var result = [];_x000D_
windowArray.forEach(val => {_x000D_
if(val && val.includes('id-')) {_x000D_
result.push(val);_x000D_
}_x000D_
});_x000D_
_x000D_
console.log(result);
_x000D_
it's not exact output that you wanted but maybe something like this will do. Parent cmp:
<table>
<item *ngFor="#i of items" [data]="i"></item>
</table>
Child cmp
import {Component} from 'angular2/core';
@Component({
selector: `item`,
inputs: ['data'],
template: `
<tr><td>{{data.name}}</td></tr>
<tr *ngFor="#i of data.items">
<td><h1>{{i}}</h1></td>
</tr>
`
})
export default class Item {
}
C++17 (All references are from the final working draft of CPP17 - n4659)
Sequence Containers
vector
: The functions insert
, emplace_back
, emplace
, push_back
cause reallocation if the new size is greater than the old capacity. Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. If no reallocation
happens, all the iterators and references before the insertion point remain valid. [26.3.11.5/1]
With respect to the reserve
function, reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. No reallocation shall take place during insertions that happen after a call to reserve()
until the time when an insertion would make the size of the vector greater than the value of capacity()
. [26.3.11.3/6]
deque
: An insertion in the middle of the deque invalidates all the iterators and references to elements of the deque. An insertion at either end of the deque invalidates all the iterators to the deque, but has no effect on the validity of references to elements of the deque. [26.3.8.4/1]
list
: Does not affect the validity of iterators and references. If an exception is thrown there are no effects. [26.3.10.4/1].
The insert
, emplace_front
, emplace_back
, emplace
, push_front
, push_back
functions are covered under this rule.
forward_list
: None of the overloads of insert_after
shall affect the validity of iterators and references [26.3.9.5/1]
array
: As a rule, iterators to an array are never invalidated throughout the lifetime of the array. One should take note, however, that during swap, the iterator will continue to point to the same array element, and will thus change its value.
Associative Containers
All Associative Containers
: The insert
and emplace
members shall not affect the validity of iterators and references to the container [26.2.6/9]Unordered Associative Containers
All Unordered Associative Containers
: Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements. [26.2.7/9]
The insert
and emplace
members shall not affect the validity of references to container elements, but may invalidate all iterators to the container. [26.2.7/14]
The insert
and emplace
members shall not affect the validity of iterators if (N+n) <= z * B
, where N
is the number of elements in the container prior to the insert operation, n
is the number of elements inserted, B
is the container’s bucket count, and z
is the container’s maximum load factor. [26.2.7/15]
All Unordered Associative Containers
: In case of a merge operation (e.g., a.merge(a2)
), iterators referring to the transferred elements and all iterators referring to a
will be invalidated, but iterators to elements remaining in a2
will remain valid. (Table 91 — Unordered associative container requirements)
Container Adaptors
stack
: inherited from underlying containerqueue
: inherited from underlying containerpriority_queue
: inherited from underlying containerSequence Containers
vector
: The functions erase
and pop_back
invalidate iterators and references at or after the point of the erase. [26.3.11.5/3]
deque
: An erase operation that erases the last element of a deque
invalidates only the past-the-end iterator and all iterators and references to the erased elements. An erase operation that erases the first element of a deque
but not the last element invalidates only iterators and references to the erased elements. An erase operation that erases neither the first element nor the last element of a deque
invalidates the past-the-end iterator and all iterators and references to all the elements of the deque
.
[ Note: pop_front
and pop_back
are erase operations. —end note ] [26.3.8.4/4]
list
: Invalidates only the iterators and references to the erased elements. [26.3.10.4/3]. This applies to erase
, pop_front
, pop_back
, clear
functions.
remove
and remove_if
member functions: Erases all the elements in the list referred by a list iterator i
for which the following conditions hold: *i == value
, pred(*i) != false
. Invalidates only the iterators and references to the erased elements [26.3.10.5/15].
unique
member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i
in the range [first + 1, last)
for which *i == *(i-1)
(for the version of unique with no arguments) or pred(*i, *(i - 1))
(for the version of unique with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.10.5/19]
forward_list
: erase_after
shall invalidate only iterators and references to the erased elements. [26.3.9.5/1].
remove
and remove_if
member functions - Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value
(for remove()
), pred(*i)
is true (for remove_if()
). Invalidates only the iterators and references to the erased elements. [26.3.9.6/12].
unique
member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i in the range [first + 1, last) for which *i == *(i-1)
(for the version with no arguments) or pred(*i, *(i - 1))
(for the version with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.9.6/16]
All Sequence Containers
: clear
invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator (Table 87 — Sequence container requirements). But for forward_list
, clear
does not invalidate past-the-end iterators. [26.3.9.5/32]
All Sequence Containers
: assign
invalidates all references, pointers and
iterators referring to the elements of the container. For vector
and deque
, also invalidates the past-the-end iterator. (Table 87 — Sequence container requirements)
Associative Containers
All Associative Containers
: The erase
members shall invalidate only iterators and references to the erased elements [26.2.6/9]
All Associative Containers
: The extract
members invalidate only iterators to the removed element; pointers and references to the removed element remain valid [26.2.6/10]
Container Adaptors
stack
: inherited from underlying containerqueue
: inherited from underlying containerpriority_queue
: inherited from underlying containerGeneral container requirements relating to iterator invalidation:
Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [26.2.1/12]
no swap()
function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ] [26.2.1/(11.6)]
As examples of the above requirements:
transform
algorithm: The op
and binary_op
functions shall not invalidate iterators or subranges, or modify elements in the ranges [28.6.4/1]
accumulate
algorithm: In the range [first, last], binary_op
shall neither modify elements nor invalidate iterators or subranges [29.8.2/1]
reduce
algorithm: binary_op shall neither invalidate iterators or subranges, nor modify elements in the range [first, last]. [29.8.3/5]
and so on...
You can simulate them for example with hashes, but need care about the leading zeroes and many other things. The next demonstration works, but it is far from optimal solution.
#!/bin/bash
declare -A matrix
num_rows=4
num_columns=5
for ((i=1;i<=num_rows;i++)) do
for ((j=1;j<=num_columns;j++)) do
matrix[$i,$j]=$RANDOM
done
done
f1="%$((${#num_rows}+1))s"
f2=" %9s"
printf "$f1" ''
for ((i=1;i<=num_rows;i++)) do
printf "$f2" $i
done
echo
for ((j=1;j<=num_columns;j++)) do
printf "$f1" $j
for ((i=1;i<=num_rows;i++)) do
printf "$f2" ${matrix[$i,$j]}
done
echo
done
the above example creates a 4x5 matrix with random numbers and print it transposed, with the example result
1 2 3 4
1 18006 31193 16110 23297
2 26229 19869 1140 19837
3 8192 2181 25512 2318
4 3269 25516 18701 7977
5 31775 17358 4468 30345
The principle is: Creating one associative array where the index is an string like 3,4
. The benefits:
30,40,2
for 3 dimensional.${matrix[2,3]}
You might want to have look at simple command line scheduler "at":
C:\Documents and Settings\mahendra.patil>at/?
The AT command schedules commands and programs to run on a computer at a specified time and date. The Schedule service must be running to use the AT command.
AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]]
AT [\\computername] time [/INTERACTIVE]
[ /EVERY:date[,...] | /NEXT:date[,...]] "command"
\computername Specifies a remote computer. Commands are scheduled on the local computer if this parameter is omitted.
id Is an identification number assigned to a scheduled command.
/delete Cancels a scheduled command. If id is omitted, all the scheduled commands on the computer are canceled.
/yes Used with cancel all jobs command when no further confirmation is desired.
time Specifies the time when command is to run.
/interactive Allows the job to interact with the desktop of the user who is logged on at the time the job runs.
/every:date[,...] Runs the command on each specified day(s) of the week or month. If date is omitted, the current day of the month is assumed.
/next:date[,...] Runs the specified command on the next occurrence of the day (for example, next Thursday). If date is omitted, the current day of the month is assumed.
"command" Is the Windows NT command, or batch program to be run.
Small impovement of Albinofrenchy answer:
base.ts
export class Animal {
move() { /* ... */ }
}
export class Plant {
photosynthesize() { /* ... */ }
}
dog.ts
import * as b from './base';
export class Dog extends b.Animal {
woof() { }
}
things.ts
import { Dog } from './dog'
namespace things {
export const dog = Dog;
}
export = things;
main.ts
import * as things from './things';
console.log(things.dog);
I am calling the json on login button click
@IBAction func loginClicked(sender : AnyObject) {
var request = NSMutableURLRequest(URL: NSURL(string: kLoginURL)) // Here, kLogin contains the Login API.
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(self.criteriaDic(), options: nil, error: &err) // This Line fills the web service with required parameters.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
var err1: NSError?
var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1 ) as NSDictionary
println("json2 :\(json2)")
if(err) {
println(err!.localizedDescription)
}
else {
var success = json2["success"] as? Int
println("Success: \(success)")
}
})
task.resume()
}
Here, I have made a seperate dictionary for the parameters.
var params = ["format":"json", "MobileType":"IOS","MIN":"f8d16d98ad12acdbbe1de647414495ec","UserName":emailTxtField.text,"PWD":passwordTxtField.text,"SigninVia":"SH"]as NSDictionary
return params
}
// You can add your own sets of parameter here.
Below code may help.
age=(lambda i,f: f(i,f))(input("Please enter your age: "),lambda i,f: i if i.isdigit() else f(input("Please enter your age: "),f))
print("You are able to vote in the united states" if int(age)>=18 else "You are not able to vote in the united states",end='')
If you want to have maximum tries, say 3, use below code
age=(lambda i,n,f: f(i,n,f))(input("Please enter your age: "),1,lambda i,n,f: i if i.isdigit() else (None if n==3 else f(input("Please enter your age: "),n+1,f)))
print("You are able to vote in the united states" if age and int(age)>=18 else "You are not able to vote in the united states",end='')
Note: This uses recursion.
Also you can use DownloadFileAsync
method in WebClient
class. It downloads to a local file the resource with the specified URI
. Also this method does not block the calling thread.
Sample:
webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");
For more information:
http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/
Why don't you use
function jsredir() {_x000D_
window.location.href = "https://stackoverflow.com";_x000D_
}
_x000D_
<button onclick="jsredir()">Click Me!</button>
_x000D_
This looks like an academic exercise which unfortunately makes it harder since you can't use C++. Basically you have to manage some of the overhead for the allocation and keep track how much memory has been allocated if you need to resize it later. This is where the C++ standard library shines.
For your example, the following code allocates the memory and later resizes it:
// initial size
int count = 100;
words *testWords = (words*) malloc(count * sizeof(words));
// resize the array
count = 76;
testWords = (words*) realloc(testWords, count* sizeof(words));
Keep in mind, in your example you are just allocating a pointer to a char and you still need to allocate the string itself and more importantly to free it at the end. So this code allocates 100 pointers to char and then resizes it to 76, but does not allocate the strings themselves.
I have a suspicion that you actually want to allocate the number of characters in a string which is very similar to the above, but change word to char.
EDIT: Also keep in mind it makes a lot of sense to create functions to perform common tasks and enforce consistency so you don't copy code everywhere. For example, you might have a) allocate the struct, b) assign values to the struct, and c) free the struct. So you might have:
// Allocate a words struct
words* CreateWords(int size);
// Assign a value
void AssignWord(word* dest, char* str);
// Clear a words structs (and possibly internal storage)
void FreeWords(words* w);
EDIT: As far as resizing the structs, it is identical to resizing the char array. However the difference is if you make the struct array bigger, you should probably initialize the new array items to NULL. Likewise, if you make the struct array smaller, you need to cleanup before removing the items -- that is free items that have been allocated (and only the allocated items) before you resize the struct array. This is the primary reason I suggested creating helper functions to help manage this.
// Resize words (must know original and new size if shrinking
// if you need to free internal storage first)
void ResizeWords(words* w, size_t oldsize, size_t newsize);
Here's a sqldf solution:
sqldf("Select Code, Country, '1950' As Year, `1950` As Value From wide
Union All
Select Code, Country, '1951' As Year, `1951` As Value From wide
Union All
Select Code, Country, '1952' As Year, `1952` As Value From wide
Union All
Select Code, Country, '1953' As Year, `1953` As Value From wide
Union All
Select Code, Country, '1954' As Year, `1954` As Value From wide;")
To make the query without typing in everything, you can use the following:
Thanks to G. Grothendieck for implementing it.
ValCol <- tail(names(wide), -2)
s <- sprintf("Select Code, Country, '%s' As Year, `%s` As Value from wide", ValCol, ValCol)
mquery <- paste(s, collapse = "\n Union All\n")
cat(mquery) #just to show the query
#> Select Code, Country, '1950' As Year, `1950` As Value from wide
#> Union All
#> Select Code, Country, '1951' As Year, `1951` As Value from wide
#> Union All
#> Select Code, Country, '1952' As Year, `1952` As Value from wide
#> Union All
#> Select Code, Country, '1953' As Year, `1953` As Value from wide
#> Union All
#> Select Code, Country, '1954' As Year, `1954` As Value from wide
sqldf(mquery)
#> Code Country Year Value
#> 1 AFG Afghanistan 1950 20,249
#> 2 ALB Albania 1950 8,097
#> 3 AFG Afghanistan 1951 21,352
#> 4 ALB Albania 1951 8,986
#> 5 AFG Afghanistan 1952 22,532
#> 6 ALB Albania 1952 10,058
#> 7 AFG Afghanistan 1953 23,557
#> 8 ALB Albania 1953 11,123
#> 9 AFG Afghanistan 1954 24,555
#> 10 ALB Albania 1954 12,246
Unfortunately, I don't think that PIVOT
and UNPIVOT
would work for R
SQLite
. If you want to write up your query in a more sophisticated manner, you can also take a look at these posts:
Using sprintf
writing up sql queries Or Pass variables to sqldf
I followed an example in another repository and wrapped the directory structure within a pair of triple backticks (```
):
```
project
¦ README.md
¦ file001.txt
¦
+---folder1
¦ ¦ file011.txt
¦ ¦ file012.txt
¦ ¦
¦ +---subfolder1
¦ ¦ file111.txt
¦ ¦ file112.txt
¦ ¦ ...
¦
+---folder2
¦ file021.txt
¦ file022.txt
```
You can use CSS to hide the button.
button {
visibility: hidden;
}
If your <button>
is just a clickable area on the image, why bother make it a button? You can use <map>
element instead.
First, make sure that you've committed everything.
Then reset your repository to the previous working state:
$ git reset f836e4c1fa51524658b9f026eb5efa24afaf3a36
or using --hard
(this will remove all local, not committed changes!):
$ git reset f836e4c1fa51524658b9f026eb5efa24afaf3a36 --hard
Use the hash which was there before your wrongly merged commit.
Check which commits you'd like to re-commit on the top of the previous correct version by:
$ git log 4c3e23f529b581c3cbe95350e84e66e3cb05704f
commit 4c3e23f529b581c3cbe95350e84e66e3cb05704f
...
commit 16b373a96b0a353f7454b141f7aa6f548c979d0a
...
Apply your right commits on the top of the right version of your repository by:
By using cherry-pick (the changes introduced by some existing commits)
git cherry-pick ec59ab844cf504e462f011c8cc7e5667ebb2e9c7
Or by cherry-picking the range of commits by:
First checking the right changes before merging them:
git diff 5216b24822ea1c48069f648449997879bb49c070..4c3e23f529b581c3cbe95350e84e66e3cb05704f
First checking the right changes before merging them:
git cherry-pick 5216b24822ea1c48069f648449997879bb49c070..4c3e23f529b581c3cbe95350e84e66e3cb05704f
where this is the range of the correct commits which you've committed (excluding wrongly committed merge).
Many use the build scripts found either here: http://www.raywenderlich.com/41377/creating-a-static-library-in-ios-tutorial or here: https://gist.github.com/sponno/7228256 for their run script in their target.
I was pulling my hair out trying to add x86_64, i386, armv7s, armv7, and arm64 to the Architectures section, only to find lipo -info targetname.a
never returning these architectures after a successful build.
In my case, I had to modify the target runscript, specifically step 1 from the gist link, to manually include the architectures using -arch.
Step 1. Build Device and Simulator versions
xcodebuild -target ${PROJECT_NAME} ONLY_ACTIVE_ARCH=NO -configuration ${CONFIGURATION} -sdk iphoneos BUILD_DIR="${BUILD_DIR}"
BUILD_ROOT="${BUILD_ROOT}" xcodebuild -target ${PROJECT_NAME} -configuration ${CONFIGURATION} -sdk iphonesimulator -arch x86_64 -arch i386 -arch armv7 -arch armv7s -arch arm64 BUILD_DIR="${BUILD_DIR}" BUILD_ROOT="${BUILD_ROOT}"
Use WORKSPACE environment variable to change workspace directory.
If doing using Jenkinsfile, use following code :
dir("${env.WORKSPACE}/aQA"){
sh "pwd"
}
TDN's solution worked for me when I was having the same issue. The Build server created workspaces under my account. Checking this box allowed me to see and delete them.
ES2020 Answer
The new Nullish Coalescing Operator, is finally available on JavaScript, though browser support is limited. According to the data from caniuse, only 48.34% of browsers are supported (as of April 2020).
According to the documentation,
The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
const options={
filters:{
firstName:'abc'
}
};
const filter = options.filters[0] ?? '';
const filter2 = options.filters[1] ?? '';
This will ensure that both of your variables will have a fallback value of ''
if filters[0]
or filters[1]
are null
, or undefined
.
Do take note that the nullish coalescing operator does not return the default value for other types of falsy value such as 0
and ''
. If you wish to account for all falsy values, you should be using the OR operator ||
.
Give a try to ViewCompat.setBackground(yourView, drawableBackground)
I had same issue with my WPF RSS reader, I originally went with Awesomium (I think version 1.6) Awesomium is great. You get a lot of control for caching (images and HTML content), JavaScript execution, intercepting downloads and so forth. It's also super fast. The process isolation means when browser crashes it does not crash the app.
But it's also heavy, even release build adds about 10-15mb (can't remember exact number) and hence a slight start-up penalty. I then realized, only problem I had with IE browser control was that it would throw the JavaScript errors every now and again. But that was fixed with the following snippet.
I hardly used my app on XP or Vista but on Win 7 and above it never crashed (at least not because I used IE browser control)
IOleServiceProvider sp = browser.Document as IOleServiceProvider;
if (sp != null)
{
IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11d0-8A3E-00C04FC9E26E");
webBrowser;
sp.QueryService(ref IID_IWebBrowserApp, ref IID_IWebBrowser2, out webBrowser);
if (webBrowser != null)
{
webBrowser.GetType().InvokeMember("Silent",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.PutDispProperty, null, webBrowser, new object[] { silent });
}
}
Try this Function :
public int indexOfArray(String input){
for(int i=0;i<TYPES,length();i++)
{
if(TYPES[i].equals(input))
{
return i ;
}
}
return -1 // if the text not found the function return -1
}
Bootstrap have a specific class for this: center-block
<button type="button" class="your_class center-block"> Book </button>
This will help you to overcome overflow: overlay
issues as well.
.div{
height: 300px;
overflow: auto;
visibility: hidden;
}
.div-content,
.div:hover {
visibility: visible;
}
I don't think there is a way to ignore adding DEFINER
s to the dump. But there are ways to remove them after the dump file is created.
Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost
with an empty string ""
Edit the dump (or pipe the output) using perl
:
perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
I used zxing-1.3 jar and I had to make some changes implementing code from other answers, so I will leave my solution for others. I did the following:
1) find zxing-1.3.jar, download it and add in properties (add external jar).
2) in my activity layout add ImageView and name it (in my example it was tnsd_iv_qr).
3) include code in my activity to create qr image (in this example I was creating QR for bitcoin payments):
QRCodeWriter writer = new QRCodeWriter();
ImageView tnsd_iv_qr = (ImageView)findViewById(R.id.tnsd_iv_qr);
try {
ByteMatrix bitMatrix = writer.encode("bitcoin:"+btc_acc_adress+"?amount="+amountBTC, BarcodeFormat.QR_CODE, 512, 512);
int width = 512;
int height = 512;
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (bitMatrix.get(x, y)==0)
bmp.setPixel(x, y, Color.BLACK);
else
bmp.setPixel(x, y, Color.WHITE);
}
}
tnsd_iv_qr.setImageBitmap(bmp);
} catch (WriterException e) {
//Log.e("QR ERROR", ""+e);
}
If someone is wondering, variable "btc_acc_adress" is a String (with BTC adress), amountBTC is a double, with, of course, transaction amount.
Create card_background.xml in the res/drawable folder with the following code:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#BDBDBD"/>
<corners android:radius="5dp"/>
</shape>
</item>
<item
android:left="0dp"
android:right="0dp"
android:top="0dp"
android:bottom="2dp">
<shape android:shape="rectangle">
<solid android:color="#ffffff"/>
<corners android:radius="5dp"/>
</shape>
</item>
</layer-list>
Then add the following code to the element to which you want the card layout
android:background="@drawable/card_background"
the following line defines the color of the shadow for the card
<solid android:color="#BDBDBD"/>
I had faced similar issue with Angular4 and Jasmine unit tests; below given solution worked for me
Add below import statement
import { APP_BASE_HREF } from '@angular/common';
Add below statement for TestBed configuration:
TestBed.configureTestingModule({
providers: [
{ provide: APP_BASE_HREF, useValue : '/' }
]
})
My simple solution which is based on the default value of function parameters.
def getSystemContext(contextObjList=[]):
if len( contextObjList ) == 0:
contextObjList.append( Context() )
pass
return contextObjList[0]
class Context(object):
# Anything you want here
One of the best resources I found was using let's encrypt, you do not need ELB nor cloudfront for your EC2 instance to have HTTPS, just follow the following simple instructions: let's encrypt Login to your server and follow the steps in the link.
It is also important as mentioned by others that you have port 443 opened by editing your security groups
You can view your certificate or any other website's by changing the site name in this link
Please do not forget that it is only valid for 90 days
Your output is correct. Denote the white characters of " Hello" and " This" at the beginning.
Another issue is with your methodology. Use the Arrays.sort()
method:
String[] strings = { " Hello ", " This ", "Is ", "Sorting ", "Example" };
Arrays.sort(strings);
Output:
Hello
This
Example
Is
Sorting
Here the third element of the array "is" should be "Is", otherwise it will come in last after sorting. Because the sort method internally uses the ASCII value to sort elements.
Just put this in the first line of your script :
#!/usr/bin/env python
Make the file executable with
chmod +x myfile.py
Execute with
./myfile.py
Recursively add subfolders,
for i in `find . -name "*.java" -type f`; do
echo "$i"
done
I seem to be a bit late to the party and much more of a beginner than any expertise; BUT this worked for me:
window.onbeforeunload = function() {
return false;
};
I placed this as an inline script immediately after my Head and Meta elements, like this:
<script>
window.onbeforeunload = function() {
return false;
}
</script>
This page seems to me to be highly relevant to the originator's requirement (especially the sections headed window.onunload
and window.onbeforeunload
):
https://javascript.info/onload-ondomcontentloaded
Hoping this helps.
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class AvoidNullExp {
public static void main(String[] args) {
List<File> fileList =new ArrayList<>();
final File folder = new File("g:/master");
new AvoidNullExp().listFilesForFolder(folder, fileList);
}
public void listFilesForFolder(final File folder,List<File> fileList) {
File[] filesInFolder = folder.listFiles();
if (filesInFolder != null) {
for (final File fileEntry : filesInFolder) {
if (fileEntry.isDirectory()) {
System.out.println("DIR : "+fileEntry.getName());
listFilesForFolder(fileEntry,fileList);
} else {
System.out.println("FILE : "+fileEntry.getName());
fileList.add(fileEntry);
}
}
}
}
}
We copy/paste html pages from our ERP to Excel using "paste special.. as html/unicode" and it works quite well with tables.
It happened because of PHP 5.3 , which comes in WAMP 2.0i package and not Joomla.
You have two choices to fix it,
either use WAMP 2h (previous version) or download PHP 5.2.9-2 addon from WAMP website.
.register a:link{
color:#FFFFFF;
}
Call make
command this way:
make CFLAGS=-Dvar=42
And be sure to use $(CFLAGS)
in your compile command in the Makefile. As @jørgensen mentioned , putting the variable assignment after the make
command will override the CFLAGS
value already defined the Makefile.
Alternatively you could set -Dvar=42
in another variable than CFLAGS
and then reuse this variable in CFLAGS
to avoid completely overriding CFLAGS
.
Use the string objects Match method:
// Match a string that ends with abc, similar to LIKE '%abc'
if (theString.match(/^.*abc$/))
{
/*Match found */
}
// Match a string that starts with abc, similar to LIKE 'abc%'
if (theString.match(/^abc.*$/))
{
/*Match found */
}
What is your output when you do java -version
? This will tell you what version the running JVM is.
The Unsupported major.minor version 51.0 error could mean:
Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor
error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)
See: http://www.java.com/en/download/manual.jsp (7 Update 25 )
and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)
for the latest version of the JRE and JDK respectively.
EDIT:
Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.
Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.
open your /etc/paths file, put /usr/local/bin on top of /usr/bin
$ sudo vi /etc/paths
/usr/local/bin
/usr/local/sbin
/usr/bin
/bin
/usr/sbin
/sbin
and Restart the terminal, @mmel
It's fatal. The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather than the usual handshake. This bypasses the normal half-closed state transition. I like this description:
"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur.
SHOW ENGINE INNODB STATUS \G
Look for the Section -
TRANSACTIONS
We can use INFORMATION_SCHEMA Tables.
Useful Queries
To check about all the locks transactions are waiting for:
USE INFORMATION_SCHEMA;
SELECT * FROM INNODB_LOCK_WAITS;
A list of blocking transactions:
SELECT *
FROM INNODB_LOCKS
WHERE LOCK_TRX_ID IN (SELECT BLOCKING_TRX_ID FROM INNODB_LOCK_WAITS);
OR
SELECT INNODB_LOCKS.*
FROM INNODB_LOCKS
JOIN INNODB_LOCK_WAITS
ON (INNODB_LOCKS.LOCK_TRX_ID = INNODB_LOCK_WAITS.BLOCKING_TRX_ID);
A List of locks on particular table:
SELECT * FROM INNODB_LOCKS
WHERE LOCK_TABLE = db_name.table_name;
A list of transactions waiting for locks:
SELECT TRX_ID, TRX_REQUESTED_LOCK_ID, TRX_MYSQL_THREAD_ID, TRX_QUERY
FROM INNODB_TRX
WHERE TRX_STATE = 'LOCK WAIT';
Reference - MySQL Troubleshooting: What To Do When Queries Don't Work, Chapter 6 - Page 96.
Updated
How to implement page refresh in Angular 2+ note this is done within your component:
location.reload();
I know this is an old question, but I was struggling to do this with a time period over 2 hours, so this might help someone. Also, several of the answers don't actually plot against time, giving equal space whatever the duration.
Firstly, as @jameswarren says, use a scatter graph. Then right-click the horizontal axis and choose Format Axis.
Under Number, select Time, and at this point you may find your scale goes a bit crazy, because it chooses to scale the axis by days. So go back to Axis Options and select Fixed for the Minimum, Maximum and Major unit scales.
To set the unit to hours, type in 1/24 = 0.0416667 (I used half that to get half-hourly increments). To make this start at a round number, multiply it by your preferred number of hours and type that into the Minimum box. In my case 08:00 = 0.333333
This is my solution(There is a nested LinearLayout):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/item"
android:layout_width="match_parent"
android:layout_height="47dp"
android:background="@drawable/box_arrow_top_bg"
android:gravity="center"
android:text="????"
android:textColor="#666"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>
In my case I changed this:
<mat-form-field>
<input type="email" placeholder="email" [(ngModel)]="data.email">
</mat-form-field>
to this:
<mat-form-field>
<input matInput type="email" placeholder="email" [(ngModel)]="data.email">
</mat-form-field>
Adding the matInput directive to the input tag was what fixed this error for me.
For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 Now Just go Project under Project settings and select the project SDK.
I have one more idea (it is valid for C++11).
Let's look at the following example:
#include <cstddef>
#include <cstdio>
int main() {
struct alignas(0x1000) A {
char data[0x1000];
};
printf("max_align_t: %zu\n", alignof(max_align_t));
A a;
printf("a: %p\n", &a);
A *ptr = new A;
printf("ptr: %p\n", ptr);
delete ptr;
}
With C++11 standard, GCC gives the following output:
max_align_t: 16
a: 0x7ffd45e6f000
ptr: 0x1fe3ec0
ptr
is not aligned properly.
With C++17 standard and further, GCC gives the following output:
max_align_t: 16
a: 0x7ffc924f6000
ptr: 0x9f6000
ptr
is aligned properly.
As I know, C++ standard didn't support over-aligned new before C++17 came, and if your structure has alignment greater than max_align_t
, you can have problems.
To bypass this issue in C++11, you can use aligned_alloc
.
#include <cstddef>
#include <cstdlib>
#include <cstdio>
#include <new>
int main() {
struct alignas(0x1000) A {
char data[0x1000];
};
printf("max_align_t: %zu\n", alignof(max_align_t));
A a;
printf("a: %p\n", &a);
void *buf = aligned_alloc(alignof(A), sizeof(A));
if (buf == nullptr) {
printf("aligned_alloc() failed\n");
exit(1);
}
A *ptr = new(buf) A();
printf("ptr: %p\n", ptr);
ptr->~A();
free(ptr);
}
ptr
is aligned in this case.
max_align_t: 16
a: 0x7ffe56b57000
ptr: 0x2416000
It's better to use $(window).scroll()
rather than $('#Eframe').on("mousewheel")
$('#Eframe').on("mousewheel")
will not trigger if people manually scroll using up and down arrows on the scroll bar or grabbing and dragging the scroll bar itself.
$(window).scroll(function(){
var scrollPos = $(document).scrollTop();
console.log(scrollPos);
});
If #Eframe
is an element with overflow:scroll
on it and you want it's scroll position. I think this should work (I haven't tested it though).
$('#Eframe').scroll(function(){
var scrollPos = $('#Eframe').scrollTop();
console.log(scrollPos);
});
This import android packages cannot be resolved
is also occurs when your using some library and that library is not in the same path where your application is there, or if you are importing the library and not coping library to the workspace
You can also use the react-fontawesome
icon library. Here's the link: react-fontawesome
From the NPM page, just install via npm:
npm install --save react-fontawesome
Require the module:
var FontAwesome = require('react-fontawesome');
And finally, use the <FontAwesome />
component and pass in attributes to specify icon and styling:
var MyComponent = React.createClass({
render: function () {
return (
<FontAwesome
className='super-crazy-colors'
name='rocket'
size='2x'
spin
style={{ textShadow: '0 1px 0 rgba(0, 0, 0, 0.1)' }}
/>
);
}
});
Don't forget to add the font-awesome CSS to index.html:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">
How I solved this issue: 1. Be connected to the internet. 2. Open the Anaconda Prompt (looks like a regular command window). If you installed the .exe in your /name/user/ location you should be fine, if not navigate to it. Then start an environment.
conda info --envs
Then run
conda install -c anaconda anaconda-navigator
Press y when prompted (if prompted). It will being downloading the packages needed.
Then run your newly installed Anaconda Navigator
anaconda-navigator
It should start, and also appear in your regular windows 10 apps list.
if you are using windows, in WinDef.h you have:
typedef unsigned char BYTE;
in typeScript
of angular 6
, this code is working for me.
var formData = new FormData();
formData.append('name', 'value1');
formData.append('name', 'value2');
console.log(formData.get('name')); // this is return first element value.
or for all values:
console.log(formData.getAll('name')); // return all values
The reason why you get your error is because a "1 by n" matrix is different from an array of length n.
I recommend using hstack()
and vstack()
instead.
Like this:
import numpy as np
a = np.arange(32).reshape(4,8) # 4 rows 8 columns matrix.
b = a[:,-1:] # last column of that matrix.
result = np.hstack((a,b)) # stack them horizontally like this:
#array([[ 0, 1, 2, 3, 4, 5, 6, 7, 7],
# [ 8, 9, 10, 11, 12, 13, 14, 15, 15],
# [16, 17, 18, 19, 20, 21, 22, 23, 23],
# [24, 25, 26, 27, 28, 29, 30, 31, 31]])
Notice the repeated "7, 15, 23, 31" column.
Also, notice that I used a[:,-1:]
instead of a[:,-1]
. My version generates a column:
array([[7],
[15],
[23],
[31]])
Instead of a row array([7,15,23,31])
Edit: append()
is much slower. Read this answer.
In Asp.Net Core you can edit the web.config files like so:
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
You can remove the server header in the Kestrel options:
.UseKestrel(c =>
{
// removes the server header
c.AddServerHeader = false;
})
I had a similar issue. It is caused due the dependent package 'rJava'. This problem can be overcome by re-directing the R to use a different JAVA_HOME
.
if(Sys.getenv("JAVA_HOME")!=""){
Sys.setenv(JAVA_HOME="")
}
library(rJava)
This worked for me.
I figured out below would work:
my_df.dropna().quantile([0.0, .9])
In here:
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do
if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.
Although the earlier answers are OK, here's my contribution.
//returns the size of a character array using a pointer to the first element of the character array
int size(char *ptr)
{
//variable used to access the subsequent array elements.
int offset = 0;
//variable that counts the number of elements in your array
int count = 0;
//While loop that tests whether the end of the array has been reached
while (*(ptr + offset) != '\0')
{
//increment the count variable
++count;
//advance to the next element of the array
++offset;
}
//return the size of the array
return count;
}
In your main function, you call the size function by passing the address of the first element of your array.
For example:
char myArray[] = {'h', 'e', 'l', 'l', 'o'};
printf("The size of my character array is: %d\n", size(&myArray[0]));