This disables the script errors and also disables other windows.. such as the NTLM login window or the client certificate accept window. The below will suppress only javascript errors.
// Hides script errors without hiding other dialog boxes.
private void SuppressScriptErrorsOnly(WebBrowser browser)
{
// Ensure that ScriptErrorsSuppressed is set to false.
browser.ScriptErrorsSuppressed = false;
// Handle DocumentCompleted to gain access to the Document object.
browser.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(
browser_DocumentCompleted);
}
private void browser_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
((WebBrowser)sender).Document.Window.Error +=
new HtmlElementErrorEventHandler(Window_Error);
}
private void Window_Error(object sender,
HtmlElementErrorEventArgs e)
{
// Ignore the error and suppress the error dialog box.
e.Handled = true;
}
TRUNCATE TABLE `table`
unless you need to preserve the current value of the AUTO_INCREMENT sequence, in which case you'd probably prefer
DELETE FROM `table`
though if the time of the operation matters, saving the AUTO_INCREMENT value, truncating the table, and then restoring the value using
ALTER TABLE `table` AUTO_INCREMENT = value
will happen a lot faster.
I have come to this question and the one below several times.
how to call scalar function in sql server 2008
Each time, I try entering the Function using the syntax shown here in SQL Server Management Studio, or SSMS, to see the results, and each time I get the errors.
For me, that is because my result set is in tabular data format. Therefore, to see the results in SSMS, I have to call it like this:
SELECT * FROM dbo.Afisho_rankimin_TABLE(5);
I understand that the author's question involved a scalar function, so this answer is only to help others who come to StackOverflow often when they have a problem with a query (like me).
I hope this helps others.
Jasmine doesn't have that functionality, but you might be able to hack something together using Object.defineProperty
.
You could refactor your code to use a getter function, then spy on the getter.
spyOn(myObj, 'getValueA').andReturn(1);
expect(myObj.getValueA()).toBe(1);
i had the same problem, i fixed it by removing the transform:translateY
CSS i placed on the footer
of the page.
CDATA
has no meaning at all in HTML.
CDATA
is an XML construct which sets a tag's contents that is normally #PCDATA - parsed character data, to be instead taken as #CDATA, that is, non-parsed character data. It is only relevant and valid in XHTML.
It is used in script
tags to avoid parsing <
and &
. In HTML, this is not needed, because in HTML, script
is already #CDATA.
If you have (or create) a single string, you can use np.fromstring:
import numpy as np
x = ["1.1", "2.2", "3.2"]
x = ','.join(x)
x = np.fromstring( x, dtype=np.float, sep=',' )
Note, x = ','.join(x)
transforms the x array to string '1.1, 2.2, 3.2'
. If you read a line from a txt file, each line will be already a string.
For those errors where modelstate.isvalid is false, I generally send the error as it is thrown by the code. Its easy to understand for the developer who is consuming my service. I generally send the result using below code.
if(!ModelState.IsValid) {
List<string> errorlist=new List<string>();
foreach (var value in ModelState.Values)
{
foreach(var error in value.Errors)
errorlist.Add( error.Exception.ToString());
//errorlist.Add(value.Errors);
}
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest,errorlist);}
This sends the error to the client in below format which is basically a list of errors:
[
"Newtonsoft.Json.JsonReaderException: **Could not convert string to integer: abc. Path 'Country',** line 6, position 16.\r\n
at Newtonsoft.Json.JsonReader.ReadAsInt32Internal()\r\n
at Newtonsoft.Json.JsonTextReader.ReadAsInt32()\r\n
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter, Boolean inArray)\r\n
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)",
"Newtonsoft.Json.JsonReaderException: **Could not convert string to integer: ab. Path 'State'**, line 7, position 13.\r\n
at Newtonsoft.Json.JsonReader.ReadAsInt32Internal()\r\n
at Newtonsoft.Json.JsonTextReader.ReadAsInt32()\r\n
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter, Boolean inArray)\r\n
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)"
]
With pandas >= 1.0 there is now a dedicated string datatype:
1) You can convert your column to this pandas string datatype using .astype('string'):
df['zipcode'] = df['zipcode'].astype('string')
2) This is different from using str
which sets the pandas object datatype:
df['zipcode'] = df['zipcode'].astype(str)
3) For changing into categorical datatype use:
df['zipcode'] = df['zipcode'].astype('category')
You can see this difference in datatypes when you look at the info of the dataframe:
df = pd.DataFrame({
'zipcode_str': [90210, 90211] ,
'zipcode_string': [90210, 90211],
'zipcode_category': [90210, 90211],
})
df['zipcode_str'] = df['zipcode_str'].astype(str)
df['zipcode_string'] = df['zipcode_str'].astype('string')
df['zipcode_category'] = df['zipcode_category'].astype('category')
df.info()
# you can see that the first column has dtype object
# while the second column has the new dtype string
# the third column has dtype category
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 zipcode_str 2 non-null object
1 zipcode_string 2 non-null string
2 zipcode_category 2 non-null category
dtypes: category(1), object(1), string(1)
The 'string' extension type solves several issues with object-dtype NumPy arrays:
You can accidentally store a mixture of strings and non-strings in an object dtype array. A StringArray can only store strings.
object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text, but still object-dtype columns.
When reading code, the contents of an object dtype array is less clear than string.
More info on working with the new string datatype can be found here: https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html
For HostGator, you need to use the following for your headers:
$headers = 'From: [email protected]' . " " .
'Reply-To: [email protected]' . " " .
'X-Mailer: PHP/' . phpversion();
It only worked for me when the from user was host e-mail while the Reply-To can be something different e.g. From: [email protected], Reply-To: [email protected]
http://support.hostgator.com/articles/specialized-help/technical/php-email-from-header http://support.hostgator.com/articles/specialized-help/technical/how-to-use-sendmail-with-php
Another posibility:
public enum ConditionsToBeSatisfied implements Predicate<Number> {
IS_NOT_NULL(Objects::nonNull, "Item is null"),
IS_NOT_AN_INTEGER(item -> item instanceof Integer, "Item is not an integer"),
IS_POSITIVE(item -> item instanceof Integer && (Integer) item > 0, "Item is negative");
private final Predicate<Number> predicate;
private final String notSatisfiedLogMessage;
ConditionsToBeSatisfied(final Predicate<Number> predicate, final String notSatisfiedLogMessage) {
this.predicate = predicate;
this.notSatisfiedLogMessage = notSatisfiedLogMessage;
}
@Override
public boolean test(final Number item) {
final boolean isNotValid = predicate.negate().test(item);
if (isNotValid) {
log.warn("Invalid {}. Cause: {}", item, notSatisfiedLogMessage);
}
return predicate.test(item);
}
}
and using:
Predicate<Number> p = IS_NOT_NULL.and(IS_NOT_AN_INTEGER).and(IS_POSITIVE);
Little bit off topic but say i want to remove all 2s from a list. Here's a very elegant way to do that.
void RemoveAll<T>(T item,List<T> list)
{
while(list.Contains(item)) list.Remove(item);
}
With predicate:
void RemoveAll<T>(Func<T,bool> predicate,List<T> list)
{
while(list.Any(predicate)) list.Remove(list.First(predicate));
}
+1 only to encourage you to leave your answer here for learning purposes. You're also right about it being off-topic, but I won't ding you for that because of there is significant value in leaving your examples here, again, strictly for learning purposes. I'm posting this response as an edit because posting it as a series of comments would be unruly.
Though your examples are short & compact, neither is elegant in terms of efficiency; the first is bad at O(n2), the second, absolutely abysmal at O(n3). Algorithmic efficiency of O(n2) is bad and should be avoided whenever possible, especially in general-purpose code; efficiency of O(n3) is horrible and should be avoided in all cases except when you know n will always be very small. Some might fling out their "premature optimization is the root of all evil" battle axes, but they do so naïvely because they do not truly understand the consequences of quadratic growth since they've never coded algorithms that have to process large datasets. As a result, their small-dataset-handling algorithms just run generally slower than they could, and they have no idea that they could run faster. The difference between an efficient algorithm and an inefficient algorithm is often subtle, but the performance difference can be dramatic. The key to understanding the performance of your algorithm is to understand the performance characteristics of the primitives you choose to use.
In your first example, list.Contains()
and Remove()
are both O(n), so a while()
loop with one in the predicate & the other in the body is O(n2); well, technically O(m*n), but it approaches O(n2) as the number of elements being removed (m) approaches the length of the list (n).
Your second example is even worse: O(n3), because for every time you call Remove()
, you also call First(predicate)
, which is also O(n). Think about it: Any(predicate)
loops over the list looking for any element for which predicate()
returns true. Once it finds the first such element, it returns true. In the body of the while()
loop, you then call list.First(predicate)
which loops over the list a second time looking for the same element that had already been found by list.Any(predicate)
. Once First()
has found it, it returns that element which is passed to list.Remove()
, which loops over the list a third time to yet once again find that same element that was previously found by Any()
and First()
, in order to finally remove it. Once removed, the whole process starts over at the beginning with a slightly shorter list, doing all the looping over and over and over again starting at the beginning every time until finally no more elements matching the predicate remain. So the performance of your second example is O(m*m*n), or O(n3) as m approaches n.
Your best bet for removing all items from a list that match some predicate is to use the generic list's own List<T>.RemoveAll(predicate)
method, which is O(n) as long as your predicate is O(1). A for()
loop technique that passes over the list only once, calling list.RemoveAt()
for each element to be removed, may seem to be O(n) since it appears to pass over the loop only once. Such a solution is more efficient than your first example, but only by a constant factor, which in terms of algorithmic efficiency is negligible. Even a for()
loop implementation is O(m*n) since each call to Remove()
is O(n). Since the for()
loop itself is O(n), and it calls Remove()
m times, the for()
loop's growth is O(n2) as m approaches n.
I believe you are looking for:
Just pass it the localhost IP.
There is also a gethostbyname function, that is also usefull.
This will replace consecutive spaces with one space (but not tab).
tr -s '[:blank:]'
This will replace consecutive spaces with a tab.
tr -s '[:blank:]' '\t'
Use a binding for the value in your template.
value="{{ option.id }}"
should be
[value]="option.id"
And in your selected value use ngModel
instead of value
.
<mat-select [(value)]="selected2">
should be
<mat-select [(ngModel)]="selected2">
Complete code:
<div>
<mat-select [(ngModel)]="selected2">
<mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option>
</mat-select>
</div>
On a side note as of version 2.0.0-beta.12 the material select now accepts a mat-form-field
element as the parent element so it is consistent with the other material input controls. Replace the div
element with mat-form-field
element after you upgrade.
<mat-form-field>
<mat-select [(ngModel)]="selected2">
<mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option>
</mat-select>
</mat-form-field>
To improve on the answer provided by @artofwarfare, here is what I consider a neater way to check for the message
attribute and print it or print the Exception
object as a fallback.
try:
pass
except Exception as e:
print getattr(e, 'message', repr(e))
The call to repr
is optional, but I find it necessary in some use cases.
Update #1:
Following the comment by @MadPhysicist, here's a proof of why the call to repr
might be necessary. Try running the following code in your interpreter:
try:
raise Exception
except Exception as e:
print(getattr(e, 'message', repr(e)))
print(getattr(e, 'message', str(e)))
Update #2:
Here is a demo with specifics for Python 2.7 and 3.5: https://gist.github.com/takwas/3b7a6edddef783f2abddffda1439f533
On Linux, I often use curl with the --head parameter. It is available for several operating systems, including Windows.
[edit] related to the answer below, gknw.net is currently down as of February 23 2012. Check curl.haxx.se for updated info.
You misspelled permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Here's a decent explanation of clone()
if you end up needing it...
You can enable the CURLOPT_VERBOSE
option and log that information to a (temporary) CURLOPT_STDERR
:
// CURLOPT_VERBOSE: TRUE to output verbose information. Writes output to STDERR,
// or the file specified using CURLOPT_STDERR.
curl_setopt($handle, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($handle, CURLOPT_STDERR, $verbose);
You can then read it after curl has done the request:
$result = curl_exec($handle);
if ($result === FALSE) {
printf("cUrl error (#%d): %s<br>\n", curl_errno($handle),
htmlspecialchars(curl_error($handle)));
}
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";
(I originally answered similar but more extended in a related question.)
More information like metrics about the last request is available via curl_getinfo
. This information can be useful for debugging curl requests, too. A usage example, I would normally wrap that into a function:
$version = curl_version();
extract(curl_getinfo($handle));
$metrics = <<<EOD
URL....: $url
Code...: $http_code ($redirect_count redirect(s) in $redirect_time secs)
Content: $content_type Size: $download_content_length (Own: $size_download) Filetime: $filetime
Time...: $total_time Start @ $starttransfer_time (DNS: $namelookup_time Connect: $connect_time Request: $pretransfer_time)
Speed..: Down: $speed_download (avg.) Up: $speed_upload (avg.)
Curl...: v{$version['version']}
EOD;
You've already got it: A if test else B
is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
The final if
clause acts as a filter, which is different from having the conditional expression.
# Patrick Burwell's Ping Script - [email protected] #
$Output= @() #sets an array
$names = Get-Content ".\input\ptd.pc_list.txt" #sets a list to use, like a DNS dump
foreach ($name in $names){ #sets the input by enumerating a text file to loop through and sets a variable to execute against
if ($IPV4 = Test-Connection -Delay 15 -ComputerName $name -Count 1 -ErrorAction SilentlyContinue|select IPV4Address #run ping and sets only IPV4Address response variable
){# If true then run...
$Output+= $Name,($IPV4.IPV4Address).IPAddressToString # Fills the array with the #true response
Write-Host $Name',','Ping,'($IPV4.IPV4Address).IPAddressToString -ForegroundColor Green #Sets the output to receive the Name, result and IPV4Address and prints the reply to the console with specific colors
}
else{#If false then run...
$Output+= "$name," #Fills the array with the #false response
Write-Host "$Name," -ForegroundColor Red #Prints the reply to the console with specific colors
}
}
#$Output | Out-file ".\output\result.csv" #<-- use to export to a text file (Set path as needed)
#$Output | Export-CSV ".\output\result.csv" -NoTypeInformation #<-- use to export to a csv file (Set path as needed)
#If you choose, you can merely have the reply by the name and IP, and the Name and no IP by removing the Ping comments
The Set interface itself does not stipulate any particular order. The SortedSet does however.
You can do this in two steps:
git checkout -f
git clean -fd
LIKE 'WC[[]R]S123456'
or
LIKE 'WC\[R]S123456' ESCAPE '\'
Should work.
You can loop over each row of the DataTable
and check the value.
I'm a big fan of using a foreach loop when using IEnumerable
s. Makes it very simple and clean to look at or process each row
DataTable dtPs = // ... initialize your DataTable
foreach (DataRow dr in dtPs.Rows)
{
if (dr["item_manuf_id"].ToString() == "some value")
{
// do your deed
}
}
Alternatively you can use a PrimaryKey
for your DataTable
. This helps in various ways, but you often need to define one before you can use it.
An example of using one if at http://msdn.microsoft.com/en-us/library/z24kefs8(v=vs.80).aspx
DataTable workTable = new DataTable("Customers");
// set constraints on the primary key
DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));
workCol.AllowDBNull = false;
workCol.Unique = true;
workTable.Columns.Add("CustLName", typeof(String));
workTable.Columns.Add("CustFName", typeof(String));
workTable.Columns.Add("Purchases", typeof(Double));
// set primary key
workTable.PrimaryKey = new DataColumn[] { workTable.Columns["CustID"] };
Once you have a primary key defined and data populated, you can use the Find(...) method to get the rows that match your primary key.
Take a look at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx
DataRow drFound = dtPs.Rows.Find("some value");
if (drFound["item_manuf_id"].ToString() == "some value")
{
// do your deed
}
Finally, you can use the Select() method to find data within a DataTable
also found at at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx.
String sExpression = "item_manuf_id == 'some value'";
DataRow[] drFound;
drFound = dtPs.Select(sExpression);
foreach (DataRow dr in drFound)
{
// do you deed. Each record here was already found to match your criteria
}
I know it's been a while since someone answerd here and the poster probably already got his answer either from here or from somewhere else. I do however think that this post will help anyone looking for a way to keep track of errors and timeouts while doing getJSON requests. Therefore below my answer to the question
The getJSON structure is as follows (found on http://api.jqueri.com):
$(selector).getJSON(url,data,success(data,status,xhr))
most people implement that using
$.getJSON(url, datatosend, function(data){
//do something with the data
});
where they use the url var to provide a link to the JSON data, the datatosend as a place to add the "?callback=?"
and other variables that have to be send to get the correct JSON data returned, and the success funcion as a function for processing the data.
You can however add the status and xhr variables in your success function. The status variable contains one of the following strings : "success", "notmodified", "error", "timeout", or "parsererror", and the xhr variable contains the returned XMLHttpRequest object (found on w3schools)
$.getJSON(url, datatosend, function(data, status, xhr){
if (status == "success"){
//do something with the data
}else if (status == "timeout"){
alert("Something is wrong with the connection");
}else if (status == "error" || status == "parsererror" ){
alert("An error occured");
}else{
alert("datatosend did not change");
}
});
This way it is easy to keep track of timeouts and errors without having to implement a custom timeout tracker that is started once a request is done.
Hope this helps someone still looking for an answer to this question.
nvmw is no longer maintained, but I found another source that seems to be up to date (as of 1/4/17).
It works. Allowed me to downgrade to 6.3.1
Just for curiosity and to compare with Saint Hill's answer.
If you need to process heavy data you should not use JVM in client mode. Client mode is not made for optimizations.
Let's compare results of @Saint Hill benchmarks using a JVM in Client mode and Server mode.
Core2Quad Q6600 G0 @ 2.4GHz
JavaSE 1.7.0_40
See also: Real differences between "java -server" and "java -client"?
CLIENT MODE:
len = 2: 111k charAt(i), 105k cbuff[i], 62k new[i], 17k field access. (chars/ms)
len = 4: 285k charAt(i), 166k cbuff[i], 114k new[i], 43k field access. (chars/ms)
len = 6: 315k charAt(i), 230k cbuff[i], 162k new[i], 69k field access. (chars/ms)
len = 8: 333k charAt(i), 275k cbuff[i], 181k new[i], 85k field access. (chars/ms)
len = 12: 342k charAt(i), 342k cbuff[i], 222k new[i], 117k field access. (chars/ms)
len = 16: 363k charAt(i), 347k cbuff[i], 275k new[i], 152k field access. (chars/ms)
len = 20: 363k charAt(i), 392k cbuff[i], 289k new[i], 180k field access. (chars/ms)
len = 24: 375k charAt(i), 428k cbuff[i], 311k new[i], 205k field access. (chars/ms)
len = 28: 378k charAt(i), 474k cbuff[i], 341k new[i], 233k field access. (chars/ms)
len = 32: 376k charAt(i), 492k cbuff[i], 340k new[i], 251k field access. (chars/ms)
len = 64: 374k charAt(i), 551k cbuff[i], 374k new[i], 367k field access. (chars/ms)
len = 128: 385k charAt(i), 624k cbuff[i], 415k new[i], 509k field access. (chars/ms)
len = 256: 390k charAt(i), 675k cbuff[i], 436k new[i], 619k field access. (chars/ms)
len = 512: 394k charAt(i), 703k cbuff[i], 439k new[i], 695k field access. (chars/ms)
len = 1024: 395k charAt(i), 718k cbuff[i], 462k new[i], 742k field access. (chars/ms)
len = 2048: 396k charAt(i), 725k cbuff[i], 471k new[i], 767k field access. (chars/ms)
len = 4096: 396k charAt(i), 727k cbuff[i], 459k new[i], 780k field access. (chars/ms)
len = 8192: 397k charAt(i), 712k cbuff[i], 446k new[i], 772k field access. (chars/ms)
SERVER MODE:
len = 2: 86k charAt(i), 41k cbuff[i], 46k new[i], 80k field access. (chars/ms)
len = 4: 571k charAt(i), 250k cbuff[i], 97k new[i], 222k field access. (chars/ms)
len = 6: 666k charAt(i), 333k cbuff[i], 125k new[i], 315k field access. (chars/ms)
len = 8: 800k charAt(i), 400k cbuff[i], 181k new[i], 380k field access. (chars/ms)
len = 12: 800k charAt(i), 521k cbuff[i], 260k new[i], 545k field access. (chars/ms)
len = 16: 800k charAt(i), 592k cbuff[i], 296k new[i], 640k field access. (chars/ms)
len = 20: 800k charAt(i), 666k cbuff[i], 408k new[i], 800k field access. (chars/ms)
len = 24: 800k charAt(i), 705k cbuff[i], 452k new[i], 800k field access. (chars/ms)
len = 28: 777k charAt(i), 736k cbuff[i], 368k new[i], 933k field access. (chars/ms)
len = 32: 800k charAt(i), 780k cbuff[i], 571k new[i], 969k field access. (chars/ms)
len = 64: 800k charAt(i), 901k cbuff[i], 800k new[i], 1306k field access. (chars/ms)
len = 128: 1084k charAt(i), 888k cbuff[i], 633k new[i], 1620k field access. (chars/ms)
len = 256: 1122k charAt(i), 966k cbuff[i], 729k new[i], 1790k field access. (chars/ms)
len = 512: 1163k charAt(i), 1007k cbuff[i], 676k new[i], 1910k field access. (chars/ms)
len = 1024: 1179k charAt(i), 1027k cbuff[i], 698k new[i], 1954k field access. (chars/ms)
len = 2048: 1184k charAt(i), 1043k cbuff[i], 732k new[i], 2007k field access. (chars/ms)
len = 4096: 1188k charAt(i), 1049k cbuff[i], 742k new[i], 2031k field access. (chars/ms)
len = 8192: 1157k charAt(i), 1032k cbuff[i], 723k new[i], 2048k field access. (chars/ms)
CONCLUSION:
As you can see, server mode is much faster.
You need to use an explicit java.util.Iterator
to iterate over the Map
's entry set rather than being able to use the enhanced For-loop syntax available in Java 6. The following example iterates over a Map
of Integer
, String
pairs, removing any entry whose Integer
key is null or equals 0.
Map<Integer, String> map = ...
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
// Remove entry if key is null or equals 0.
if (entry.getKey() == null || entry.getKey() == 0) {
it.remove();
}
}
In addition to the provided answer, there are more details to navigate
. From the function's comments:
/**
* Navigate based on the provided array of commands and a starting point.
* If no starting route is provided, the navigation is absolute.
*
* Returns a promise that:
* - resolves to 'true' when navigation succeeds,
* - resolves to 'false' when navigation fails,
* - is rejected when an error happens.
*
* ### Usage
*
* ```
* router.navigate(['team', 33, 'user', 11], {relativeTo: route});
*
* // Navigate without updating the URL
* router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
* ```
*
* In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current
* URL.
*/
The Router Guide has more details on programmatic navigation.
create procedure PSaleCForms
as
begin
declare
@b varchar(9),
@c nvarchar(500),
@q nvarchar(max)
declare @T table(FY nvarchar(9),Qtr int,title nvarchar (max),invoicenumber nvarchar(max),invoicedate datetime,sp decimal 18,2),grandtotal decimal(18,2))
declare @data cursor
set @data= Cursor
forward_only static
for
select x.DBTitle,y.CurrentFinancialYear from [Accounts Manager].dbo.DBManager x inner join [Accounts Manager].dbo.Accounts y on y.DBID=x.DBID where x.cfy=1
open @data
fetch next from @data
into @c,@b
while @@FETCH_STATUS=0
begin
set @q=N'Select '''+@b+''' [fy], case cast(month(i.invoicedate)/3.1 as int) when 0 then 4 else cast(month(i.invoicedate)/3.1 as int) end [Qtr], l.title,i.invoicenumber,i.invoicedate,i.sp,i.grandtotal from ['+@c+'].dbo.invoicemain i inner join ['+@c+'].dbo.ledgermain l on l.ledgerid=i.ledgerid where (sp=0 or stocktype=''x'') and invoicetype=''DS'''
insert into @T exec [master].dbo.sp_executesql @q fetch next from @data into @c,@b end close @data deallocate @data select * from @T return end
What fixed it for me was plugging my iPhone and allowing it as a simulator destination. Doing so required my to register my iPhone in Apple Dev account and once that was done and I ran my project from Xcode on my iPhone everything fixed itself.
>>> a = 147.234
>>> a % 1
0.23400000000000887
>>> a // 1
147.0
>>>
If you want the integer part as an integer and not a float, use int(a//1)
instead. To obtain the tuple in a single passage: (int(a//1), a%1)
EDIT: Remember that the decimal part of a float number is approximate, so if you want to represent it as a human would do, you need to use the decimal library
Don't use a reg-ex.
Apparently the following is a reg-ex that correctly validates most e-mails addresses that conform to RFC 2822, (and will still fail on things like "[email protected]", as will org.apache.commons.validator.routines.EmailValidator)
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
Possibly the easiest way to validate an e-mail to just send a confirmation e-mail to the address provided and it it bounces then it's not valid.
If you want to perform some basic checks you could just check that it's in the form *@*
If you have some business logic specific validation then you could perform that using a regex, e.g. must be a gmail.com account or something.
Incase someone wants to postion a child div directly under a parent
#father {
position: relative;
}
#son1 {
position: absolute;
top: 100%;
}
Working demo Codepen
To really get this clear, here's my for-beginners answer:
You inputed the arguments in the wrong order.
A keyword argument has this style:
nullable=True, unique=False
A fixed parameter should be defined: True, False, etc. A non-keyword argument is different:
name="Ricardo", fruit="chontaduro"
This syntax error asks you to first put name="Ricardo"
and all of its kind (non-keyword) before those like nullable=True.
Some of what is explained above is meant only for placing an SMS in a 'ready to launch' state.
as Senthil Mg said you can use sms manager to send the sms directly but SMSManager
has been moved to android.telephony.SmsManager
I know it's not a lot of more info, but it might help someone some day.
This is an example of how to set time in a div(only_time) using javascript.
function date_time() {
var date = new Date();
var am_pm = "AM";
var hour = date.getHours();
if(hour>=12){
am_pm = "PM";
}
if (hour == 0) {
hour = 12;
}
if(hour>12){
hour = hour - 12;
}
if(hour<10){
hour = "0"+hour;
}
var minute = date.getMinutes();
if (minute<10){
minute = "0"+minute;
}
var sec = date.getSeconds();
if(sec<10){
sec = "0"+sec;
}
document.getElementById("time").innerHTML = hour+":"+minute+":"+sec+" "+am_pm;
}
setInterval(date_time,500);
<per>
<div class="date" id="time"></div>
</per>
If you want to select the last child and need to be specific on the element type you can use the selector last-of-type
Here is an example:
$("div p:last-of-type").css("border", "3px solid red");
$("div span:last-of-type").css("border", "3px solid red");
<div id="example">
<p>This is paragraph 1</p>
<p>This is paragraph 2</p>
<span>This is paragraph 3</span>
<span>This is paragraph 4</span>
<p>This is paragraph 5</p>
</div>
In the example above both Paragraph 4 and Paragraph 5 will have a red border since Paragraph 5 is the last element of "p" type in the div and Paragraph 4 is the last "span" in the div.
Fixed by enabling Groovy plugin. Enabling it also enables the "SDK manager" option.
See the documentation for the print function: print()
The content of end
is printed after the thing you want to print. By default it contains a newline ("\n"
) but it can be changed to something else, like an empty string.
If the steps provided by @MainMa didn't work follow following steps
Step 1 Try killing the process from windows task manager or using taskkill /F /PID . You can find pid of the process by command 'sc queryex '. Try next step if you still can't uninstall.
Step 2 If above
Run Autoruns for Windows Search for service by name and delete results.
The &nKByte
creates a temporary value, which cannot be bound to a reference to non-const.
You could change void test(float *&x)
to void test(float * const &x)
or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);
.
You have some variables that are different types in Java language like that:
message of type string
timestamp of type time
count of type integer
version of type integer
If you use a HashMap like:
HashMap<String,Object> yourHash = new HashMap<String,Object>();
yourHash.put("message","message");
yourHash.put("timestamp",timestamp);
yourHash.put("count ",count);
yourHash.put("version ",version);
If you want to use the yourHash:
for(String key : yourHash.keySet()){
String message = (String) yourHash.get(key);
Datetime timestamp= (Datetime) yourHash.get(key);
int timestamp= (int) yourHash.get(key);
}
On the anaconda prompt, do a
conda -V
or conda --version
to get the conda version.python -V
or python --version
to get the python version.conda list anaconda$
to get the Anaconda version.conda list
to get the Name, Version, Build & Channel details of all the packages installed (in the current environment).conda info
to get all the current environment details.conda info --envs
To see a list of all your environmentsI would make your final select as:
SELECT EmplID
, EmplName
, InTime
, [TimeOut]
, [DateVisited]
, CONVERT(varchar(3),DATEDIFF(minute,InTime, TimeOut)/60) + ':' +
RIGHT('0' + CONVERT(varchar(2),DATEDIFF(minute,InTime,TimeOut)%60),2)
as TotalHours
from times
Order By EmplID, DateVisited
Any solution trying to use DATEDIFF(hour,...
is bound to be complicated (if it's correct) because DATEDIFF
counts transitions - DATEDIFF(hour,...09:59',...10:01')
will return 1 because of the transition of the hour from 9 to 10. So I'm just using DATEDIFF
on minutes.
The above can still be subtly wrong if seconds are involved (it can slightly overcount because its counting minute transitions) so if you need second or millisecond accuracy you need to adjust the DATEDIFF
to use those units and then apply suitable division constants (as per the hours one above) to just return hours and minutes.
The error is down to an "inappropriate use" of the double colon operator:
return $cnf::getConfig($key);
as by using the ::
you're attempting to call a static method of the class itself. In your example you want to call a non-static method on an instantiated object.
I think what you want is:
return $cnf->getConfig($key);
You can also use...
SQL_VARIANT_PROPERTY()
...in cases where you don't have direct access to the metadata (e.g. a linked server query perhaps?).
In SQL Server 2005 and beyond you are better off using the catalog views (sys.columns) as opposed to INFORMATION_SCHEMA. Unless portability to other platforms is important. Just keep in mind that the INFORMATION_SCHEMA views won't change and so they will progressively be lacking information on new features etc. in successive versions of SQL Server.
Either use window.onload
this way
<script>
window.onload = function() {
// ...
}
</script>
or alternatively
<script>
window.onload = functionName;
</script>
(yes, without the parentheses)
Or just put the script at the very bottom of page, right before </body>
. At that point, all HTML DOM elements are ready to be accessed by document
functions.
<body>
...
<script>
functionName();
</script>
</body>
This if an Info message that could pop in your LogCat on many situations.
In my case, it happened when I was inflating several views from XML layout files programmatically. The message is harmless by itself, but could be the sign of a later problem that would use all the RAM your App is allowed to use and cause the mega-evil Force Close to happen. I have grown to be the kind of Developer that likes to see his Log WARN/INFO/ERROR Free. ;)
So, this is my own experience:
I got the message:
10-09 01:25:08.373: I/Choreographer(11134): Skipped XXX frames! The application may be doing too much work on its main thread.
... when I was creating my own custom "super-complex multi-section list" by inflating a view from XML and populating its fields (images, text, etc...) with the data coming from the response of a REST/JSON web service (without paging capabilities) this views would act as rows, sub-section headers and section headers by adding all of them in the correct order to a LinearLayout (with vertical orientation inside a ScrollView). All of that to simulate a listView with clickable elements... but well, that's for another question.
As a responsible Developer you want to make the App really efficient with the system resources, so the best practice for lists (when your lists are not so complex) is to use a ListActivity or ListFragment with a Loader and fill the ListView with an Adapter, this is supposedly more efficient, in fact it is and you should do it all the time, again... if your list is not so complex.
Solution: I implemented paging on my REST/JSON web service to prevent "big response sizes" and I wrapped the code that added the "rows", "section headers" and "sub-section headers" views on an AsyncTask to keep the Main Thread cool.
So... I hope my experience helps someone else that is cracking their heads open with this Info message.
Happy hacking!
SQL Server doesn't support the SQL standard interval data type. Your best bet is to calculate the difference in seconds, and use a function to format the result. The native function CONVERT() might appear to work fine as long as your interval is less than 24 hours. But CONVERT() isn't a good solution for this.
create table test (
id integer not null,
ts datetime not null
);
insert into test values (1, '2012-01-01 08:00');
insert into test values (1, '2012-01-01 09:00');
insert into test values (1, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 10:30');
insert into test values (2, '2012-01-01 09:00');
insert into test values (3, '2012-01-01 09:00');
insert into test values (3, '2012-01-02 12:00');
Values were chosen in such a way that for
This SELECT statement includes one column that calculates seconds, and one that uses CONVERT() with subtraction.
select t.id,
min(ts) start_time,
max(ts) end_time,
datediff(second, min(ts),max(ts)) elapsed_sec,
convert(varchar, max(ts) - min(ts), 108) do_not_use
from test t
group by t.id;
ID START_TIME END_TIME ELAPSED_SEC DO_NOT_USE
1 January, 01 2012 08:00:00 January, 01 2012 09:00:00 3600 01:00:00
2 January, 01 2012 08:30:00 January, 01 2012 10:30:00 7200 02:00:00
3 January, 01 2012 09:00:00 January, 02 2012 12:00:00 97200 03:00:00
Note the misleading "03:00:00" for the 27-hour difference on id number 3.
dos2unix is a commandline utility that will do this, or :%s/^M//g
will if you use Ctrl-v Ctrl-m to input the ^M, or you can :set ff=unix
and Vim will do it for you.
There is documentation on the fileformat setting, and the Vim wiki has a comprehensive page on line ending conversions.
Alternately, if you move files back and forth a lot, you might not want to convert them, but rather to do :set ff=dos
, so Vim will know it's a DOS file and use DOS conventions for line endings.
If you just want to prevent the sleep mode on a specific View
, just call setKeepScreenOn(true)
on that View
or set the keepScreenOn
property to true
. This will prevent the screen from going off while the View
is on the screen. No special permission required for this.
Button cancelBTN = new Button();
cancelBTN.Size = new Size(0, 0);
cancelBTN.TabStop = false;
this.Controls.Add(cancelBTN);
this.CancelButton = cancelBTN;
public void AnalyseArray(ArrayList<Integer> array) {
// Do something
}
...
ArrayList<Integer> A = new ArrayList<Integer>();
AnalyseArray(A);
I achieved it by using method swizzling(Swift 4.2):
To create an UIViewController extension as follows
extension UIViewController {
@objc private func swizzled_presentstyle(_ viewControllerToPresent: UIViewController, animated: Bool, completion: (() -> Void)?) {
if #available(iOS 13.0, *) {
if viewControllerToPresent.modalPresentationStyle == .automatic || viewControllerToPresent.modalPresentationStyle == .pageSheet {
viewControllerToPresent.modalPresentationStyle = .fullScreen
}
}
self.swizzled_presentstyle(viewControllerToPresent, animated: animated, completion: completion)
}
static func setPresentationStyle_fullScreen() {
let instance: UIViewController = UIViewController()
let aClass: AnyClass! = object_getClass(instance)
let originalSelector = #selector(UIViewController.present(_:animated:completion:))
let swizzledSelector = #selector(UIViewController.swizzled_presentstyle(_:animated:completion:))
let originalMethod = class_getInstanceMethod(aClass, originalSelector)
let swizzledMethod = class_getInstanceMethod(aClass, swizzledSelector)
if let originalMethod = originalMethod, let swizzledMethod = swizzledMethod {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
}
and in AppDelegate, in application:didFinishLaunchingWithOptions: invoke the swizzling code by calling:
UIViewController.setPresentationStyle_fullScreen()
When you create a new File
, you are supposed to provide the file name, not only the directory you want to put your file in.
Try with something like
File file = new File("D:/Data/" + item.getFileName());
There is nothing particularly tricky about the example you posted.
In a ternary operator, the first argument (the conditional) is evaluated and if the result is true
, the second argument is evaluated and returned, otherwise, the third is evaluated and returned. Each of those arguments can be any valid code block, including function calls.
Think of it this way:
var x = (1 < 2) ? true : false;
Could also be written as:
var x = (1 < 2) ? getTrueValue() : getFalseValue();
This is perfectly valid, and those functions can contain any arbitrary code, whether it is related to returning a value or not. Additionally, the results of the ternary operation don't have to be assigned to anything, just as function results do not have to be assigned to anything:
(1 < 2) ? getTrueValue() : getFalseValue();
Now simply replace those with any arbitrary functions, and you are left with something like your example:
(1 < 2) ? removeItem($this) : addItem($this);
Now your last example really doesn't need a ternary at all, as it can be written like this:
x = (1 < 2); // x will be set to "true"
rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.
There is a performance comparison with YAJL and JsonCPP.
Update:
I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.
function getBackgroundColor($dom) {
var bgColor = "";
while ($dom[0].tagName.toLowerCase() != "html") {
bgColor = $dom.css("background-color");
if (bgColor != "rgba(0, 0, 0, 0)" && bgColor != "transparent") {
break;
}
$dom = $dom.parent();
}
return bgColor;
}
working properly under Chrome and Firefox
I think your best bet here may be to define a single global-scoped variable, and dumping your variables there:
var MyApp = {}; // Globally scoped object
function foo(){
MyApp.color = 'green';
}
function bar(){
alert(MyApp.color); // Alerts 'green'
}
No one should yell at you for doing something like the above.
The HttpContext.Current.User.Identity.Name returns null
This depends on whether the authentication mode is set to Forms or Windows in your web.config file.
For example, if I write the authentication like this:
<authentication mode="Forms"/>
Then because the authentication mode="Forms", I will get null for the username. But if I change the authentication mode to Windows like this:
<authentication mode="Windows"/>
I can run the application again and check for the username, and I will get the username successfully.
For more information, see System.Web.HttpContext.Current.User.Identity.Name Vs System.Environment.UserName in ASP.NET.
pip install easy-tictoc
In the code:
from tictoc import tic, toc
tic()
#Some code
toc()
Disclaimer: I'm the author of this library.
you can try this: .timeout 100
to set timeout .
I don't know what happen in command line but in C# .Net when I do this: "UPDATE table-name SET column-name = value;"
I get Database is locked but this "UPDATE table-name SET column-name = value"
it goes fine.
It looks like when you add ;, sqlite'll look for further command.
The answers with enumerate
are nice, but I personally don't like the lambda used to sort by the value. The following just reverses the index and the value, and sorts that. So it'll first sort by value, then by index.
sorted((e,i) for i,e in enumerate(myList))
You would use data validation for this. Click in the cell you want to have a multiple drop down > DATA > Validation > Criteria (List from a Range) - here you select form a list of items you want in the drop down. And .. you are good. I have included an example to reference.
select v.SQL_TEXT,
v.PARSING_SCHEMA_NAME,
v.FIRST_LOAD_TIME,
v.DISK_READS,
v.ROWS_PROCESSED,
v.ELAPSED_TIME,
v.service
from v$sql v
where to_date(v.FIRST_LOAD_TIME,'YYYY-MM-DD hh24:mi:ss')>ADD_MONTHS(trunc(sysdate,'MM'),-2)
where
clause is optional. You can sort the results according to FIRST_LOAD_TIME and find the records up to 2 months ago.
$mylabel.text("-123456");
var string = $mylabel.text().replace('-', '');
if you have done it that way variable string
now holds "123456"
you can also (i guess the better way) do this...
$mylabel.text("-123456");
$mylabel.text(function(i,v){
return v.replace('-','');
});
Is this a console program project or a Windows project? I'm asking because for a Win32 and similar project, the entry point is WinMain()
.
If it says Subsystem Windows
your entry point should be WinMain(), i.e.
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd)
{
your code here ...
}
Besides, speaking of the comments. This is a compile (or more precisely a Link) error, not a run-time error. When you start to debug, the compiler needs to make a complete program (not just to compile your module) and that is when the error occurs.
It does not even get to the point being loaded and run.
In my case I put required="required" inside CKEditor control.
Removing this attribute fixed the issue.
Before
<CKEditor:CKEditorControl ID="txtDescription" BasePath="/ckeditor/" runat="server" required="required"></CKEditor:CKEditorControl>
After
<CKEditor:CKEditorControl ID="txtDescription" BasePath="/ckeditor/" runat="server"></CKEditor:CKEditorControl>
You could use x ** (1. / 3)
to compute the (floating-point) cube root of x
.
The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:
def is_perfect_cube(x):
x = abs(x)
return int(round(x ** (1. / 3))) ** 3 == x
print(is_perfect_cube(63))
print(is_perfect_cube(64))
print(is_perfect_cube(65))
print(is_perfect_cube(-63))
print(is_perfect_cube(-64))
print(is_perfect_cube(-65))
print(is_perfect_cube(2146689000)) # no other currently posted solution
# handles this correctly
This takes the cube root of x
, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x
.
The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).
Amazon EC2 cannot offer Mac OS X EC2 instances due to Apple's tight licensing to only allow it to legally run on Apple hardware and the current EC2 infrastructure relies upon virtualized hardware.
Apple Mac image on Amazon EC2?
Can you run OS X on an Amazon EC2 instance?
There are other companies that do provide Mac OS X hosting, presumably on Apple hardware. One example is Go Daddy:
Go Daddy Product Catalog (see Mac® Powered Cloud Servers under Web Hosting)
To find more, search for "Mac OS X hosting" and you'll find more options.
In a Rails 2.3 app it is just ./script/server start
You can use Object.assign()
to merge them into a new object:
const response = {_x000D_
lat: -51.3303,_x000D_
lng: 0.39440_x000D_
}_x000D_
_x000D_
const item = {_x000D_
id: 'qwenhee-9763ae-lenfya',_x000D_
address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
}_x000D_
_x000D_
const newItem = Object.assign({}, item, { location: response });_x000D_
_x000D_
console.log(newItem );
_x000D_
You can also use object spread, which is a Stage 4 proposal for ECMAScript:
const response = {_x000D_
lat: -51.3303,_x000D_
lng: 0.39440_x000D_
}_x000D_
_x000D_
const item = {_x000D_
id: 'qwenhee-9763ae-lenfya',_x000D_
address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
}_x000D_
_x000D_
const newItem = { ...item, location: response }; // or { ...response } if you want to clone response as well_x000D_
_x000D_
console.log(newItem );
_x000D_
1 gotcha: when you use "p" to put the line, it puts it after the line your cursor is on, so if you want to add the line after the line you're yanking, don't move the cursor down a line before putting the new line.
In a thread on comp.lang.java.help
, Hunter Gratzner gives some arguments against the presence of a Pair
construct in Java. The main argument is that a class Pair
doesn't convey any semantics about the relationship between the two values (how do you know what "first" and "second" mean ?).
A better practice is to write a very simple class, like the one Mike proposed, for each application you would have made of the Pair
class. Map.Entry
is an example of a pair that carry its meaning in its name.
To sum up, in my opinion it is better to have a class Position(x,y)
, a class Range(begin,end)
and a class Entry(key,value)
rather than a generic Pair(first,second)
that doesn't tell me anything about what it's supposed to do.
you can always use iteration param:
ITER=0
for I in ${FOO[@]}
do
echo ${I} ${ITER}
ITER=$(expr $ITER + 1)
done
Starting with CMake 3.15, the correct way of achieving this would be using:
cmake --install <dir> --prefix "/usr"
<?php
$ddate = "2012-10-18";
$duedt = explode("-",$ddate);
$date = mktime(0, 0, 0, $duedt[1], $duedt[2],$duedt[0]);
$week = (int)date('W', $date);
echo "Weeknummer: ".$week;
?>
You had the params to mktime wrong - needs to be Month/Day/Year, not Day/Month/Year
It's probably more than solved. Just want to contribute with another simple solution:
var text = 'uololooo';
// With ES6
[...text].forEach(c => console.log(c))
// With the `of` operator
for (const c of text) {
console.log(c)
}
// With ES5
for (var x = 0, c=''; c = text.charAt(x); x++) {
console.log(c);
}
// ES5 without the for loop:
text.split('').forEach(function(c) {
console.log(c);
});
You can do :
1) javac -cp /path/to/jar/file Myprogram.java
2) java -cp .:/path/to/jar/file Myprogram
So, lets suppose your current working directory
in terminal is src/Report/
javac -cp src/external/myfile.jar Reporter.java
java -cp .:src/external/myfile.jar Reporter
Take a look here to setup Classpath
Recent Clang compiler has a __FILE_NAME__
macro (see here).
The error is indeed fixed by inserting this
with a type annotation as the first callback parameter. My attempt to do that was botched by simultaneously changing the callback into an arrow-function:
foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS
It should've been this:
foo.on('error', function(this: Foo, err: any) {
or this:
foo.on('error', function(this: typeof foo, err: any) {
A GitHub issue was created to improve the compiler's error message and highlight the actual grammar error with this
and arrow-functions.
If you have a package.json, you can install all the current project dependencies using:
npm install
Here's one way to do it:
if not any(d['main_color'] == 'red' for d in a):
# does not exist
The part in parentheses is a generator expression that returns True
for each dictionary that has the key-value pair you are looking for, otherwise False
.
If the key could also be missing the above code can give you a KeyError
. You can fix this by using get
and providing a default value. If you don't provide a default value, None
is returned.
if not any(d.get('main_color', default_value) == 'red' for d in a):
# does not exist
You may want one of these, so to correspond to the Bootstrap layout:
<div class="col-xs-12">
<hr >
</div>
<!-- or -->
<div class="col-xs-12">
<hr style="border-style: dashed; border-top-width: 2px;">
</div>
<!-- or -->
<div class="col-xs-12">
<hr class="col-xs-1" style="border-style: dashed; border-top-width: 2px;">
</div>
Without a DIV
grid element included, layout may brake on different devices.
We use a script which checks if a running container is started with the latest image. We also use upstart init scripts for starting the docker image.
#!/usr/bin/env bash
set -e
BASE_IMAGE="registry"
REGISTRY="registry.hub.docker.com"
IMAGE="$REGISTRY/$BASE_IMAGE"
CID=$(docker ps | grep $IMAGE | awk '{print $1}')
docker pull $IMAGE
for im in $CID
do
LATEST=`docker inspect --format "{{.Id}}" $IMAGE`
RUNNING=`docker inspect --format "{{.Image}}" $im`
NAME=`docker inspect --format '{{.Name}}' $im | sed "s/\///g"`
echo "Latest:" $LATEST
echo "Running:" $RUNNING
if [ "$RUNNING" != "$LATEST" ];then
echo "upgrading $NAME"
stop docker-$NAME
docker rm -f $NAME
start docker-$NAME
else
echo "$NAME up to date"
fi
done
And init looks like
docker run -t -i --name $NAME $im /bin/bash
std::fill_n(array, elementCount, 0);
Assuming array
is a normal array (e.g. int[]
)
I totally missed the export button at the bottom of each visualization. As for read only access...Shield from Elasticsearch might be worth exploring.
You can pass string parameters to JavaScript functions like below code:
I passed three parameters where the third one is a string parameter.
var btn ="<input type='button' onclick='RoomIsReadyFunc(" + ID + "," + RefId + ",\"" + YourString + "\");' value='Room is Ready' />";
// Your JavaScript function
function RoomIsReadyFunc(ID, RefId, YourString)
{
alert(ID);
alert(RefId);
alert(YourString);
}
you can run your past mysql with run /PATH_PAST_MYSQL/bin/mysqld.exe
it run your last mysql and you can see it in phpmyadmin and other section of your system.
notice: stop your current mysql version.
S F My English.
string s = "Hello Marco !";
s = s.Remove(s.length - 2, 2);
You've correctly diagnosed your problem, so good job. Once you call into your search code, the for loop just keeps right on going.
I'm a big fan of https://github.com/caolan/async, and it serves me well. Basically with it you'd end up with something like:
var async = require('async')
async.eachSeries(Object.keys(config), function (key, next){
search(config[key].query, function(err, result) { // <----- I added an err here
if (err) return next(err) // <---- don't keep going if there was an error
var json = JSON.stringify({
"result": result
});
results[key] = {
"result": result
}
next() /* <---- critical piece. This is how the forEach knows to continue to
the next loop. Must be called inside search's callback so that
it doesn't loop prematurely.*/
})
}, function(err) {
console.log('iterating done');
});
I hope that helps!
if(myEditText.isSelected){
myEditText.setSelection(myEditText.length())
}
Update: Chrome 58+ hid these and other debug messages by default. To display them click the arrow next to 'Info' and select 'Verbose'.
Chrome 57 turned on 'hide violations' by default. To turn them back on you need to enable filters and uncheck the 'hide violations' box.
suddenly it appears when someone else involved in the project
I think it's more likely you updated to Chrome 56. This warning is a wonderful new feature, in my opinion, please only turn it off if you're desperate and your assessor will take marks away from you. The underlying problems are there in the other browsers but the browsers just aren't telling you there's a problem. The Chromium ticket is here but there isn't really any interesting discussion on it.
These messages are warnings instead of errors because it's not really going to cause major problems. It may cause frames to get dropped or otherwise cause a less smooth experience.
They're worth investigating and fixing to improve the quality of your application however. The way to do this is by paying attention to what circumstances the messages appear, and doing performance testing to narrow down where the issue is occurring. The simplest way to start performance testing is to insert some code like this:
function someMethodIThinkMightBeSlow() {
const startTime = performance.now();
// Do the normal stuff for this function
const duration = performance.now() - startTime;
console.log(`someMethodIThinkMightBeSlow took ${duration}ms`);
}
If you want to get more advanced, you could also use Chrome's profiler, or make use of a benchmarking library like this one.
Once you've found some code that's taking a long time (50ms is Chrome's threshold), you have a couple of options:
(1) and (2) may be difficult or impossible, but it's sometimes really easy and should be your first attempts. If needed, it should always be possible to do (3). To do this you will use something like:
setTimeout(functionToRunVerySoonButNotNow);
or
// This one is not available natively in IE, but there are polyfills available.
Promise.resolve().then(functionToRunVerySoonButNotNow);
You can read more about the asynchronous nature of JavaScript here.
As in this answer Custom HTTP Header for a specific file you can use <File>
to enable CORS for a single file with this code:
<Files "index.php">
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
</Files>
<% String s="Hi"; %>
var v ="<%=s%>";
They tell what size can be stored in a integer variable. To remember the size you can think in terms of :-) 2 beer( 2 bytes) , 4 beer(4 bytes) or 8 beer( 8 bytes).
Int16 :-2 beers/bytes = 16 bit = 2^16 = 65536 = 65536/2 = -32768 to 32767
Int32 :- 4 beers/bytes = 32 bit = 2^32 = 4294967296 = 4294967296/2 = -2147483648 to 2147483647
Int64 :- 8 beer/ bytes = 64 bit = 2^64 = 18446744073709551616 = 18446744073709551616 /2 = -9223372036854775808 to 9223372036854775807
In short you can store more than 32767 value in int16 , more than 2147483647 value in int32 and more than 9223372036854775807 value in int64.
To understand above calculation you can check out this video int16 vs int32 vs int64
I write a faster method for it can make the small one to set. But I test it in some data that some time it's faster that Intersect but some time Intersect fast that my code.
public static bool Contain<T>(List<T> a, List<T> b)
{
if (a.Count <= 10 && b.Count <= 10)
{
return a.Any(b.Contains);
}
if (a.Count > b.Count)
{
return Contain((IEnumerable<T>) b, (IEnumerable<T>) a);
}
return Contain((IEnumerable<T>) a, (IEnumerable<T>) b);
}
public static bool Contain<T>(IEnumerable<T> a, IEnumerable<T> b)
{
HashSet<T> j = new HashSet<T>(a);
return b.Any(j.Contains);
}
The Intersect calls Set
that have not check the second size and this is the Intersect's code.
Set<TSource> set = new Set<TSource>(comparer);
foreach (TSource element in second) set.Add(element);
foreach (TSource element in first)
if (set.Remove(element)) yield return element;
The difference in two methods is my method use HashSet
and check the count and Intersect
use set
that is faster than HashSet
. We dont warry its performance.
The test :
static void Main(string[] args)
{
var a = Enumerable.Range(0, 100000);
var b = Enumerable.Range(10000000, 1000);
var t = new Stopwatch();
t.Start();
Repeat(()=> { Contain(a, b); });
t.Stop();
Console.WriteLine(t.ElapsedMilliseconds);//490ms
var a1 = Enumerable.Range(0, 100000).ToList();
var a2 = b.ToList();
t.Restart();
Repeat(()=> { Contain(a1, a2); });
t.Stop();
Console.WriteLine(t.ElapsedMilliseconds);//203ms
t.Restart();
Repeat(()=>{ a.Intersect(b).Any(); });
t.Stop();
Console.WriteLine(t.ElapsedMilliseconds);//190ms
t.Restart();
Repeat(()=>{ b.Intersect(a).Any(); });
t.Stop();
Console.WriteLine(t.ElapsedMilliseconds);//497ms
t.Restart();
a.Any(b.Contains);
t.Stop();
Console.WriteLine(t.ElapsedMilliseconds);//600ms
}
private static void Repeat(Action a)
{
for (int i = 0; i < 100; i++)
{
a();
}
}
http://docs.python.org/howto/unicode.html#the-unicode-type
str = unicode(str, errors='replace')
or
str = unicode(str, errors='ignore')
Note: This will strip out (ignore) the characters in question returning the string without them.
For me this is ideal case since I'm using it as protection against non-ASCII input which is not allowed by my application.
Alternatively: Use the open method from the codecs
module to read in the file:
import codecs
with codecs.open(file_name, 'r', encoding='utf-8',
errors='ignore') as fdata:
BrowserStack.com
On this site, you can emulate a lot of iOS's devices online.
[if lt IE 8]
means "if lower than IE8" - and thats why it isn't working in IE8.
wahat you want is [if lte IE 8]
which means "if lower than or equal IE8".
cardeal's answer was really helpful. Took it a little further and figured it may help others some where down the line. Here is the fiddle:
https://jsfiddle.net/vtL5x0wh/
And the code:
<body ng-app="checkboxExample">
<script>
angular.module('checkboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.value0 = "none";
$scope.value1 = "none";
$scope.value2 = "none";
$scope.value3 = "none";
$scope.checkboxModel = {
critical1: {selected: true, id: 'C1', error:'critical' , score:20},
critical2: {selected: false, id: 'C2', error:'critical' , score:30},
critical3: {selected: false, id: 'C3', error:'critical' , score:40},
myClick : function($event) {
$scope.value0 = $event.selected;
$scope.value1 = $event.id;
$scope.value2 = $event.error;
$scope.value3 = $event.score;
}
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>
Value1:
<input type="checkbox" ng-model="checkboxModel.critical1.selected" ng-change="checkboxModel.myClick(checkboxModel.critical1)">
</label><br/>
<label>Value2:
<input type="checkbox" ng-model="checkboxModel.critical2.selected" ng-change="checkboxModel.myClick(checkboxModel.critical2)">
</label><br/>
<label>Value3:
<input type="checkbox" ng-model="checkboxModel.critical3.selected" ng-change="checkboxModel.myClick(checkboxModel.critical3)">
</label><br/><br/><br/><br/>
<tt>selected = {{value0}}</tt><br/>
<tt>id = {{value1}}</tt><br/>
<tt>error = {{value2}}</tt><br/>
<tt>score = {{value3}}</tt><br/>
</form>
Check my sample solution
<h5 style="float: left; width: 50%;">Employee: Employee Name</h5>
<h5 style="float: right; width: 50%; text-align: right;">Employee: Employee Name</h5>
This will divide your page into two and insert the two header elements to the right and left part equally.
class Outer(object):
outer_var = 1
class Inner(object):
@property
def inner_var(self):
return Outer.outer_var
This isn't quite the same as similar things work in other languages, and uses global lookup instead of scoping the access to outer_var
. (If you change what object the name Outer
is bound to, then this code will use that object the next time it is executed.)
If you instead want all Inner
objects to have a reference to an Outer
because outer_var
is really an instance attribute:
class Outer(object):
def __init__(self):
self.outer_var = 1
def get_inner(self):
return self.Inner(self)
# "self.Inner" is because Inner is a class attribute of this class
# "Outer.Inner" would also work, or move Inner to global scope
# and then just use "Inner"
class Inner(object):
def __init__(self, outer):
self.outer = outer
@property
def inner_var(self):
return self.outer.outer_var
Note that nesting classes is somewhat uncommon in Python, and doesn't automatically imply any sort of special relationship between the classes. You're better off not nesting. (You can still set a class attribute on Outer
to Inner
, if you want.)
#temp is materalized and CTE is not.
CTE is just syntax so in theory it is just a subquery. It is executed. #temp is materialized. So an expensive CTE in a join that is execute many times may be better in a #temp. On the other side if it is an easy evaluation that is not executed but a few times then not worth the overhead of #temp.
The are some people on SO that don't like table variable but I like them as the are materialized and faster to create than #temp. There are times when the query optimizer does better with a #temp compared to a table variable.
The ability to create a PK on a #temp or table variable gives the query optimizer more information than a CTE (as you cannot declare a PK on a CTE).
With Microsoft Sql Server:
--
-- Create test case
--
DECLARE @myDateTime DATETIME
SET @myDateTime = '2008-05-03'
--
-- Convert string
--
SELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10)
On Windows, solved by running this file which allowed me to update the SDK via GUI: C:\Users\%UserName%\AppData\Local\Android\sdk\tools\android.bat
Android started OK after the SDK update.
Note: running C:\Users\%UserName%\AppData\Local\Android\sdk\SDK Manager.exe did nothing on my system.
Adding a space before the EOF delimiter allows to avoid cmd:
- shell: |
cat <<' EOF'
This is a test.
EOF
Another way
@Html.TextAreaFor(model => model.Comments[0].Comment)
And in your css do this
textarea
{
font-family: inherit;
width: 650px;
height: 65px;
}
That DataType dealie allows carriage returns in the data, not everybody likes those.
.Net framework of the referencing dll should be same as the .Net framework version of the Project in which dll is referred
You can use class(x) to check the variable type. If requirement is to check all variables type of a data frame then sapply(x, class) can be used.
There are two ways to mount files into your container. It looks like you want a bind mount.
This mounts local files directly into the container's filesystem. The containerside path and the hostside path both point to the same file. Edits made from either side will show up on both sides.
? echo foo > ./foo
? docker run --mount type=bind,source=$(pwd)/foo,target=/foo -it debian:latest
# cat /foo
foo # local file shows up in container
? echo 'bar' > ./foo # make a hostside change
# cat /foo
bar # the hostside change shows up
# echo baz > /foo # make a containerside change
# exit
? cat foo
baz # the containerside change shows up
? docker run --mount type=volume,source=foovolume,target=/foo -it debian:latest
root@containerB# echo 'this is in a volume' > /foo/data
? docker volume ls
DRIVER VOLUME NAME
local foovolume
? docker run --mount type=volume,source=foovolume,target=/foo -it debian:latest
root@containerC:/# cat /foo/data
this is in a volume # data is still available
-v
vs --mount
These do the same thing. -v
is more concise, --mount
is more explicit.
bind mounts
-v /hostside/path:/containerside/path
--mount type=bind,source=/hostside/path,target=/containerside/path
volume mounts
-v /containerside/path
-v volumename:/containerside/path
--mount type=volume,source=volumename,target=/containerside/path
(If a volume name is not specified, a random one is chosen.)
The documentaion tries to convince you to use one thing in favor of another instead of just telling you how it works, which is confusing.
First I'd say you probably want to turn off persistent connections as they almost always do more harm than good.
Secondly I'd say you want to double check your MySQL users, just to make sure it's not possible for anyone to be connecting from a remote server. This is also a major security thing to check.
Thirdly I'd say you want to turn on the MySQL Slow Query Log to keep an eye on any queries that are taking a long time, and use that to make sure you don't have any queries locking up key tables for too long.
Some other things you can check would be to run the following query while the CPU load is high:
SHOW PROCESSLIST;
This will show you any queries that are currently running or in the queue to run, what the query is and what it's doing (this command will truncate the query if it's too long, you can use SHOW FULL PROCESSLIST to see the full query text).
You'll also want to keep an eye on things like your buffer sizes, table cache, query cache and innodb_buffer_pool_size (if you're using innodb tables) as all of these memory allocations can have an affect on query performance which can cause MySQL to eat up CPU.
You'll also probably want to give the following a read over as they contain some good information.
It's also a very good idea to use a profiler. Something you can turn on when you want that will show you what queries your application is running, if there's duplicate queries, how long they're taking, etc, etc. An example of something like this is one I've been working on called PHP Profiler but there are many out there. If you're using a piece of software like Drupal, Joomla or Wordpress you'll want to ask around within the community as there's probably modules available for them that allow you to get this information without needing to manually integrate anything.
The data itself is one or more lucene indices, since you can have multiple shards. What you also need to backup is the cluster state, which contains all sorts of information regarding the cluster, the available indices, their mappings, the shards they are composed of etc.
It's all within the data
directory though, you can just copy it. Its structure is pretty intuitive. Right before copying it's better to disable automatic flush (in order to backup a consistent view of the index and avoiding writes on it while copying files), issue a manual flush, disable allocation as well. Remember to copy the directory from all nodes.
Also, next major version of elasticsearch is going to provide a new snapshot/restore api that will allow you to perform incremental snapshots and restore them too via api. Here is the related github issue: https://github.com/elasticsearch/elasticsearch/issues/3826.
It's usually the metacharacter .
when not inside a character class.
So use ^.{1,35}$
. However, dot does not include newlines unless the dot-all modifier is applied against it.
You can use ^[\S\s]{1,35}$
without any modifiers, and this includes newlines as well.
Ohh what a mess! My advise: When its comes to messy poms or project packaging, Eclipse is really bad at showing the real problem. It will tell you some dependencies are missing, when in fact for pom is malformed or some other problem are present in your pom.
Leave Eclipse alone are run a maven install. You will get to the real problem really quick!
Don't forget about spaces:
source=""
samples=("")
if [ $1 = "country" ]; then
source="country"
samples="US Canada Mexico..."
else
echo "try again"
fi
Simple answer:A grammar is said to be an LL(1),if the associated LL(1) parsing table has atmost one production in each table entry.
Take the simple grammar A -->Aa|b.[A is non-terminal & a,b are terminals]
then find the First and follow sets A.
First{A}={b}.
Follow{A}={$,a}.
Parsing table for Our grammar.Terminals as columns and Nonterminal S as a row element.
a b $
--------------------------------------------
S | A-->a |
| A-->Aa. |
--------------------------------------------
As [S,b] contains two Productions there is a confusion as to which rule to choose.So it is not LL(1).
Some simple checks to see whether a grammar is LL(1) or not. Check 1: The Grammar should not be left Recursive. Example: E --> E+T. is not LL(1) because it is Left recursive. Check 2: The Grammar should be Left Factored.
Left factoring is required when two or more grammar rule choices share a common prefix string. Example: S-->A+int|A.
Check 3:The Grammar should not be ambiguous.
These are some simple checks.
First, checkout to your Branch3:
git checkout Branch3
Then merge the Branch1:
git merge Branch1
And if you want the updated commits of Branch1 on Branch2, you are probaly looking for git rebase
git checkout Branch2
git rebase Branch1
This will update your Branch2 with the latest updates of Branch1.
You need to update the package list in your Ubuntu:
$ sudo apt-get update
$ sudo apt-get install <package_name>
I struggled with this on Mac OS X where the find command doesn't support -printf
.
A solution that I found, that admittedly relies on the 'group' for all files being 'staff' was...
ls -l -R | sed 's/\(.*\)staff *\([0-9]*\)..............\(.*\)/\2 \3/'
This splits the ls long output into three tokens
And then outputs tokens 2 and 3, i.e. output is number of bytes and then filename
8071 sections.php
54681 services.php
37961 style.css
13260 thumb.php
70951 workshops.php
Bash supports a concept called "Positional Parameters". These positional parameters represent arguments that are specified on the command line when a Bash script is invoked.
Positional parameters are referred to by the names $0
, $1
, $2
... and so on. $0
is the name of the script itself, $1
is the first argument to the script, $2
the second, etc. $*
represents all of the positional parameters, except for $0
(i.e. starting with $1
).
An example:
#!/bin/bash
FILE="$1"
externalprogram "$FILE" <other-parameters>
Not tested, but I think this will be close?
SELECT m1.id
FROM mytable m1
INNER JOIN mytable m2 ON m1.id < m2.id
GROUP BY m1.id
HAVING SUM(m1.cash) > 500
ORDER BY m1.id
LIMIT 1,2
The idea is to SUM up all the previous rows, get only the ones where the sum of the previous rows is > 500, then skip one and return the next one.
String path = "C:\\Documents and Settings\\Manoj\\Desktop";
String javaPath = path.replace("\\", "/"); // Create a new variable
or
path = path.replace("\\", "/"); // Just use the existing variable
String
s are immutable. Once they are created, you can't change them. This means replace
returns a new String where the target("\\"
) is replaced by the replacement("/"
). Simply calling replace
will not change path
.
The difference between replaceAll
and replace
is that replaceAll will search for a regex, replace doesn't.
This works flawlessly @ 2019
.marketing-panel {
background-image: url("../images/background.jpg");
background-repeat: no-repeat;
background-size: auto;
background-position: center;
}
$sidemenu
is not an object
, so you can't call methods on it. It is probably not being sent to your view
, or $sidemenus
is empty.
Go to Horizontal axis properties,choose 'Category' in AXIS type,choose "Disabled" in SIDE Margin option
I also ran into a similar issue. The issue seems to be permissions. If you do an ls -l
, you may be able to identify that your file may NOT have the execute bit turned on. This will NOT allow the script to execute. :)
As @artooro added in comment:
To fix that issue run
chmod +x testscript.sh
Kindly use offset-md-4
instead of col-md-offset-4
in bootstrap 4. It's little changes adopted in bootstrap 4.
Solved by correcting date time on the phone (it was some default date 01.01.1980), and cleaning the project.
Recently I was working on a game compatible with CocoonJS with DOM limited to the canvas element - here is my approach:
Using fillText with a font that has not been loaded yet will execute properly but with no visual feedback - so the canvas plane will stay intact - all you have to do is periodically check the canvas for any changes (for example looping through getImageData searching for any non transparent pixel) that will happen when the font loads properly.
I have explained this technique a little bit more in my recent article http://rezoner.net/preloading-font-face-using-canvas,686
You would use the read.csv
function; for example:
dat = read.csv("spam.csv", header = TRUE)
You can also reference this tutorial for more details.
Note: make sure the .csv
file to read is in your working directory (using getwd()
) or specify the right path to file. If you want, you can set the current directory using setwd
.
Problem Cause:
The problem is that the cell has not been created yet. TableView first calculates the height for row and then populates the data for each row, so the rows array has not been created when heightForRow method gets called. So your app is trying to access a memory location which it does not have the permission to and therefor you get the EXC_BAD_ACCESS
message.
How to achieve self sizing TableViewCell
in UITableView
:
Just set proper constraints for your views contained in TableViewCell
's view in StoryBoard
. Remember you shouldn't set height constraints to TableViewCell's root view, its height should be properly computable by the height of its subviews -- This is like what you do to set proper constraints for UIScrollView
. This way your cells will get different heights according to their subviews. No additional action needed
This is the only solution that keeps a tab from ever getting inserted for me, without a sequence or conversion of tabs to spaces. Both of those seemed adequate, but wasteful:
(setq-default
indent-tabs-mode nil
tab-width 4
tab-stop-list (quote (4 8))
)
Note that quote
needs two numbers to work (but not more!).
Also, in most major modes (Python
for instance), indentation is automatic in Emacs. If you need to indent outside of the auto indent, use:
M-i
This message means that there are certain possible method calls which may fail at run-time. Suppose you have
class A { public function foo($a = 1) {;}}
class B extends A { public function foo($a) {;}}
function bar(A $a) {$a->foo();}
The compiler only checks the call $a->foo() against the requirements of A::foo() which requires no parameters. $a may however be an object of class B which requires a parameter and so the call would fail at runtime.
This however can never fail and does not trigger the error
class A { public function foo($a) {;}}
class B extends A { public function foo($a = 1) {;}}
function bar(A $a) {$a->foo();}
So no method may have more required parameters than its parent method.
The same message is also generated when type hints do not match, but in this case PHP is even more restrictive. This gives an error:
class A { public function foo(StdClass $a) {;}}
class B extends A { public function foo($a) {;}}
as does this:
class A { public function foo($a) {;}}
class B extends A { public function foo(StdClass $a) {;}}
That seems more restrictive than it needs to be and I assume is due to internals.
Visibility differences cause a different error, but for the same basic reason. No method can be less visible than its parent method.
How can I display these open transactions and commit or cancel them?
There is no open transaction, MySQL will rollback the transaction upon disconnect.
You cannot commit the transaction (IFAIK).
You display threads using
SHOW FULL PROCESSLIST
See: http://dev.mysql.com/doc/refman/5.1/en/thread-information.html
It will not help you, because you cannot commit a transaction from a broken connection.
What happens when a connection breaks
From the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/mysql-tips.html
4.5.1.6.3. Disabling mysql Auto-Reconnect
If the mysql client loses its connection to the server while sending a statement, it immediately and automatically tries to reconnect once to the server and send the statement again. However, even if mysql succeeds in reconnecting, your first connection has ended and all your previous session objects and settings are lost: temporary tables, the autocommit mode, and user-defined and session variables. Also, any current transaction rolls back.
This behavior may be dangerous for you, as in the following example where the server was shut down and restarted between the first and second statements without you knowing it:
Also see: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html
How to diagnose and fix this
To check for auto-reconnection:
If an automatic reconnection does occur (for example, as a result of calling mysql_ping()), there is no explicit indication of it. To check for reconnection, call
mysql_thread_id()
to get the original connection identifier before callingmysql_ping()
, then callmysql_thread_id()
again to see whether the identifier has changed.
Make sure you keep your last query (transaction) in the client so that you can resubmit it if need be.
And disable auto-reconnect mode, because that is dangerous, implement your own reconnect instead, so that you know when a drop occurs and you can resubmit that query.
I think I am too late to answer this question but anyways here goes nothing.
I have run in to the same problem before and I think there are two alternative solutions you can choose from.
from time import *
sleep(10)
exit_now = raw_input("Do you like to exit now (Y)es (N)o ? ")'
if exit_now.lower() = 'n'
//more processing here
Alternatively you can use a hybrid of those two methods as well where you can prompt for a message and use sleep(sometime) to delay the window closing as well. choice is yours.
please note the above are just ideas and if you want to use any of those in practice you might have to think about your application logic a bit.
Find out Year - Month- Day between two Days in Orale Sql
select
trunc(trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))/12) years ,
trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))
-
(trunc(trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))/12))*12
months,
round(To_date('20120101', 'YYYYMMDD')-add_months(to_date('19910228','YYYYMMDD'),
trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD'))))) days
from dual;
This is an old question and its been answered but I thought I'd put the --binary-files=text option here for anyone who wants to use it. The -I option ignores the binary file but if you want the grep to treat the binary file as a text file use --binary-files=text like so:
bash$ grep -i reset mediaLog*
Binary file mediaLog_dc1.txt matches
bash$ grep --binary-files=text -i reset mediaLog*
mediaLog_dc1.txt:2016-06-29 15:46:02,470 - Media [uploadChunk ,315] - ERROR - ('Connection aborted.', error(104, 'Connection reset by peer'))
mediaLog_dc1.txt:ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
bash$
String test_string = "tesintg#$234524@#";
if (System.Text.RegularExpressions.Regex.IsMatch(test_string, "^[a-zA-Z0-9\x20]+$"))
{
// Good-to-go
}
An example can be found here: http://ideone.com/B1HxA
Open with append:
pFile2 = fopen("myfile2.txt", "a");
then just write to pFile2
, no need to fseek()
.
Here's what I did:
That's it. I have tested it with my Nokia and it's working for me.
This may not be what you are looking for, but in the interest of coming at a problem from another angle....
Are these two Java processes that might want to access the same file in the same application? Perhaps you can just filter all access to the file through a single, synchronized method (or, even better, using JSR-166)? That way, you can control access to the file, and perhaps even queue access requests.
After reading the documentation of VideoCapture
. I figured out that you can tell VideoCapture
, which frame to process next time we call VideoCapture.read()
(or VideoCapture.grab()
).
The problem is that when you want to read()
a frame which is not ready, the VideoCapture
object stuck on that frame and never proceed. So you have to force it to start again from the previous frame.
Here is the code
import cv2
cap = cv2.VideoCapture("./out.mp4")
while not cap.isOpened():
cap = cv2.VideoCapture("./out.mp4")
cv2.waitKey(1000)
print "Wait for the header"
pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
while True:
flag, frame = cap.read()
if flag:
# The frame is ready and already captured
cv2.imshow('video', frame)
pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
print str(pos_frame)+" frames"
else:
# The next frame is not ready, so we try to read it again
cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, pos_frame-1)
print "frame is not ready"
# It is better to wait for a while for the next frame to be ready
cv2.waitKey(1000)
if cv2.waitKey(10) == 27:
break
if cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES) == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
# If the number of captured frames is equal to the total number of frames,
# we stop
break
Use this format: ${__time(yyyy-MM-dd'T'hh:mm:ss.SS'Z')}
Which will give you: 2018-01-16T08:32:28.75Z
Includes C, C++, Delphi, EditPad, Java, JavaScript, Perl, PHP (preg), PostgreSQL, PowerGREP, PowerShell, Python, REALbasic, Real Studio, Ruby, TCL, VB.Net, VBScript, wxWidgets, XML Schema, Xojo, XRegExp.
PCRE compatibility may vary
Anywhere: . ^ $ * + - ? ( ) [ ] { } \ |
Includes awk, ed, egrep, emacs, GNUlib, grep, PHP (ereg), MySQL, Oracle, R, sed.
PCRE support may be enabled in later versions or by using extensions
ERE/awk/egrep/emacs
Outside a character class: . ^ $ * + ? ( ) [ { } \ |
Inside a character class: ^ - [ ]
BRE/ed/grep/sed
Outside a character class: . ^ $ * [ \
Inside a character class: ^ - [ ]
For literals, don't escape: + ? ( ) { } |
For standard regex behavior, escape: \+ \? \( \) \{ \} \|
\xFF
] -
only need escaping within a character class, but I kept them in a single list for simplicity"(\")(/)(\\.)"
versus /(")(\/)(\.)/
in JavaScript)do it using jQuery put inside code on the <head></head>
tag
<script type="text/javascript">
$(document).ready(function() {
var docHeight = $(window).height();
var footerHeight = $('#footer').height();
var footerTop = $('#footer').position().top + footerHeight;
if (footerTop < docHeight) {
$('#footer').css('margin-top', 10 + (docHeight - footerTop) + 'px');
}
});
</script>
I spent a whole day on this error
if you are working with n-tear architecture
or you tried to separate Models
generated by EDMX
form DataAccessLayer to DomainModelLayer
maybe you will get this error
webconfig (UILayer)
and appconfig (DataAccessLayer)
are the same Second which is Very important the connection string
connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provid.....
which is the problem
from where on earth I got Model
or whatever .csdl in my connection string where are they
here I our solution look at the picture
hope the help you
The syntax you are using is new to SQL Server 2008:
INSERT INTO [MyDB].[dbo].[MyTable]
([FieldID]
,[Description])
VALUES
(1000,N'test'),(1001,N'test2')
For SQL Server 2005, you will have to use multiple INSERT
statements:
INSERT INTO [MyDB].[dbo].[MyTable]
([FieldID]
,[Description])
VALUES
(1000,N'test')
INSERT INTO [MyDB].[dbo].[MyTable]
([FieldID]
,[Description])
VALUES
(1001,N'test2')
One other option is to use UNION ALL
:
INSERT INTO [MyDB].[dbo].[MyTable]
([FieldID]
,[Description])
SELECT 1000, N'test' UNION ALL
SELECT 1001, N'test2'
What you want to do is this:
set statistics time on
-- your query
set statistics time off
That will have the output looking something like this in your Messages window:
SQL Server Execution Times: CPU time = 6 ms, elapsed time = 6 ms.
This might work. This Code dynamically appends the <script>
tag to the head
of the html file on button clicked.
const url = 'http://iknow.com/this/does/not/work/either/file.js';
export class MyAppComponent {
loadAPI: Promise<any>;
public buttonClicked() {
this.loadAPI = new Promise((resolve) => {
console.log('resolving promise...');
this.loadScript();
});
}
public loadScript() {
console.log('preparing to load...')
let node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
node.async = true;
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
}
}
This code work correctly only when u put into button click because at that time user put values into editable text and then when user clicks button it fetch the data and convert into string
EditText dob=(EditText)findviewbyid(R.id.edit_id);
String str=dob.getText().toString();
This code works, can you compare it with yours?
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>HTML Tutorial</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<meta charset="windows-1252">
<script>
$(document).ready(function(){
var a = $("#a").val();
var b = $("#b").val();
$("#submit").on("click", function(){
var sum = a + b;
alert(sum);
})
})
</script>
</head>
<body>
<input type="text" id="a" name="option">
<input type="text" id="b" name="task">
<input id="submit" type="button" value="press me">
</body>
</html>
I tried the above solutions and I was still having difficulties. I had other files staged with two files that were deleted accidentally.
To undo the two deleted files I had to unstage all of the files:
git reset HEAD .
At that point I was able to do the checkout of the deleted items:
git checkout -- WorkingFolder/FileName.ext
Finally I was able to restage the rest of the files and continue with my commit.
The rouine is pretty good, however it causes my app to hang, so I needed to add the case:
<xsl:when test="$text = '' or $replace = ''or not($replace)" >
<xsl:value-of select="$text" />
<!-- Prevent thsi routine from hanging -->
</xsl:when>
before the function gets called recursively.
I got the answer from here: When test hanging in an infinite loop
Thank you!
It happens when MAVEN is not installed locally on the system.
I faced the same issue when i cloned a Maven based Project from GIT and then as soon as I executed I got exception "Cannot Find Class In ClassPath : Class Name"
So i did a mvn clean test and found that maven is not installed locally.
After doing sudo apt install maven Maven got installed and i was able to Run the code
Adding to Eric's answer, you can also configure this in the csproj
file:
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>MyTests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
Or if you have one test project per project to be tested, you could do something like this in your Directory.Build.props
file:
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>$(MSBuildProjectName).Test</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
See: https://stackoverflow.com/a/49978185/1678053
Example: https://github.com/gldraphael/evlog/blob/master/Directory.Build.props#L5-L12
Follow below steps:
Must put the html files in resources/templates/
Replace the @RestController
with @Controller
Remove if you are using any view resolvers.
Your controller method should return file name of view without extension like return "index"
Include the below dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>`
You can't use float
inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle
.
So if you want to position child
element to right of parent
element you can use margin-left: auto
but now child
element will also push other div
to the right as you can see here Fiddle
.
What you can do now is change order of elements and set order: 2
on child
element so it doesn't affect second div
.parent {_x000D_
display: flex;_x000D_
}_x000D_
.child {_x000D_
margin-left: auto;_x000D_
order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">Ignore parent?</div>_x000D_
<div>another child</div>_x000D_
</div>
_x000D_
Use array_splice
to empty an array and retain the reference:
array_splice($myArray, 0);
also this works too
SELECT replace(replace(replace(convert(varchar, getdate(), 120),':',''),'-',''),' ','')
<android.support.v7.widget.AppCompatCheckBox
android:id="@+id/checkBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layoutDirection="rtl"
android:text="text" />`
The '
character in SQL is used for string constants. In this case it is used for ending the string constant and not for comment.
Only second approach will work. You can modify collection during iteration using iterator.remove()
only. All other attempts will cause ConcurrentModificationException
.
Another option is to have an @reboot command in your crontab.
Not every version of cron supports this, but if your instance is based on the Amazon Linux AMI then it will work.
You can use the instanceof
operator to see if an object is an instance of another, but since there are no classes, you can't get a class name.
You can use the DATE()
function to extract the date portion of the timestamp:
SELECT * FROM table
WHERE DATE(timestamp) = '2012-05-25'
Though, if you have an index on the timestamp column, this would be faster because it could utilize an index on the timestamp column if you have one:
SELECT * FROM table
WHERE timestamp BETWEEN '2012-05-25 00:00:00' AND '2012-05-25 23:59:59'
Would you be able to use a USB->RS232 adapter? I have a few, and they just use the FTDI driver. Then, you should be able to rename /dev/ttyUSB0 (or whatever gets created) as /dev/ttyS2 .
With Dispatcher you will need to include
using System.Windows.Threading;
Also note that if you right-click DispatcherTimer and click Resolve it should add the appropriate references.
in gradle.properties, you can even delete
org.gradle.jvmargs=-Xmx1536m
such lines or comment them out. Let android studio decide for it. When I ran into this same problem, none of above solutions worked for me. Commenting out this line in gradle.properties helped in solving that error.
If your code is ES7 based (or upper versions):
channelArray.includes('three'); //will return true or false
If not, for example you are using IE with no babel transpile:
channelArray.indexOf('three') !== -1; //will return true or false
the indexOf
method will return the position the element has into the array, because of that we use !==
different from -1 if the needle is found at the first position.
This problem cause to me because of the project path . Y:\Example&SourceCode with & sign So i change the Project path to another one without special characters. Now It is Fine.
height : <percent>
will only work if you have all parent nodes with specified percent height with a fixed height in pixels, ems, etc. on top level. That way, the height will cascade down to your element.
You can specify 100% to html and body elements as @Travis stated earlier to have the page height cascading down to your nodes.
[id^='someId']
will match all ids starting with someId
.
[id$='someId']
will match all ids ending with someId
.
[id*='someId']
will match all ids containing someId
.
If you're looking for the name
attribute just substitute id
with name
.
If you're talking about the tag name of the element I don't believe there is a way using querySelector
I was curious about the relative speed of the two popular approaches - casting to string and using modular arithmetic - so I profiled them and was surprised to see how close they were in terms of performance.
(My use-case was slightly different, I wanted to get all digits in the number.)
The string approach gave:
10000002 function calls in 1.113 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
10000000 1.113 0.000 1.113 0.000 sandbox.py:1(get_digits_str)
1 0.000 0.000 0.000 0.000 cProfile.py:133(__exit__)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
While the modular arithmetic approach gave:
10000002 function calls in 1.102 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
10000000 1.102 0.000 1.102 0.000 sandbox.py:6(get_digits_mod)
1 0.000 0.000 0.000 0.000 cProfile.py:133(__exit__)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
There were 10^7 tests run with a max number size less than 10^28.
Code used for reference:
def get_digits_str(num):
for n_str in str(num):
yield int(n_str)
def get_digits_mod(num, radix=10):
remaining = num
yield remaining % radix
while remaining := remaining // radix:
yield remaining % radix
if __name__ == '__main__':
import cProfile
import random
random_inputs = [random.randrange(0, 10000000000000000000000000000) for _ in range(10000000)]
with cProfile.Profile() as str_profiler:
for rand_num in random_inputs:
get_digits_str(rand_num)
str_profiler.print_stats(sort='cumtime')
with cProfile.Profile() as mod_profiler:
for rand_num in random_inputs:
get_digits_mod(rand_num)
mod_profiler.print_stats(sort='cumtime')
The following worked for me:
$(':input').val('');
However, it is submitting the form, so it might not be what you are looking for.
Here is the solution :
Turn the "$(PROJECT_DIR)" attribute(might be non-recursive by default) into recursive option in Select Project Click on Targets Click - Build Settings Search for 'Framework Search Path' - Double click the input.
Scratched from https://stackoverflow.com/a/31298214/4493512
str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
str.to_date
=> Tue, 10 Aug 2010
For newer versions (such as Visual Studio 2017)
import psutil
def check_process_status(process_name):
"""
Return status of process based on process name.
"""
process_status = [ proc.status() for proc in psutil.process_iter() if proc.name() == process_name ]
if process_status:
print("Process name %s and staus %s"%(process_name, process_status[0]))
else:
print("Process name not valid", process_name)
read the documentation: matplotlib.pyplot.subplots
pyplot.subplots()
returns a tuple fig, ax
which is unpacked in two variables using the notation
fig, axes = plt.subplots(nrows=2, ncols=2)
the code
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
does not work because subplots()
is a function in pyplot
not a member of the object Figure
.
In static class, if you are getting information from xml or reg, class tries to initialize all properties. therefore, you should control if the config variable is there otherwise properties will not initialize so the class.
Check xml referance variable is there, Check reg referance variable is is there, Make sure you handle if they are not there.
You can use list comprehension on a dataframe to count frequencies of the columns as such
[my_series[c].value_counts() for c in list(my_series.select_dtypes(include=['O']).columns)]
Breakdown:
my_series.select_dtypes(include=['O'])
Selects just the categorical data
list(my_series.select_dtypes(include=['O']).columns)
Turns the columns from above into a list
[my_series[c].value_counts() for c in list(my_series.select_dtypes(include=['O']).columns)]
Iterates through the list above and applies value_counts() to each of the columns
On Kotlin you can set width and height of any view directly using their virtual properties:
someView.layoutParams.width = 100
someView.layoutParams.height = 200
The $PWD
is a good option by Matthew above. If you want find to only print files then you can also add the -type f option to search only normal files. Other options are "d" for directories only etc. So in your case it would be (if i want to search only for files with .c ext):
find $PWD -type f -name "*.c"
or if you want all files:
find $PWD -type f
Note: You can't make an alias for the above command, because $PWD gets auto-completed to your home directory when the alias is being set by bash.
Does this work:
$msgid = $_GET['msgid'];
$oldMessage = '';
$deletedFormat = '';
//read the entire string
$str=file_get_contents('msghistory.txt');
//replace something in the file string - this is a VERY simple example
$str=str_replace($oldMessage, $deletedFormat,$str);
//write the entire string
file_put_contents('msghistory.txt', $str);
Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx
You can also use command line utility net
to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code
I create equations with random numbers in VBA and for x squared put in x^2.
I read each square (or textbox) text into a string.
I then read each character in the string in turn and note the location of the ^ ("hats")'s in each.
Say the hats were at positions 4, 8 and 12.
I then "chop out" the first hat - the position of the character to be superscripted is now 4, the position of the other hats is now 7 and 11. I chop out the second hat, the character to superscript is now at 7 and the hat has moved to 10. I chop out the last hat .. the superscript character is now position 10.
I now select each character in turn and change the font to superscript.
Thus I can fill a whole spreadsheet with algebra using ^ and then call a routine to tidy it up.
For big powers like x to the 23 I build x^2^3 and the above routine does it.
Both are of same concept but in atomic boolean it will provide atomicity to the operation in case the cpu switch happens in between.
StrSubstitutor
from Apache Commons Lang may be used for string formatting with named placeholders:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.1</version>
</dependency>
Substitutes variables within a string by values.
This class takes a piece of text and substitutes all the variables within it. The default definition of a variable is ${variableName}. The prefix and suffix can be changed via constructors and set methods.
Variable values are typically resolved from a map, but could also be resolved from system properties, or by supplying a custom variable resolver.
Example:
String template = "Hi ${name}! Your number is ${number}";
Map<String, String> data = new HashMap<String, String>();
data.put("name", "John");
data.put("number", "1");
String formattedString = StrSubstitutor.replace(template, data);
You can use the JFileChooser class, check this example.
I would need to display the jobid, jobname and 5 fields called Priority1, Priority2, Priority3, Priority4. Priority5.
Something's wrong with your query design. You're showing a specific job in each row as well, and so you'll either have a situation where ever row has four priority columns with a '0' and one priority column with a '1' (the priority for that job) or you'll end up repeating the count for all priorities on every row.
What do you really want to show here?
$url = 'url_to_post';
$data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" => "Mother","last_name" => "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
$postdata = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
print_r ($result);
This code worked for me. You can try...
You can add a android:layoutAnimation="@anim/rv_item_animation"
attribute to RecyclerView
like this:
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layoutAnimation="@anim/layout_animation_fall_down"
/>
thanks for the excellent article here: https://proandroiddev.com/enter-animation-using-recyclerview-and-layoutanimation-part-1-list-75a874a5d213
This is all you need.
rsync -e ssh file host:/directory/.
If you can comment out code and your program still works, then yes, that code was optional.
.strip()
with no arguments (or None
as the first argument) removes all whitespace at the start and end, including spaces, tabs, newlines and carriage returns. Leaving it in doesn't do any harm, and allows your program to deal with unexpected extra whitespace inserted into the file.
For example, by using .strip()
, the following two lines in a file would lead to the same end result:
foo\tbar \n
foo\tbar\n
I'd say leave it in.