It's rather hacky, but you could use one1
as a Float64Index
to do everything in one go:
df.set_index('one').sort_index().groupby('key1')['two'].plot(style='--o', legend=True)
Note that as of 0.20.3, sorting the index is necessary, and the legend is a bit wonky.
By using exploits or on badly configured servers it could be possible to download your PHP source. You could however either obfuscate and/or encrypt your code (using Zend Guard, Ioncube or a similar app) if you want to make sure your source will not be readable (to be accurate, obfuscation by itself could be reversed given enough time/resources, but I haven't found an IonCube or Zend Guard decryptor yet...).
I see what you are trying to ask and I think this is the simplest answer to what you are looking for, given you might not know how many key pairs your are being sent.
Simple Key Pair JSON structure
var data = {
'XXXXXX' : '100.0',
'YYYYYYY' : '200.0',
'ZZZZZZZ' : '500.0',
}
Usage JavaScript code to access the key pairs
for (var key in data)
{ if (!data.hasOwnProperty(key))
{ continue; }
console.log(key + ' -> ' + data[key]);
};
Console output should look like this
XXXXXX -> 100.0
YYYYYYY -> 200.0
ZZZZZZZ -> 500.0
Here is a JSFiddle to show how it works.
alternatively you can perform a fast export without using Office dll, as Excel can parse csv files without problems.
Doing something like this (for less than 65.536 rows with titles):
Try
If (p_oGrid.RowCount = 0) Then
MsgBox("No data", MsgBoxStyle.Information, "App")
Exit Sub
End If
Cursor.Current = Cursors.WaitCursor
Dim sText As New System.Text.StringBuilder
Dim sTmp As String
Dim aVisibleData As New List(Of String)
For iAuxRow As Integer = 0 To p_oGrid.Columns.Count - 1
If p_oGrid.Columns(iAuxRow).Visible Then
aVisibleData.Add(p_oGrid.Columns(iAuxRow).Name)
sText.Append(p_oGrid.Columns(iAuxRow).HeaderText.ToUpper)
sText.Append(";")
End If
Next
sText.AppendLine()
For iAuxRow As Integer = 0 To p_oGrid.RowCount - 1
Dim oRow As DataGridViewRow = p_oGrid.Rows(iAuxRow)
For Each sCol As String In aVisibleData
Dim sVal As String
sVal = oRow.Cells(sCol).Value.ToString()
sText.Append(sVal.Replace(";", ",").Replace(vbCrLf, " ; "))
sText.Append(";")
Next
sText.AppendLine()
Next
sTmp = IO.Path.GetTempFileName & ".csv"
IO.File.WriteAllText(sTmp, sText.ToString, System.Text.Encoding.UTF8)
sText = Nothing
Process.Start(sTmp)
Catch ex As Exception
process_error(ex)
Finally
Cursor.Current = Cursors.Default
End Try
String info = "Hello \"world\"!";
info = info.replace("\"", "\\\"");
String info1 = "Hello "world!";
info1 = info1.replace('"', '\"').replace("\"", "\\\"");
For the 2nd field info1, 1st replace double quotes with an escape character.
Use %
encoding for the ^
character, viz. http://finance.yahoo.com/q/h?s=%5EIXIC
Inline SVG can be used in IE 10 and 11 and Edge 12.
I've created a project called gray which includes a polyfill for these browsers. The polyfill switches out <img>
tags with inline SVG: https://github.com/karlhorky/gray
To implement, the short version is to download the jQuery plugin at the GitHub link above and add after jQuery at the end of your body:
<script src="/js/jquery.gray.min.js"></script>
Then every image with the class grayscale
will appear as gray.
<img src="/img/color.jpg" class="grayscale">
You can see a demo too if you like.
Sometime would be better use name of parent class instead name of table:
# Refers to the current class
self.class.unscoped.where(self.class.primary_key => id).update_all(created _at: timestamp)
For example "Person" base class, subclasses (and database tables) "Client" and "Seller" Instead using:
Client.where(self.class.primary_key => id).update_all(created _at: timestamp)
Seller.where(self.class.primary_key => id).update_all(created _at: timestamp)
You can use object of base class by this way:
person.class.unscoped.where(self.class.primary_key => id).update_all(created _at: timestamp)
Even though they are separate windows but the request you send from Postman, it's details should be available in network tab of developer tools. Just make sure you are not sending any other http traffic during that time, just for clarity.
The assignment operator has lower precedence than &&
, so your condition is equivalent to:
if ((match == 0 && k) = m)
But the left-hand side of this is an rvalue, namely the boolean resulting from the evaluation of the subexpression match == 0 && k
, so you cannot assign to it.
By contrast, comparison has higher precedence, so match == 0 && k == m
is equivalent to:
if ((match == 0) && (k == m))
From my point of view the best way to manage multiple conditional props is the props object approach from @brigand. But it can be improved in order to avoid adding one if
block for each conditional prop.
rename it as you like (iv, condVal, cv, _, ...)
You can define a helper function to return a value, or another, if a condition is met:
// components-helpers.js
export const ifVal = (cond, trueValue=true, falseValue=null) => {
return cond ? trueValue : falseValue
}
If cond
is true
(or truthy), the trueValue
is returned - or true
.
If cond
is false
(or falsy), the falseValue
is returned - or null
.
These defaults (true
and null
) are, usually the right values to allow a prop to be passed or not to a React component. You can think to this function as an "improved React ternary operator". Please improve it if you need more control over the returned values.
Let's use it with many props.
// your-code.js
import { ifVal } from './components-helpers.js'
// BE SURE to replace all true/false with a real condition in you code
// this is just an example
const inputProps = {
value: 'foo',
enabled: ifVal(true), // true
noProp: ifVal(false), // null - ignored by React
aProp: ifVal(true, 'my value'), // 'my value'
bProp: ifVal(false, 'the true text', 'the false text') // 'my false value',
onAction: ifVal(isGuest, handleGuest, handleUser) // it depends on isGuest value
};
<MyComponent {...inputProps} />
This approach is something similar to the popular way to conditionally manage classes using the classnames utility, but adapted to props.
You'll have a clean and readable syntax, even with many conditional props: every new prop just add a line of code inside the object declaration.
In this way you replace the syntax noise of repeated operators (...
, &&
, ? :
, ...), that can be very annoying when you have many props, with a plain function call.
Our top priority, as developers, is to write the most obvious code that solve a problem. Too many times we solve problems for our ego, adding complexity where it's not required. Our code should be straightforward, for us today, for us tomorrow and for our mates.
just because we can do something doesn't mean we should
I hope this late reply will help.
This works for me. Returns the number that Excel displays in the bottom status line when a pivot
column
is filtered
and I need the count
of the visible cells
.
Global Const DashBoardSheet = "DashBoard"
Global Const ProfileColRng = "$L:$L"
.
.
.
Sub MySub()
Dim myreccnt as long
.
.
.
myreccnt = GetFilteredPivotRowCount(DashBoardSheet, ProfileColRng)
.
.
.
End Sub
Function GetFilteredPivotRowCount(sheetname As String, cntrange As String) As long
Dim reccnt As Long
reccnt = Sheets(sheetname).Range(cntrange).SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeConstants).Count - 1
GetFilteredPivotRowCount = reccnt
End Function
HTML
<div id="replaceMe">i need to be replaced</div>
<div id="iamReplacement">i am replacement</div>
JavaScript
jQuery('#replaceMe').replaceWith(jQuery('#iamReplacement'));
You can do this using the ConnectivityManager
API for android. It allows you to check whether you are connected to the internet and the type of internet connection you are connected to. Basically, Metered or Un-metered.
To check for internet connection.
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
Documentation link: https://developer.android.com/training/monitoring-device-state/connectivity-status-type
We have document.referrer for this, but it is not on which we can relay. This could be saved, could be not
$(document).ready(function() {
var referrer = document.referrer;
});
The better approach is to add a cookie to store the previous-url in the browser.
We, SnippetBucket.com working for enterprise linux RedHat, found httpd server don't allow proxy to run, neither localhost or 127.0.0.1, nor any other external domain.
[error] (13)Permission denied: proxy: AJP: attempt to connect to
10.x.x.x:8069 (virtualhost.virtualdomain.com) failed
type=AVC msg=audit(1265039669.305:14): avc: denied { name_connect } for pid=4343 comm="httpd" dest=8069
scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:port_t:s0 tclass=tcp_socket
/usr/sbin/setsebool httpd_can_network_connect 1
/usr/sbin/setsebool -P httpd_can_network_connect 1
<select id='bookcategory' class="form-control" required="">
<option value="" disabled="disabled">Category</option>
<option value="1">LITERATURE & FICTION</option>
<option value="2">NON FICTION</option>
<option value="3">ACADEMIC</option>
<option value="4">CHILDREN & TEENS</option>
</select>
HTML form validation can be performed automatically by the browser.
Try the above code:
The rest all will be done automatically, no need to create any js functions just this dropdown and a submit button.
If you use android studio, this might be useful for you.
I had a similar problem and i solved it by changing the skd path from the default C:\Program Files (x86)\Android\android-studio\sdk to C:\Program Files (x86)\Android\android-sdk .
It seems the problem came from the compiler version (gradle sets it automatically to the highest one available in the sdk folder) which doesn't support this theme, and since android studio had only the api 7 in its sdk folder, it gave me this error.
For more information on how to change Android sdk path in Android Studio: Android Studio - How to Change Android SDK Path
The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:
XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
where xml2.Element("ID").Value == variable
select xml2).FirstOrDefault();
This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.
Marc
Change the file name if your file name is like pandas.py or pd.py, it will shadow the real name otherwise.
This error can occur if you are installing a package with a different bitness than your Python version. To see whether your Python installation is 32- or 64-bit, see here.
Some superpacks (e.g. for Scipy) available on SourceForge or python.org are for 32-bit systems and some are for 64-bit systems. See this answer. In Windows, uninstalling the 32-bit and installing the 64-bit version (or vice versa if your installation is 32-bit) can solve the problem.
h = [(i + 1, x) for i, x in enumerate(xrange(2000, 2005))]
Another native solution to this, which doesn't require any 3rd party libraries but a reference to System.Web.Extensions is the JavaScriptSerializer. This is not a new but a very unknown built-in features there since 3.5.
using System.Web.Script.Serialization;
..
JavaScriptSerializer serializer = new JavaScriptSerializer();
objectString = serializer.Serialize(new MyObject());
and back
MyObject o = serializer.Deserialize<MyObject>(objectString)
Using font-face requires a little understanding of browser inconsistencies and may require some changes on the web server itself. First thing you have to do is check the console to see if/what messages are being generated. Is it a permissions issue or resource not found....?
Secondly because each browser is expecting a different font type I would use Font Squirrel to upload your font and then generate the additional files and CSS needed. http://www.fontsquirrel.com/fontface/generator
And finally, versions of FireFox and IE will not allow fonts to be loaded cross domain. You may need to modify your Apache config or .htaccess (Header set Access-Control-Allow-Origin "*")
Thanks to Instagram's ever changing (and horrifically designed) API schema most of the above will no longer work as of April 2018.
Here is the latest path to access individual post data if you are querying their API directly using the https://www.instagram.com/username/?__a=1
method.
Assuming your returned JSON
data is $data
you can loop through each result using the following path examples :
foreach ($data->graphql->user->edge_owner_to_timeline_media->edges as $item) {
$content_id = $item->node->id;
$date_posted = $item-node->taken_at_timestamp;
$comments = $item->node->edge_media_to_comment->count;
$likes = $item->node->edge_liked_by->count;
$image = $item->node->display_url;
$content = $item->node->edge_media_to_caption->edges[0]->node->text;
// etc etc ....
}
The main things in this recent change were graphql
and edge_owner_to_timeline_media
.
Looks like they are going to be killing this API access off for non 'business' customers in DEC 2018 so make the most of it while you can.
Hope it helps somebody ;)
I managed to get it working with that:
SSH_ASKPASS="echo \"my-pass-here\""
ssh -tt remotehost -l myusername
I've created an npm module to do this with some added flexibility:
// create a 3x3 array
var twodimensional = new MultiDimensional([3, 3])
// create a 3x3x4 array
var threedimensional = new MultiDimensional([3, 3, 4])
// create a 4x3x4x2 array
var fourdimensional = new MultiDimensional([4, 3, 4, 2])
// etc...
You can also initialize the positions with any value:
// create a 3x4 array with all positions set to 0
var twodimensional = new MultiDimensional([3, 4], 0)
// create a 3x3x4 array with all positions set to 'Default String'
var threedimensionalAsStrings = new MultiDimensional([3, 3, 4], 'Default String')
Or more advanced:
// create a 3x3x4 array with all positions set to a unique self-aware objects.
var threedimensional = new MultiDimensional([3, 3, 4], function(position, multidimensional) {
return {
mydescription: 'I am a cell at position ' + position.join(),
myposition: position,
myparent: multidimensional
}
})
Get and set values at positions:
// get value
threedimensional.position([2, 2, 2])
// set value
threedimensional.position([2, 2, 2], 'New Value')
For iOS 8.0+ and macOS 10.10+, you can use NSString's native containsString:
.
For older versions of iOS and macOS, you can create your own (obsolete) category for NSString:
@interface NSString ( SubstringSearch )
- (BOOL)containsString:(NSString *)substring;
@end
// - - - -
@implementation NSString ( SubstringSearch )
- (BOOL)containsString:(NSString *)substring
{
NSRange range = [self rangeOfString : substring];
BOOL found = ( range.location != NSNotFound );
return found;
}
@end
Note: Observe Daniel Galasko's comment below regarding naming
You can take this trick to use only qplot. Use inner variable $mapping
. You can even add colour= to your plots so this will be putted in mapping too, and then your plots combined with legend and colors automatically.
cpu_metric2 <- qplot(y=Y2,x=X1)
cpu_metric1 <- qplot(y=Y1,
x=X1,
xlab="Time", ylab="%")
combined_cpu_plot <- cpu_metric1 +
geom_line() +
geom_point(mapping=cpu_metric2$mapping)+
geom_line(mapping=cpu_metric2$mapping)
document.onkeypress = function (e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode == 13) {
// Do something here
printResult();
}
};
Heres my two cents. I am working on an app for Windows 8 and want the button to register a click event when I press the Enter button. I am doing this in JS. I tried a couple of suggestions, but had issues. This works just fine.
In my case, where the timezones are not available on the server, this works great:
SELECT CONVERT_TZ(`date_field`,'+00:00',@@global.time_zone) FROM `table`
Note: global.time_zone uses the server timezone. You have to make sure, that it has the desired timezone!
For the conversion to get the hexadecimal values in SQL back into ASCII, here is the solution I got on this (using the function from user chaos to encode into hexadecimal)
function hexEncode($data) {
if(is_numeric($data))
return $data;
$unpacked = unpack('H*hex', $data);
return '0x' . $unpacked['hex'];
}
function hexDecode($hex) {
$str = '';
for ($i=0; $i<strlen($hex); $i += 2)
$str .= chr(hexdec(substr($hex, $i, 2)));
return $str;
}
$stringHex = hexEncode('Test String');
var_dump($stringHex);
$stringAscii = hexDecode($stringHex);
var_dump($stringAscii);
Try this test:
any(substring in string for substring in substring_list)
It will return True
if any of the substrings in substring_list
is contained in string
.
Note that there is a Python analogue of Marc Gravell's answer in the linked question:
from itertools import imap
any(imap(string.__contains__, substring_list))
In Python 3, you can use map
directly instead:
any(map(string.__contains__, substring_list))
Probably the above version using a generator expression is more clear though.
Huffman has a static cost, the Huffman table, so I disagree it's a good choice.
There are adaptative versions which do away with this, but the compression rate may suffer. Actually, the question you should ask is "what algorithm to compress text strings with these characteristics". For instance, if long repetitions are expected, simple Run-Lengh Encoding might be enough. If you can guarantee that only English words, spaces, punctiation and the occasional digits will be present, then Huffman with a pre-defined Huffman table might yield good results.
Generally, algorithms of the Lempel-Ziv family have very good compression and performance, and libraries for them abound. I'd go with that.
With the information that what's being compressed are URLs, then I'd suggest that, before compressing (with whatever algorithm is easily available), you CODIFY them. URLs follow well-defined patterns, and some parts of it are highly predictable. By making use of this knowledge, you can codify the URLs into something smaller to begin with, and ideas behind Huffman encoding can help you here.
For example, translating the URL into a bit stream, you could replace "http" with the bit 1, and anything else with the bit "0" followed by the actual procotol (or use a table to get other common protocols, like https, ftp, file). The "://" can be dropped altogether, as long as you can mark the end of the protocol. Etc. Go read about URL format, and think on how they can be codified to take less space.
This is because str.index(ch)
will return the index where ch
occurs the first time. Try:
def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
This will return a list of all indexes you need.
P.S. Hugh's answer shows a generator function (it makes a difference if the list of indexes can get large). This function can also be adjusted by changing []
to ()
.
A bit late to the party but, should you have root access, you can do the following directly:
Log into your mysql as root,
$ mysql -u root -p
Show databases;
mysql>SHOW DATABASES;
Select mysql database, which is where all privileges info is located
mysql>USE mysql;
Show tables.
mysql>SHOW TABLES;
The table concerning privileges for your case is 'db', so let's see what columns it has:
mysql>DESC db;
In order to list the users privileges, type the following command, for example:
mysql>SELECT user, host, db, Select_priv, Insert_priv, Update_priv, Delete_priv FROM db ORDER BY user, db;
If you can't find that user or if you see that that user has a 'N' in the Select_priv column, then you have to either INSERT or UPDATE accordingly:
INSERT:
INSERT INTO db (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv) VALUES ('localhost','DBname','UserName','Y' ,'N','N','N');
UPDATE:
UPDATE db SET Select_priv = 'Y' WHERE User = 'UserName' AND Db = 'DBname' AND Host='localhost';
Finally, type the following command:
mysql>FLUSH PRIVILEGES;
Ciao.
working like a charm here for bootstrap 4>4.1.1
var myGroup = $('your-list');
myGroup.on('show.bs.collapse','.collapse', function() {
myGroup.find('.collapse.show').collapse('hide');
});
If your detached HEAD is a fast forward of master and you just want the commits upstream, you can
git push origin HEAD:master
to push directly, or
git checkout master && git merge [ref of HEAD]
will merge it back into your local master.
You can still use filter, moving to an outside function the element modification (iterating just once)
def do_the_magic(x):
do_action(x)
return check(x)
# you can get a different filtered list
filter(do_the_magic,yourList)
# or have it modified in place (as suggested by Steven Rumbalski, see comment)
yourList[:] = itertools.ifilter(do_the_magic, yourList)
Hope Below steps will help
Add the dependency to your project-level build.gradle:
classpath 'com.google.gms:google-services:3.0.0'
Add the plugin to your app-level build.gradle:
apply plugin: 'com.google.gms.google-services'
app-level build.gradle:
dependencies {
compile 'com.google.android.gms:play-services-auth:9.8.0'
}
Intellij imports the project after resolving all the dependencies. In my case, it was unable to resolve dependencies for some of the modules and was stuck there. I had to copy my Maven settings.xml
from local repo to the default .m2
folder in order to point it to the correct local repo.
To install scikit-learn version 18.0, I used both commands:
conda update scikit-learn
pip install -U scikit-learn
But it does not work. There was a problem "Cannot install 'scikit-learn'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall".
Finally, i can install it by using following command:
pip install --user --upgrade scikit-learn==0.18.0
Found the script below in this github issue. Works great for me.
#!/usr/bin/env ruby
port = ARGV.first || 3000
system("sudo echo kill-server-on #{port}")
pid = `sudo lsof -iTCP -sTCP:LISTEN -n -P | grep #{port} | awk '{ print $2 }' | head -n 1`.strip
puts "PID: #{pid}"
`kill -9 #{pid}` unless pid.empty?
You can either run it in irb or inside a ruby file.
For the latter, create server_killer.rb
then run it with ruby server_killer.rb
This answer is late, but I was having the same issue. I found something that works.
In eclipse Project Explorer, right click the project name -> select "Run As" -> "Maven Build..."
In the goals, enter spring-boot:run
then click Run button.
I have the STS plug-in (i.e. SpringSource Tool Suite), so on some projects I will get a "Spring Boot App" option under Run As. But, it doesn't always show up for some reason. I use the above workaround for those.
Here is a reference that explains how to run Spring boot apps:
Spring boot tutorial
Swift only solution
Similar to Luca's anwer, I use a UIView
extension. Compared to his solution I use DispatchQueue.main.async
to make sure animations are done on the main thread, alpha
parameter for fading to a specific value and optional duration
parameters for cleaner code.
extension UIView {
func fadeTo(_ alpha: CGFloat, duration: TimeInterval = 0.3) {
DispatchQueue.main.async {
UIView.animate(withDuration: duration) {
self.alpha = alpha
}
}
}
func fadeIn(_ duration: TimeInterval = 0.3) {
fadeTo(1.0, duration: duration)
}
func fadeOut(_ duration: TimeInterval = 0.3) {
fadeTo(0.0, duration: duration)
}
}
How to use it:
// fadeIn() - always animates to alpha = 1.0
yourView.fadeIn() // uses default duration of 0.3
yourView.fadeIn(1.0) // uses custom duration (1.0 in this example)
// fadeOut() - always animates to alpha = 0.0
yourView.fadeOut() // uses default duration of 0.3
yourView.fadeOut(1.0) // uses custom duration (1.0 in this example)
// fadeTo() - used if you want a custom alpha value
yourView.fadeTo(0.5) // uses default duration of 0.3
yourView.fadeTo(0.5, duration: 1.0)
I just had the same problem/question and solved it like this (only client code):
var io = io.connect('localhost');
io.on('connect', function () {
console.log(this.socket.sessionid);
});
Updated June 2020
It is no longer possible... allegedly. If you have a Facebook or Instagram dedicated contact (because you work in either a big agency or with a big client) it may potentially be possible depending on your use case, but it's highly discouraged.
Before December 2019:
It is now "possible":
https://developers.facebook.com/docs/instagram-api/content-publishing
The Content Publishing API is a subset of Instagram Graph API endpoints that allow you to publish media objects. Publishing media objects with this API is a two step process — you first create a media object container, then publish the container on your Business Account.
Its worth noting that "The Content Publishing API is in closed beta with Facebook Marketing Partners and Instagram Partners only. We are not accepting new applicants at this time." from https://stackoverflow.com/a/49677468/445887
you can just use
ls > filenames.txt
(usually, start a shell by using "Terminal", or "shell", or "Bash".) You may need to use cd
to go to that folder first, or you can ls ~/docs > filenames.txt
Have hit the same problem today.
These are poorly documented, an open issue exist.
Some for keyup, like space:
<input (keyup.space)="doSomething()">
<input (keyup.spacebar)="doSomething()">
Some for keydown
(may work for keyup too):
<input (keydown.enter)="...">
<input (keydown.a)="...">
<input (keydown.esc)="...">
<input (keydown.alt)="...">
<input (keydown.shift.esc)="...">
<input (keydown.shift.arrowdown)="...">
<input (keydown.f4)="...">
All above are from below links:
https://github.com/angular/angular/issues/18870
https://github.com/angular/angular/issues/8273
https://github.com/angular/angular/blob/master/packages/platform-browser/src/dom/events/key_events.ts
https://alligator.io/angular/binding-keyup-keydown-events/
First, Latin-1 is the same as ISO-8859-1, so, the default was already OK for you. Right?
You successfully set the encoding to ISO-8859-1 with your command line parameter. You also set it programmatically to "Latin-1", but, that's not a recognized value of a file encoding for Java. See http://java.sun.com/javase/6/docs/technotes/guides/intl/encoding.doc.html
When you do that, looks like Charset resets to UTF-8, from looking at the source. That at least explains most of the behavior.
I don't know why OutputStreamWriter shows ISO8859_1. It delegates to closed-source sun.misc.* classes. I'm guessing it isn't quite dealing with encoding via the same mechanism, which is weird.
But of course you should always be specifying what encoding you mean in this code. I'd never rely on the platform default.
It happens that I'm just starting to learn coding and I needed something similar as you have just asked in SQLite (I´m using [SQLiteStudio] (3.1.1)).
It happens that you must define the column's 'Constraint' as 'Not Null' then entering your desired definition using 'Default' 'Constraint' or it will not work (I don't know if this is an SQLite or the program requirment).
Here is the code I used:
CREATE TABLE <MY_TABLE> (
<MY_TABLE_KEY> INTEGER UNIQUE
PRIMARY KEY,
<MY_TABLE_SERIAL> TEXT DEFAULT (<MY_VALUE>)
NOT NULL
<THE_REST_COLUMNS>
);
The main difference is that SurfaceView
can be drawn on by background theads but Views
can't.
SurfaceViews
use more resources though so you don't want to use them unless you have to.
Open the Access Database, you will see Table, Query, Report, Module & Macro.
This contains the macros which can be used to invoke common MS-Access actions in a sequence.
For custom VBA macro, press ALT+F11.
As @Danial Martine said iOS won't show a notification banner/alert. That's by design. But if really have to do it then there is one way . I have also achieve this by same.
1.Download the parse frame work from Parse FrameWork
2.Import #import <Parse/Parse.h>
3.Add following code to your didReceiveRemoteNotification Method
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
{
[PFPush handlePush:userInfo];
}
PFPush will take care how to handle the remote notification . If App is in foreground this shows the alert otherwise it shows the notification at the top.
Use the onConfigurationChanged method of Activity. See the following code:
@Override
public void onConfigurationChanged(@NotNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
You also have to edit the appropriate element in your manifest file to include the android:configChanges Just see the code below:
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
NOTE: with Android 3.2 (API level 13) or higher, the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher, you must declare android:configChanges="orientation|screenSize" for API level 13 or higher.
Hope this will help you... :)
Your routing needs to be set up along the lines of {controller}/{action}/{firstItem}
. If you left the routing as the default {controller}/{action}/{id}
in your global.asax.cs
file, then you will need to pass in id
.
routes.MapRoute(
"Inventory",
"Inventory/{action}/{firstItem}",
new { controller = "Inventory", action = "ListAll", firstItem = "" }
);
... or something close to that.
The export default {...}
construction is just a shortcut for something like this:
const funcs = {
foo() { console.log('foo') },
bar() { console.log('bar') },
baz() { foo(); bar() }
}
export default funcs
It must become obvious now that there are no foo
, bar
or baz
functions in the module's scope. But there is an object named funcs
(though in reality it has no name) that contains these functions as its properties and which will become the module's default export.
So, to fix your code, re-write it without using the shortcut and refer to foo
and bar
as properties of funcs
:
const funcs = {
foo() { console.log('foo') },
bar() { console.log('bar') },
baz() { funcs.foo(); funcs.bar() } // here is the fix
}
export default funcs
Another option is to use this
keyword to refer to funcs
object without having to declare it explicitly, as @pawel has pointed out.
Yet another option (and the one which I generally prefer) is to declare these functions in the module scope. This allows to refer to them directly:
function foo() { console.log('foo') }
function bar() { console.log('bar') }
function baz() { foo(); bar() }
export default {foo, bar, baz}
And if you want the convenience of default export and ability to import items individually, you can also export all functions individually:
// util.js
export function foo() { console.log('foo') }
export function bar() { console.log('bar') }
export function baz() { foo(); bar() }
export default {foo, bar, baz}
// a.js, using default export
import util from './util'
util.foo()
// b.js, using named exports
import {bar} from './util'
bar()
Or, as @loganfsmyth suggested, you can do without default export and just use import * as util from './util'
to get all named exports in one object.
Use this document to transfer Sticky Notes data file StickyNotes.snt to the new format
http://www.winhelponline.com/blog/recover-backup-sticky-notes-data-file-windows-10/
Restore:
%LocalAppData%\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState
Backup
just backup following file.
%LocalAppData%\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite
How to share content: https://developers.facebook.com/docs/share/
You have to choose use the deprecated function without JS, and check every day, or follow the way use JS and have fun.
For complicated objects and when performance is not significant i use a json library, like gson to serialize the object to json text, then deserialize the text to get new object.
gson which based on reflection will works in most cases, except that transient
fields will not be copied and objects with circular reference with cause StackOverflowError
.
public static <T> T copy(T anObject, Class<T> classInfo) {
Gson gson = new GsonBuilder().create();
String text = gson.toJson(anObject);
T newObject = gson.fromJson(text, classInfo);
return newObject;
}
public static void main(String[] args) {
String originalObject = "hello";
String copiedObject = copy(originalObject, String.class);
}
The Simple way is, to convert it to JSON String as below example:
Gson gson = new Gson();
String json = gson.toJson(myObj);
Then store the string in the shared preferences. Once you need it just get string from shared preferences and convert back to JSONArray or JSONObject(as per your requirement.)
Apparently you also get this error message when you forget the --all
parameter when pushing for the first time. I wrote
git push -u origin
which gave this error, it should have been
git push -u origin --all
Oh how I love these copy-paste errors ...
Assuming you have people is List of object
Map<String, String> phoneBook=people.stream()
.collect(toMap(Person::getName, Person::getAddress));
Now you need two steps :
1)
people =removeDuplicate(people);
2)
Map<String, String> phoneBook=people.stream()
.collect(toMap(Person::getName, Person::getAddress));
Here is method to remove duplicate
public static List removeDuplicate(Collection<Person> list) {
if(list ==null || list.isEmpty()){
return null;
}
Object removedDuplicateList =
list.stream()
.distinct()
.collect(Collectors.toList());
return (List) removedDuplicateList;
}
Adding full example here
package com.example.khan.vaquar;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class RemovedDuplicate {
public static void main(String[] args) {
Person vaquar = new Person(1, "Vaquar", "Khan");
Person zidan = new Person(2, "Zidan", "Khan");
Person zerina = new Person(3, "Zerina", "Khan");
// Add some random persons
Collection<Person> duplicateList = Arrays.asList(vaquar, zidan, zerina, vaquar, zidan, vaquar);
//
System.out.println("Before removed duplicate list" + duplicateList);
//
Collection<Person> nonDuplicateList = removeDuplicate(duplicateList);
//
System.out.println("");
System.out.println("After removed duplicate list" + nonDuplicateList);
;
// 1) solution Working code
Map<Object, Object> k = nonDuplicateList.stream().distinct()
.collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
System.out.println("");
System.out.println("Result 1 using method_______________________________________________");
System.out.println("k" + k);
System.out.println("_____________________________________________________________________");
// 2) solution using inline distinct()
Map<Object, Object> k1 = duplicateList.stream().distinct()
.collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
System.out.println("");
System.out.println("Result 2 using inline_______________________________________________");
System.out.println("k1" + k1);
System.out.println("_____________________________________________________________________");
//breacking code
System.out.println("");
System.out.println("Throwing exception _______________________________________________");
Map<Object, Object> k2 = duplicateList.stream()
.collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
System.out.println("");
System.out.println("k2" + k2);
System.out.println("_____________________________________________________________________");
}
public static List removeDuplicate(Collection<Person> list) {
if (list == null || list.isEmpty()) {
return null;
}
Object removedDuplicateList = list.stream().distinct().collect(Collectors.toList());
return (List) removedDuplicateList;
}
}
// Model class
class Person {
public Person(Integer id, String fname, String lname) {
super();
this.id = id;
this.fname = fname;
this.lname = lname;
}
private Integer id;
private String fname;
private String lname;
// Getters and Setters
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
@Override
public String toString() {
return "Person [id=" + id + ", fname=" + fname + ", lname=" + lname + "]";
}
}
Results :
Before removed duplicate list[Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=3, fname=Zerina, lname=Khan], Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=1, fname=Vaquar, lname=Khan]]
After removed duplicate list[Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=3, fname=Zerina, lname=Khan]]
Result 1 using method_______________________________________________
k{1=Person [id=1, fname=Vaquar, lname=Khan], 2=Person [id=2, fname=Zidan, lname=Khan], 3=Person [id=3, fname=Zerina, lname=Khan]}
_____________________________________________________________________
Result 2 using inline_______________________________________________
k1{1=Person [id=1, fname=Vaquar, lname=Khan], 2=Person [id=2, fname=Zidan, lname=Khan], 3=Person [id=3, fname=Zerina, lname=Khan]}
_____________________________________________________________________
Throwing exception _______________________________________________
Exception in thread "main" java.lang.IllegalStateException: Duplicate key Person [id=1, fname=Vaquar, lname=Khan]
at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
at java.util.HashMap.merge(HashMap.java:1253)
at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.example.khan.vaquar.RemovedDuplicate.main(RemovedDuplicate.java:48)
I know this is old, but i think i have good solution. Comparing to other answers and also comparing to accepted, mine accepts multiple values. Basically filter object with key:value search parameters (also object within object). Also it works with numbers etc, cause when comparing, it converts them to string.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'filter'})
export class Filter implements PipeTransform {
transform(array: Array<Object>, filter: Object): any {
let notAllKeysUndefined = false;
let newArray = [];
if(array.length > 0) {
for (let k in filter){
if (filter.hasOwnProperty(k)) {
if(filter[k] != undefined && filter[k] != '') {
for (let i = 0; i < array.length; i++) {
let filterRule = filter[k];
if(typeof filterRule === 'object') {
for(let fkey in filterRule) {
if (filter[k].hasOwnProperty(fkey)) {
if(filter[k][fkey] != undefined && filter[k][fkey] != '') {
if(this.shouldPushInArray(array[i][k][fkey], filter[k][fkey])) {
newArray.push(array[i]);
}
notAllKeysUndefined = true;
}
}
}
} else {
if(this.shouldPushInArray(array[i][k], filter[k])) {
newArray.push(array[i]);
}
notAllKeysUndefined = true;
}
}
}
}
}
if(notAllKeysUndefined) {
return newArray;
}
}
return array;
}
private shouldPushInArray(item, filter) {
if(typeof filter !== 'string') {
item = item.toString();
filter = filter.toString();
}
// Filter main logic
item = item.toLowerCase();
filter = filter.toLowerCase();
if(item.indexOf(filter) !== -1) {
return true;
}
return false;
}
}
Add a reference to System.Management for your project, then try something like this:
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.Management; // need to add System.Management to your project references.
class Program
{
static void Main(string[] args)
{
var usbDevices = GetUSBDevices();
foreach (var usbDevice in usbDevices)
{
Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
}
Console.Read();
}
static List<USBDeviceInfo> GetUSBDevices()
{
List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
ManagementObjectCollection collection;
using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
collection = searcher.Get();
foreach (var device in collection)
{
devices.Add(new USBDeviceInfo(
(string)device.GetPropertyValue("DeviceID"),
(string)device.GetPropertyValue("PNPDeviceID"),
(string)device.GetPropertyValue("Description")
));
}
collection.Dispose();
return devices;
}
}
class USBDeviceInfo
{
public USBDeviceInfo(string deviceID, string pnpDeviceID, string description)
{
this.DeviceID = deviceID;
this.PnpDeviceID = pnpDeviceID;
this.Description = description;
}
public string DeviceID { get; private set; }
public string PnpDeviceID { get; private set; }
public string Description { get; private set; }
}
}
If you want to convert an entire pandas series of datetimes to regular python datetimes, you can also use .to_pydatetime()
.
pd.date_range('20110101','20110102',freq='H').to_pydatetime()
> [datetime.datetime(2011, 1, 1, 0, 0) datetime.datetime(2011, 1, 1, 1, 0)
datetime.datetime(2011, 1, 1, 2, 0) datetime.datetime(2011, 1, 1, 3, 0)
....
It also supports timezones:
pd.date_range('20110101','20110102',freq='H').tz_localize('UTC').tz_convert('Australia/Sydney').to_pydatetime()
[ datetime.datetime(2011, 1, 1, 11, 0, tzinfo=<DstTzInfo 'Australia/Sydney' EST+11:00:00 DST>)
datetime.datetime(2011, 1, 1, 12, 0, tzinfo=<DstTzInfo 'Australia/Sydney' EST+11:00:00 DST>)
....
NOTE: If you are operating on a Pandas Series you cannot call to_pydatetime()
on the entire series. You will need to call .to_pydatetime()
on each individual datetime64 using a list comprehension or something similar:
datetimes = [val.to_pydatetime() for val in df.problem_datetime_column]
I just had that happen to me, I checked out an entire folder containing hours of work! Fortunately I found out that my IDE Netbeans keeps an history of each file, that allowed me to recuperate 99% of the stuff even though I needed to fix a few things manually.
To fix this, open the SQL Server Management Studio and click New Query. Then type:
USE mydatabase
exec sp_changedbowner 'sa', 'true'
Your second attempt failed primarily because you named the CTE same as the underlying table and made the CTE look as if it was a recursive CTE, because it essentially referenced itself. A recursive CTE must have a specific structure which requires the use of the UNION ALL
set operator.
Instead, you could just have given the CTE a different name as well as added the target column to it:
With SomeName As
(
SELECT
CODE_DEST,
ROW_NUMBER() OVER (ORDER BY [RS_NOM] DESC) AS RN
FROM DESTINATAIRE_TEMP
)
UPDATE SomeName SET CODE_DEST=RN
If you are just getting into Android, you would be well served by using Android Studio rather than using any version of Eclipse. Android Studio was released in 2013 and provides a nice integrated development environment for developing for Android.
Android Studio is based on IntelliJ, which is a great java devlopment environment. It also has these specific Android features:
You can download it here.
Alongside nmaier's answer, as he said you'll always receive code 1006. However, if you were to somehow theoretically receive other codes, here is code to display the results (via RFC6455).
var websocket;
if ("WebSocket" in window)
{
websocket = new WebSocket("ws://yourDomainNameHere.org/");
websocket.onopen = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was opened");
};
websocket.onclose = function (event) {
var reason;
alert(event.code);
// See http://tools.ietf.org/html/rfc6455#section-7.4.1
if (event.code == 1000)
reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
else if(event.code == 1001)
reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
else if(event.code == 1002)
reason = "An endpoint is terminating the connection due to a protocol error";
else if(event.code == 1003)
reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
else if(event.code == 1004)
reason = "Reserved. The specific meaning might be defined in the future.";
else if(event.code == 1005)
reason = "No status code was actually present.";
else if(event.code == 1006)
reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
else if(event.code == 1007)
reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
else if(event.code == 1008)
reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
else if(event.code == 1009)
reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
else if(event.code == 1011)
reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
else if(event.code == 1015)
reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
else
reason = "Unknown reason";
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
};
websocket.onmessage = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "New message arrived: " + event.data);
};
websocket.onerror = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "There was an error with your websocket.");
};
}
else
{
alert("Websocket is not supported by your browser");
return;
}
websocket.send("Yo wazzup");
websocket.close();
I have created following class
@Configuration
public class ConfigUtility {
@Autowired
private Environment env;
public String getProperty(String pPropertyKey) {
return env.getProperty(pPropertyKey);
}
}
and called as follow to get application.properties value
@Autowired
private ConfigUtility configUtil;
public AppResponse getDetails() {
AppResponse response = new AppResponse();
String email = configUtil.getProperty("emailid");
return response;
}
unit tested, working as expected...
If are using jQuery, grep may be useful:
var arr = [ a, b, c, , e, f, , g, h ];
arr = jQuery.grep(arr, function(n){ return (n); });
arr
is now [ a, b, c, d, e, f, g];
You can use the following regex to get integer and floating values from a string:
re.findall(r'[\d\.\d]+', 'hello -34 42 +34.478m 88 cricket -44.3')
['34', '42', '34.478', '88', '44.3']
Thanks Rex
It really doesn't matter.
If you feed .c to a c++ compiler it will compile as cpp, .cc/.cxx is just an alternative to .cpp used by some compilers.
.hpp is an attempt to distinguish header files where there are significant c and c++ differences. A common usage is for the .hpp to have the necessary cpp wrappers or namespace and then include the .h in order to expose a c library to both c and c++.
If your code seems too unwieldy, a function might help:
def clamp(minvalue, value, maxvalue):
return max(minvalue, min(value, maxvalue))
new_index = clamp(0, new_index, len(mylist)-1)
There are multiple ways you can do this but I am not sure which one is the best practice. The first approach is you can append an iFrame in the dialog container on the fly with your given link:
$("#dialog").append($("<iframe />").attr("src", "your link")).dialog({dialogoptions});
Another would be to load the content of your external link into the dialog container using ajax.
$("#dialog").load("yourajaxhandleraddress.htm").dialog({dialogoptions});
Both works fine but depends on the external content.
That error is normally seen when the value given to JSON.parse
is actually undefined
.
So, I would check the code that is trying to parse this - most likely you are not parsing the actual string shown here.
Try adding 2 spaces (or a backslash \
) after the first line:
[Name of link](url)
My line of text\
Visually:
[Name of link](url)<space><space>
My line of text\
Output:
<p><a href="url">Name of link</a><br>
My line of text<br></p>
Try this:
public void removeFragment(Fragment fragment){
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragment);
fragmentTransaction.commit();
}
In my experience, this error is frequently caused by a spelling error.
I got this error today.
make[1]: *** No rule to make target
maintenaceDialog.cpp', needed by
maintenaceDialog.o'. Stop.
In my case the error was simply a spelling error. The word MAINTENANCE was missing it's third N.
Also check the spelling on your filenames.
Having to go to the parent node first seems a bit odd to me, is there a reason JavaScript works like this?
The function name is removeChild()
, and how is it possible to remove the child when there's no parent? :)
On the other hand, you do not always have to call it as you have shown. element.parentNode
is only a helper to get the parent node of the given node. If you already know the parent node, you can just use it like this:
Ex:
// Removing a specified element when knowing its parent node
var d = document.getElementById("top");
var d_nested = document.getElementById("nested");
var throwawayNode = d.removeChild(d_nested);
https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild
=========================================================
To add something more:
Some answers have pointed out that instead of using parentNode.removeChild(child);
, you can use elem.remove();
. But as I have noticed, there is a difference between the two functions, and it's not mentioned in those answers.
If you use removeChild()
, it will return a reference to the removed node.
var removedChild = element.parentNode.removeChild(element);
console.log(removedChild); //will print the removed child.
But if you use elem.remove();
, it won't return you the reference.
var el = document.getElementById('Example');
var removedChild = el.remove(); //undefined
https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove
This behavior can be observed in Chrome and FF. I believe It's worth noticing :)
Hope my answer adds some value to the question and will be helpful!!
If you prefer significant digits to fixed digits then, the signif command might be useful:
> signif(1.12345, digits = 3)
[1] 1.12
> signif(12.12345, digits = 3)
[1] 12.1
> signif(12345.12345, digits = 3)
[1] 12300
The result of floating point number is not exact, which makes them unsuitable for any financial calculation which requires exact result and not approximation. float and double are designed for engineering and scientific calculation and many times doesn’t produce exact result also result of floating point calculation may vary from JVM to JVM. Look at below example of BigDecimal and double primitive which is used to represent money value, its quite clear that floating point calculation may not be exact and one should use BigDecimal for financial calculations.
// floating point calculation
final double amount1 = 2.0;
final double amount2 = 1.1;
System.out.println("difference between 2.0 and 1.1 using double is: " + (amount1 - amount2));
// Use BigDecimal for financial calculation
final BigDecimal amount3 = new BigDecimal("2.0");
final BigDecimal amount4 = new BigDecimal("1.1");
System.out.println("difference between 2.0 and 1.1 using BigDecimal is: " + (amount3.subtract(amount4)));
Output:
difference between 2.0 and 1.1 using double is: 0.8999999999999999
difference between 2.0 and 1.1 using BigDecimal is: 0.9
The typical command is:
docker container ls -f 'status=exited'
However, this will only list one of the possible non-running statuses. Here's a list of all possible statuses:
You can filter on multiple statuses by passing multiple filters on the status:
docker container ls -f 'status=exited' -f 'status=dead' -f 'status=created'
If you are integrating this with an automatic cleanup script, you can chain one command to another with some bash syntax, output just the container id's with -q
, and you can also limit to just the containers that exited successfully with an exit code filter:
docker container rm $(docker container ls -q -f 'status=exited' -f 'exited=0')
For more details on filters you can use, see Docker's documentation: https://docs.docker.com/engine/reference/commandline/ps/#filtering
Try out below code snippet:
var list = [];
var text;
function update() {
console.log(list);
for (var i = 0; i < list.length; i++) {
console.log( i );
var letters;
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(list[i]));
ul.appendChild(li);
letters += "<li>" + list[i] + "</li>";
}
document.getElementById("list").innerHTML = letters;
}
function myFunction() {
text = prompt("enter TODO");
list.push(text);
update();
}
How about:
<asp:HtmlIframe ID="yourIframe" runat="server" />
Is supported since .Net Framework 4.5
If you have Problems using this control, you might take a look here.
The problem in your initial definition of the class is that you've written:
class name(object, name):
This means that the class inherits the base class called "object", and the base class called "name". However, there is no base class called "name", so it fails. Instead, all you need to do is have the variable in the special init method, which will mean that the class takes it as a variable.
class name(object):
def __init__(self, name):
print name
If you wanted to use the variable in other methods that you define within the class, you can assign name to self.name, and use that in any other method in the class without needing to pass it to the method.
For example:
class name(object):
def __init__(self, name):
self.name = name
def PrintName(self):
print self.name
a = name('bob')
a.PrintName()
bob
INSERT INTO hr.employees (location_id) VALUE (1000) WHERE first_name LIKE '%D%';
let me know if there is any problem in this statement.
Use the following script after appending your select.
$('#state').select2();
Don't use destroy
.
You should check for Dictionary.ContainsKey(int key) before trying to pull out the value.
Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(2,4);
myDictionary.Add(3,5);
int keyToFind = 7;
if(myDictionary.ContainsKey(keyToFind))
{
myValueLookup = myDictionay[keyToFind];
// do work...
}
else
{
// the key doesn't exist.
}
protected void Page_Load(object sender, EventArgs e)
{
// prevent user from making operation twice
btnSave.Attributes.Add("onclick",
"this.disabled=true;" + GetPostBackEventReference(btnSave).ToString() + ";");
// ... etc.
}
Use a AJAX function which will call a php page synchronously and then in that page you can put the php usleep() function which will act as a delay.
function delay(t){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","http://www.hklabs.org/files/delay.php?time="+t,false);
//This will call the page named delay.php and the response will be sent to a division with ID as "response"
xmlhttp.send();
document.getElementById("response").innerHTML=xmlhttp.responseText;
}
Make a normal breakpoint on the doIt(tablist[i]);
line
Right-click -> Properties
Check 'Conditional'
Enter tablist[i].equalsIgnoreCase("LEADDELEGATES")
I have been trying to implement Jaap's answer inside this page of my recent site, with one difference : the .main {height:} was set to auto instead of a fixed px value. As responsive developer i am looking for a solution to synchronize the image height with the left floating text element, yet only in case my text height becomes greater then my actual image height. In that case the image should not be rescaled, but cropped and centered as decribed in the original question here above. Can this be done ? You can simulate the behaviour by slowly downsizing the browser's width.
Easier way for me is to switch to R1C1
notation and just use R[-1]C1
and switch back when done.
$(document).ready(function() {
$("#check1").click(function() {
var checked = $(this).is(':checked');
if (checked) {
alert('checked');
} else {
alert('unchecked');
}
});
});
This simple way to do your task:
setContentView(R.id.main);
ImageView iv = (ImageView) findViewById(R.id.left);
int width = 60;
int height = 60;
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
iv.setLayoutParams(parms);
and another way if you want to give screen size in height and width then use below code :
setContentView(R.id.main);
Display display = getWindowManager().getDefaultDisplay();
ImageView iv = (LinearLayout) findViewById(R.id.left);
int width = display.getWidth(); // ((display.getWidth()*20)/100)
int height = display.getHeight();// ((display.getHeight()*30)/100)
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
iv.setLayoutParams(parms);
hope use full to you.
using a variable
$array_IN=Dev_Table::where('id',1)->select('tabl2_id')->get();
$sel_table2=Dev_Table2::WhereIn('id',$array_IN)->get();
Another way to do simultaneous animations if you want to call them separately (eg. from different code) is to use queue
. Again, as with Tinister's answer you would have to use animate for this and not fadeIn:
$('.tooltip').css('opacity', 0);
$('.tooltip').show();
...
$('.tooltip').animate({opacity: 1}, {queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');
To me it is about 2 different meanings of symbol =
:
x = sin(t)
means, that x
is different name for sin(t)
. So writing x + y
is the same thing as sin(t) + y
. Functional reactive programming is like math in this respect: if you write x + y
, it is computed with whatever the value of t
is at the time it's used.x = sin(t)
is an assignment: it means that x
stores the value of sin(t)
taken at the time of the assignment.First of all, your code works and that's a valid way of creating a function in JavaScript (jQuery aside), but because you are declaring a function inside another function (an anonymous one in this case) "MyBlah" will not be accessible from the global scope.
Here's an example:
$(document).ready( function () {
var MyBlah = function($blah) { alert($blah); };
MyBlah("Hello this works") // Inside the anonymous function we are cool.
});
MyBlah("Oops") //This throws a JavaScript error (MyBlah is not a function)
This is (sometimes) a desirable behavior since we do not pollute the global namespace, so if your function does not need to be called from other part of your code, this is the way to go.
Declaring it outside the anonymous function places it in the global namespace, and it's accessible from everywhere.
Lastly, the $ at the beginning of the variable name is not needed, and sometimes used as a jQuery convention when the variable is an instance of the jQuery object itself (not necessarily in this case).
Maybe what you need is creating a jQuery plugin, this is very very easy and useful as well since it will allow you to do something like this:
$('div#message').myBlah("hello")
See also: http://www.re-cycledair.com/creating-jquery-plugins
You can Try using :- git ls-files -s
Based on @returntrue answer I managed to implement it in Interface Builder.
To get round corners button using Interface Builder add a Key Path = "layer.cornerRadius"
with Type = "Number"
and Value = "10"
(or other value as required) in the "User Defined RunTime Attribute
" of the Identity Inspector
of the button.
This is the simplest solution to limit the number of digits after decimal point to two:
myeditText2 = (EditText) findViewById(R.id.editText2);
myeditText2.setInputType(3);
Yes, you can add as many SQL statements into a single script as you wish. Just one thing to note: the order matters. You can't INSERT into a table until you CREATE it; you can't set a foreign key until the primary key is inserted.
I use the following (stripped-down code) in Firefox 69.0 (on Ubuntu) to read a directory and show the image as part of a digital photo frame. The page is made in HTML, CSS, and JavaScript, and it is located on the same machine where I run the browser. The images are located on the same machine as well, so there is no viewing from "outside".
var directory = <path>;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', directory, false); // false for synchronous request
xmlHttp.send(null);
var ret = xmlHttp.responseText;
var fileList = ret.split('\n');
for (i = 0; i < fileList.length; i++) {
var fileinfo = fileList[i].split(' ');
if (fileinfo[0] == '201:') {
document.write(fileinfo[1] + "<br>");
document.write('<img src=\"' + directory + fileinfo[1] + '\"/>');
}
}
This requires the policy security.fileuri.strict_origin_policy
to be disabled. This means it might not be a solution you want to use. In my case I deemed it ok.
Alternatively, you could try the following,
resp.setStatus(301);
resp.setHeader("Location", "index.jsp");
resp.setHeader("Connection", "close");
Try to simply use break statement.
Also you can use the following code as an example:
a = [[0,1,0], [1,0,0], [1,1,1]]
b = [[0,0,0], [0,0,0], [0,0,0]]
def check_matr(matr, expVal):
for row in matr:
if len(set(row)) > 1 or set(row).pop() != expVal:
print 'Wrong'
break# or return
else:
print 'ok'
else:
print 'empty'
check_matr(a, 0)
check_matr(b, 0)
I think thats correct. RTSP may use RTP internally.
@mikejonesguy answer is perfect, just in case you plan to test room migrations (recommended), add the schema location to the source sets.
In your build.gradle file you specify a folder to place these generated schema JSON files. As you update your schema, you’ll end up with several JSON files, one for every version. Make sure you commit every generated file to source control. The next time you increase your version number again, Room will be able to use the JSON file for testing.
- Florina Muntenescu (source)
build.gradle
android {
// [...]
defaultConfig {
// [...]
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
}
}
}
// add the schema location to the source sets
// used by Room, to test migrations
sourceSets {
androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
}
// [...]
}
If you have several threads executing the methods m1 and m2 in the code below:
class SomeClass {
private int i = 0;
public void m1() { i = 5; }
public int m2() { return i; }
}
you have the guarantee that any thread calling m2
will either read 0 or 5.
On the other hand, with this code (where i
is a long):
class SomeClass {
private long i = 0;
public void m1() { i = 1234567890L; }
public long m2() { return i; }
}
a thread calling m2
could read 0, 1234567890L, or some other random value because the statement i = 1234567890L
is not guaranteed to be atomic for a long
(a JVM could write the first 32 bits and the last 32 bits in two operations and a thread might observe i
in between).
There are two ways of looking at github content, the "raw" way and the "Web page" way.
raw.githubusercontent.com
returns the raw content of files stored in github, so they can be downloaded simply to your computer. For example, if the page represents a ruby install script, then you will get a ruby install script that your ruby installation will understand.
If you instead download the file using the github.com link, you will actually be downloading a web page with buttons and comments and which displays your wanted script in the middle -- it's what you want to give to your web browser to get a nice page to look at, but for the computer, it is not a script that can be executed or code that can be compiled, but a web page to be displayed. That web page has a button called Raw that sends you to the corresponding content on raw.githubusercontent.com
.
To see the content of raw.githubusercontent.com/${repo}/${branch}/${path}
in the usual github interface:
raw.githubusercontent.com
with plain github.com
In this case, the branch name is "master" (which is a very common branch name), so you replace /master/
with /blob/master/
, and so
https://raw.githubusercontent.com/Homebrew/install/master/install
becomes
https://github.com/Homebrew/install/blob/master/install
This is the reverse of finding a file on Github and clicking the Raw link.
If you pass non-parametrized params for RestTemplate, you'll have one Metrics for everyone single different URL that you pass, considering the parameters. You would like to use parametrized urls:
http://my-url/action?param1={param1}¶m2={param2}
instead of
http://my-url/action?param1=XXXX¶m2=YYYY
The second case is what you get by using UriComponentsBuilder class.
One way to implement the first behavior is the following:
Map<String, Object> params = new HashMap<>();
params.put("param1", "XXXX");
params.put("param2", "YYYY");
String url = "http://my-url/action?%s";
String parametrizedArgs = params.keySet().stream().map(k ->
String.format("%s={%s}", k, k)
).collect(Collectors.joining("&"));
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
HttpEntity<String> entity = new HttpEntity<>(headers);
restTemplate.exchange(String.format(url, parametrizedArgs), HttpMethod.GET, entity, String.class, params);
jupyter nbconvert yourNotebook.ipynb --no-input --no-prompt
jupyter nbconvert yourNotebook.ipynb
This part of the code will take the latex file format of the jupyter notebook and converts it to a html
--no-input
This is like a parameter we are saying during conversion that dont add any inputs : here the input to a cell is the code.. so we hide it
--no-prompt
Here also we are saying, During conversion dont show any prompts form the code like errors or warnings in the final HTML file ) so that that html will have only the Text and the code output in the form of a report !!..
Hope it helps :)
I'm not working on IIS, but I do have an application that throws the same error on a 2K8 box. It works just fine on a 2K3 box, go figure.
My resolution was to "Run as administrator" to give the application elevated rights and everything works happily. I hope this helps lead you in the right direction.
Windows 2008 is rights/permissions/elevation is really different from Windows 2003, gar.
If you want to print/write double value at console then use System.out.printf()
or System.out.format()
methods.
System.out.printf("\n$%10.2f",shippingCost);
System.out.printf("%n$%.2f",shippingCost);
Using subprocess.run
import subprocess
ps = subprocess.run(['ps', '-A'], check=True, capture_output=True)
processNames = subprocess.run(['grep', 'process_name'],
input=ps.stdout, capture_output=True)
print(processNames.stdout)
You can also do (Get-Service -Name "what ever" - ComputerName RemoteHost).Status = "Stopped"
It may be little late but here are my two cents.
If you are using Java 8 then you can make use of computeIfPresent method. If the value for the specified key is present and non-null then it attempts to compute a new mapping given the key and its current mapped value.
final Map<String,Integer> map1 = new HashMap<>();
map1.put("A",0);
map1.put("B",0);
map1.computeIfPresent("B",(k,v)->v+1); //[A=0, B=1]
We can also make use of another method putIfAbsent to put a key. If the specified key is not already associated with a value (or is mapped to null) then this method associates it with the given value and returns null, else returns the current value.
In case the map is shared across threads then we can make use of ConcurrentHashMap
and AtomicInteger. From the doc:
An
AtomicInteger
is an int value that may be updated atomically. An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer. However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.
We can use them as shown:
final Map<String,AtomicInteger> map2 = new ConcurrentHashMap<>();
map2.putIfAbsent("A",new AtomicInteger(0));
map2.putIfAbsent("B",new AtomicInteger(0)); //[A=0, B=0]
map2.get("B").incrementAndGet(); //[A=0, B=1]
One point to observe is we are invoking get
to get the value for key B
and then invoking incrementAndGet()
on its value which is of course AtomicInteger
. We can optimize it as the method putIfAbsent
returns the value for the key if already present:
map2.putIfAbsent("B",new AtomicInteger(0)).incrementAndGet();//[A=0, B=2]
On a side note if we plan to use AtomicLong then as per documentation under high contention expected throughput of LongAdder is significantly higher, at the expense of higher space consumption. Also check this question.
Yes, use source or the short form which is just .
:
. other_script.sh
After you fetch the first 50 rows in the query windows, simply click on any column to get focus on the query window, then once selected do ctrl + end key
This will load the full result set (all rows)
In C++, struct
s do not have a comparison operator generated by default. You need to write your own:
bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
return /* your comparison code goes here */
}
according to this book:
MySQL lets you specify a “width” for integer types, such as INT(11). This is meaningless for most applications: it does not restrict the legal range of values, but simply specifies the number of characters MySQL’s interactive tools will reserve for display purposes. For storage and computational purposes, INT(1) is identical to INT(20).
just run DBCC useroptions
and you'll get something like this:
Set Option Value
--------------------------- --------------
textsize 2147483647
language us_english
dateformat mdy
datefirst 7
lock_timeout -1
quoted_identifier SET
arithabort SET
ansi_null_dflt_on SET
ansi_warnings SET
ansi_padding SET
ansi_nulls SET
concat_null_yields_null SET
isolation level read committed
First add your item to mItems
and then use:
mAdapter.notifyItemInserted(mItems.size() - 1);
this method is better than using:
mAdapter.notifyDataSetChanged();
in performance.
Just use Double.compare() method to compare double values.
Double.compare((d1,d2) == 0)
double d1 = 0.0;
double d2 = 0.0;
System.out.println(Double.compare((d1,d2) == 0)) // true
There is now a new way of addressing this issue - if you remove position: relative from the container which needs to have the overflow-y visible, you can have overflow-y visible and overflow-x hidden, and vice versa (have overflow-x visible and overflow-y hidden, just make sure the container with the visible property is not relatively positioned).
See this post from CSS Tricks for more details - it worked for me: https://css-tricks.com/popping-hidden-overflow/
Mac OS X uses large amounts of C++ inside some libraries, but it isn't exposed as they're afraid of the ABI breaking.
The SQL standard way of doing this would be:
SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1
Example:
INSERT INTO table1 VALUES ('hello', null, 'world');
SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1;
helloworld
On ASP.net web forms use in the @page AspCompat="true", add the system.windows.forms to you project. At your web.config add:
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
</appSettings>
Then you can use:
Clipboard.SetText(CreateDescription());
Trust me, this will work for you:
npm config set registry http://registry.npmjs.org/
//Add a list of BBDD
var item = myEntities.getList().ToList();
//Insert a new object of type in a position of the list
item.Insert(0,(new Model.getList_Result { id = 0, name = "Coca Cola" }));
//List assigned to DataGridView
dgList.DataSource = item;
string currentdatetime = DateTime.Now.ToString("dd'/'MM'/'yyyy");
You would define a constructor in an abstract class if you are in one of these situations:
Note that:
In any case, don't forget that if you don't define a constructor, then the compiler will automatically generate one for you (this one is public, has no argument, and does nothing).
Easiest way is to go to the server URL after starting the server(localhost:8080) then login as admin,Go to settings>Exclusions> Source File Exclusions- Add your packages here. Restart the server.
If you're on Android you can TextUtils.join(delimiter, tokens)
In my experience all the files which i have downloaded from internet,gmail
are stored in
/sdcard/download
on ics
/sdcard/Download
You can access it using
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
% Assuming that the dataset is ";"-delimited and each line ends with ";"
fid = fopen('sampledata.csv');
tline = fgetl(fid);
u=sprintf('%c',tline); c=length(u);
id=findstr(u,';'); n=length(id);
data=cell(1,n);
for I=1:n
if I==1
data{1,I}=u(1:id(I)-1);
else
data{1,I}=u(id(I-1)+1:id(I)-1);
end
end
ct=1;
while ischar(tline)
ct=ct+1;
tline = fgetl(fid);
u=sprintf('%c',tline);
id=findstr(u,';');
if~isempty(id)
for I=1:n
if I==1
data{ct,I}=u(1:id(I)-1);
else
data{ct,I}=u(id(I-1)+1:id(I)-1);
end
end
end
end
fclose(fid);
The Pumping lemma for regular languages is the reason why you can't do that.
The generated automaton will have a finite number of states, say k, so a string of k+1 opening braces is bound to have a state repeated somewhere (as the automaton processes the characters). The part of the string between the same state can be duplicated infinitely many times and the automaton will not know the difference.
In particular, if it accepts k+1 opening braces followed by k+1 closing braces (which it should) it will also accept the pumped number of opening braces followed by unchanged k+1 closing brases (which it shouldn't).
As of Json.NET 4.0 Release 1, there is native dynamic support.
You don't need to declare a class, just use dynamic
:
dynamic jsonDe = JsonConvert.DeserializeObject(json);
All the fields will be available:
foreach (string typeStr in jsonDe.Type[0])
{
// Do something with typeStr
}
string t = jsonDe.t;
bool a = jsonDe.a;
object[] data = jsonDe.data;
string[][] type = jsonDe.Type;
With dynamic you don't need to create a specific class to hold your data.
The answers are correct but don't mention how to sync code between the public repo and the fork.
Here is the full workflow (we've done this before open sourcing React Native):
First, duplicate the repo as others said (details here):
Create a new repo (let's call it private-repo
) via the Github UI. Then:
git clone --bare https://github.com/exampleuser/public-repo.git
cd public-repo.git
git push --mirror https://github.com/yourname/private-repo.git
cd ..
rm -rf public-repo.git
Clone the private repo so you can work on it:
git clone https://github.com/yourname/private-repo.git
cd private-repo
make some changes
git commit
git push origin master
To pull new hotness from the public repo:
cd private-repo
git remote add public https://github.com/exampleuser/public-repo.git
git pull public master # Creates a merge commit
git push origin master
Awesome, your private repo now has the latest code from the public repo plus your changes.
Finally, to create a pull request private repo -> public repo:
Use the GitHub UI to create a fork of the public repo (the small "Fork" button at the top right of the public repo page). Then:
git clone https://github.com/yourname/the-fork.git
cd the-fork
git remote add private_repo_yourname https://github.com/yourname/private-repo.git
git checkout -b pull_request_yourname
git pull private_repo_yourname master
git push origin pull_request_yourname
Now you can create a pull request via the Github UI for public-repo, as described here.
Once project owners review your pull request, they can merge it.
Of course the whole process can be repeated (just leave out the steps where you add remotes).
Use codecs if possible,
with codecs.open('file_path', 'a+', 'utf-8') as fp:
fp.write(json.dumps(res, ensure_ascii=False))
user1269737's answer is the proper (Google/Android approved) way to do this. Go read their answer and give them a +1.
I'll leave my original answer here for posterity's sake. This was the best available back in 2012, but now Android has proper support for this.
The key is using ActivityLifecycleCallbacks
(note that this requires Android API level 14 (Android 4.0)). Just check if the number of stopped activities is equal to the number of started activities. If they're equal, your application is being backgrounded. If there are more started activities, your application is still visible. If there are more resumed than paused activities, your application is not only visible, but it's also in the foreground. There are 3 main states that your activity can be in, then: visible and in the foreground, visible but not in the foreground, and not visible and not in the foreground (i.e. in the background).
The really nice thing about this method is that it doesn't have the asynchronous issues getRunningTasks()
does, but you also don't have to modify every Activity
in your application to set/unset something in onResumed()
/onPaused()
. It's just a few lines of code that's self contained, and it works throughout your whole application. Plus, there are no funky permissions required either.
MyLifecycleHandler.java:
public class MyLifecycleHandler implements ActivityLifecycleCallbacks {
// I use four separate variables here. You can, of course, just use two and
// increment/decrement them instead of using four and incrementing them all.
private int resumed;
private int paused;
private int started;
private int stopped;
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
++resumed;
}
@Override
public void onActivityPaused(Activity activity) {
++paused;
android.util.Log.w("test", "application is in foreground: " + (resumed > paused));
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityStarted(Activity activity) {
++started;
}
@Override
public void onActivityStopped(Activity activity) {
++stopped;
android.util.Log.w("test", "application is visible: " + (started > stopped));
}
// If you want a static function you can use to check if your application is
// foreground/background, you can use the following:
/*
// Replace the four variables above with these four
private static int resumed;
private static int paused;
private static int started;
private static int stopped;
// And these two public static functions
public static boolean isApplicationVisible() {
return started > stopped;
}
public static boolean isApplicationInForeground() {
return resumed > paused;
}
*/
}
MyApplication.java:
// Don't forget to add it to your manifest by doing
// <application android:name="your.package.MyApplication" ...
public class MyApplication extends Application {
@Override
public void onCreate() {
// Simply add the handler, and that's it! No need to add any code
// to every activity. Everything is contained in MyLifecycleHandler
// with just a few lines of code. Now *that's* nice.
registerActivityLifecycleCallbacks(new MyLifecycleHandler());
}
}
@Mewzer has asked some good questions about this method that I'd like to respond to in this answer for everyone:
onStop()
is not called in low memory situations; is that a problem here?
No. The docs for onStop()
say:
Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.
The key here is "keep your activity's process running..." If this low memory situation is ever reached, your process is actually killed (not just your activity). This means that this method of checking for backgrounded-ness is still valid because a) you can't check for backgrounding anyway if your process is killed, and b) if your process starts again (because a new activity is created), the member variables (whether static or not) for MyLifecycleHandler
will be reset to 0
.
Does this work for configuration changes?
By default, no. You have to explicitly set configChanges=orientation|screensize
(|
with anything else you want) in your manifest file and handle the configuration changes, or else your activity will be destroyed and recreated. If you do not set this, your activity's methods will be called in this order: onCreate -> onStart -> onResume -> (now rotate) -> onPause -> onStop -> onDestroy -> onCreate -> onStart -> onResume
. As you can see, there is no overlap (normally, two activities overlap very briefly when switching between the two, which is how this backgrounding-detection method works). In order to get around this, you must set configChanges
so that your activity is not destroyed. Fortunately, I've had to set configChanges
already in all of my projects because it was undesirable for my entire activity to get destroyed on screen rotate/resize, so I've never found this to be problematic. (thanks to dpimka for refreshing my memory on this and correcting me!)
One note:
When I've said "background" here in this answer, I've meant "your app is no longer visible." Android activities can be visible yet not in the foreground (for example, if there's a transparent notification overlay). That's why I've updated this answer to reflect that.
It's important to know that Android has a weird limbo moment when switching activities where nothing is in the foreground. For this reason, if you check if your application is in the foreground when switching between activities (in the same app), you'll be told you're not in the foreground (even though your app is still the active app and is visible).
You can check if your app is in the foreground in your Activity
's onPause()
method after super.onPause()
. Just remember the weird limbo state I just talked about.
You can check if your app is visible (i.e. if it's not in the background) in your Activity
's onStop()
method after super.onStop()
.
simply used the +
operator. Javascript concats strings with +
If protocol HTTP is given as State full protocol,browser window uses single connection to communicate with web server for multiple request given to web application.this gives chance to browser window to engage the connections between browser window and web servers for long time and to keep them in idle state for long time.This may create the situation of reaching to maximum connections of web server even though most of the connections in clients are idle.
I spent quite a while wrestling with this problem and then I realized I was making a simple mistake in the fact that I had forgotten which particular database I was targeting my connection to. I was using the standard SQL Server connection window to enter the credentials:
I had to check the Connection Properties tab to verify that I was choosing the correct database to connect to. I had accidentally left the Connect to database option here set to a selection from a previous session. This is why I was unable to connect to the database I thought I was trying to connect to.
Note that you need to click the Options >>
button in order for the Connection Properties and other tabs to show up.
I’m running a 5th gen i7 with Windows 10 and a 1TB Solid State. I compressed the Android Studio Projects folder and got about an 80% boost. Hope this helps.
I then combined it with the above solutions ie (org.gradle.parallel=true, org.gradle.daemon=true). The performance boost was quite impressive.
Additionally:
All of the above answers are totally correct but I must state as an experience Android developer (of 4 and a half years) that: No Android/Gradle developer should be working on a machine with a spinner drive, you need to fork out for a Solid State. We all hit that play button in the IDE 100s of times per day. When I went from a spinner to SSD (post Gradle), my speed and efficiency was literally 2 – 4 times faster and I promise you I’m NOT exaggerating here.
Now I’m not talking about having a machine with a small SSD and a big spinner, I’m talking about 1 big SSD. If you already have a machine with a small SSD and a big spinner you can upgrade the small spinner to say a 500GB SSD and set the SSD as your main OS drive with your developer tools installed on it.
So if you’re working in a fast paced environment please show this post to your boss. A decent 1TB SSD will set you back about £300 (including VAT), or about £160 for a 500GB SSD. Depending on if you are a junior or senior Android developer the drive will pay for itself (in wages expenses) in 1 – 2 working weeks, or about 2 and a half to 5 working days if you invest in a smaller; say 500GB SSD.
A lot of developers may argue that this is not the case, but it is the case for Gradle, as the Gradle system is very hard on the direct disk access. If you work with .NET/C#/VB Net or other development tools you won’t notice much difference but the difference in Gradle is HUGE. If you act on this post I promise you, you won’t be disappointed. Personally I’m using fifth gen i7 with 8GB RAM which originally came with a 1TB Spinner and I upgraded it to a Samsung SSD 840 EVO 1TB and I’ve never looked back since. I bought mine from: https://www.aria.co.uk.
Hope this helps. Also I must state that this is NOT a commercially motivated post, I’m just recommending Aria as I’ve used them many times before and they’ve always been reliable.
You can do it by not initializing url and writing it at hardcode like this
//var url = '@Url.Action("ActionName", "Controller");
$.post("/Controller/ActionName?para1=" + data + "¶2=" + data2, function (result) {
$("#" + data).html(result);
............. Your code
});
While your controller side code must be like this below:
public ActionResult ActionName(string para1, string para2)
{
Your Code .......
}
this was simple way. now we can do pass multiple data by json also like this:
var val1= $('#btn1').val();
var val2= $('#btn2').val();
$.ajax({
type: "GET",
url: '@Url.Action("Actionre", "Contr")',
contentType: "application/json; charset=utf-8",
data: { 'para1': val1, 'para2': val2 },
dataType: "json",
success: function (cities) {
ur code.....
}
});
While your controller side code will be same:
public ActionResult ActionName(string para1, string para2)
{
Your Code .......
}
Could you try this one:
create or replace
procedure point_triangle
IS
BEGIN
FOR thisteam in (select P.FIRSTNAME,P.LASTNAME, SUM(P.PTS) S from PLAYERREGULARSEASON P where P.TEAM = 'IND' group by P.FIRSTNAME, P.LASTNAME order by SUM(P.PTS) DESC)
LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.S);
END LOOP;
END;
git config --global fetch.prune true
To always --prune
for git fetch
and git pull
in all your Git repositories:
git config --global fetch.prune true
This above command appends in your global Git configuration (typically ~/.gitconfig
) the following lines. Use git config -e --global
to view your global configuration.
[fetch]
prune = true
git config remote.origin.prune true
To always --prune
but from one single repository:
git config remote.origin.prune true
#^^^^^^
#replace with your repo name
This above command adds in your local Git configuration (typically .git/config
) the below last line. Use git config -e
to view your local configuration.
[remote "origin"]
url = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
fetch = +refs/heads/*:refs/remotes/origin/*
prune = true
You can also use --global
within the second command or use instead --local
within the first command.
git config --global gui.pruneDuringFetch true
If you use git gui
you may also be interested by:
git config --global gui.pruneDuringFetch true
that appends:
[gui]
pruneDuringFetch = true
The corresponding documentations from git help config
:
--global
For writing options: write to global
~/.gitconfig
file rather than the repository.git/config
, write to$XDG_CONFIG_HOME/git/config
file if this file exists and the~/.gitconfig
file doesn’t.
--local
For writing options: write to the repository
.git/config
file. This is the default behavior.
fetch.prune
If true, fetch will automatically behave as if the
--prune
option was given on the command line. See alsoremote.<name>.prune
.
gui.pruneDuringFetch
"true" if git-gui should prune remote-tracking branches when performing a fetch. The default value is "false".
remote.<name>.prune
When set to true, fetching from this remote by default will also remove any remote-tracking references that no longer exist on the remote (as if the
--prune
option was given on the command line). Overridesfetch.prune
settings, if any.
I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.
// ---------------------------- START DownloadFileAsync // -----------------------//
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// DIALOG_DOWNLOAD_PROGRESS is defined as 0 at start of class
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... urls) {
try {
String xmlUrl = urls[0];
URL u = new URL(xmlUrl);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lengthOfFile = c.getContentLength();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; // total = total + len1
publishProgress("" + (int) ((total * 100) / lengthOfFile));
xmlContent += buffer;
}
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Retrieving latest announcements...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
Try the following:
<script>
//Functions to open database and to create, insert data into tables
getSelectedRow = function(val)
{
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM Employ where number = ?;',[parseInt(val)], selectedRowValues, errorHandler);
});
};
selectedRowValues = function(transaction,results)
{
for(var i = 0; i < results.rows.length; i++)
{
var row = results.rows.item(i);
alert(row['number']);
alert(row['name']);
}
};
</script>
You don't have access to javascript variable names in SQL, you must pass the values to the Database.
I had the same problem and what ended up being the issue was the RAM size: apparently 1024 (or whatever size) is different from 1024MB. Make sure you specify the units and it should work for you.
I came here looking for an answer and ended up finding it myself, thanks to the previous responses.
In my particular case, while editing PHP code on Eclipse Juno, I have found that the previous commands won't work for me. Instead of them, I should press Ctrl+ 7 (on the superior number key) to obtain the double bar comment ("//"). There's no way I can comment them with the previous mentioned key combinations.
In Java (I assume C# is more or less identical):
list = new ArrayList<T>(new HashSet<T>(list))
If you really wanted to mutate the original list:
List<T> noDupes = new ArrayList<T>(new HashSet<T>(list));
list.clear();
list.addAll(noDupes);
To preserve order, simply replace HashSet with LinkedHashSet.
How To Fix The Broken Icon Links (blank.gif, text.gif, etc.)
Unfortunately as previously mentioned, simply adding a virtual host to your project doesn't fix the broken icon links.
The Problem:
WAMP/Apache does not change the directory reference for the icons to your respective installation directory. It is statically set to "c:/Apache24/icons" and 99.9% of users Apache installation does not reside here. Especially with WAMP.
The Fix:
Find your Apache icons directory! Typically it will be located here: "c:/wamp/bin/apache/apache2.4.9/icons". However your mileage may vary depending on your installation and if your Apache version is different, then your path will be different as well.\
Open up httpd-autoindex.conf in your favorite editor. This file can usually be found here: "C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-autoindex.conf". Again, if your Apache version is different, then so will this path.
Find this definition (usually located near the top of the file):
Alias /icons/ "c:/Apache24/icons/"
<Directory "c:/Apache24/icons">
Options Indexes MultiViews
AllowOverride None
Require all granted
</Directory>
Replace the "c:/Apache24/icons/" directories with your own. IMPORTANT You MUST have a trailing forward slash in the first directory reference. The second directory reference must have no trailing slash. Your results should look similar to this. Again, your directory may differ:
Alias /icons/ "c:/wamp/bin/apache/apache2.4.9/icons/"
<Directory "c:/wamp/bin/apache/apache2.4.9/icons">
Options Indexes MultiViews
AllowOverride None
Require all granted
</Directory>
Restart your Apache server and enjoy your cool icons!
System.exit(system call)
terminates the currently running Java virtual machine by initiating its shutdown sequence. The argument serves as a status code.
By convention, a nonzero status code indicates abnormal termination.
System.exit(0) or EXIT_SUCCESS; ---> Success
System.exit(1) or EXIT_FAILURE; ---> Exception
System.exit(-1) or EXIT_ERROR; ---> Error
Read More at Java
On Unix and Linux systems, 0
for successful executions and 1
or higher for failed executions.
class1 item = lst[index];
item.foo = bar;
Probably the new PyCharm from the makers of IntelliJ and ReSharper.
This worked for me, as documented on this page:
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
StringWriter sw = new StringWriter();
trans.transform(new DOMSource(document), new StreamResult(sw));
return sw.toString();
Not the most elegant solution, and only works 90% of the time:
def vardict(*args):
ns = inspect.stack()[1][0].f_locals
retval = {}
for a in args:
found = False
for k, v in ns.items():
if a is v:
retval[k] = v
if found:
raise ValueError("Value found in more than one local variable: " + str(a))
found = True
if found:
continue
if 'self' in ns:
for k, v in ns['self'].__dict__.items():
if a is v:
retval[k] = v
if found:
raise ValueError("Value found in more than one instance attribute: " + str(a))
found = True
if found:
continue
for k, v in globals().items():
if a is v:
retval[k] = v
if found:
raise ValueError("Value found in more than one global variable: " + str(a))
found = True
assert found, "Couldn't find one of the parameters."
return retval
You'll run into problems if you store the same reference in multiple variables, but also if multiple variables store the same small int, since these get interned.
You might try reducing your base memory under settings to around 3175MB and reduce your cores to 1. That should work given that your BIOS is set for virtualization. Use the f12 key, security, virtualization to make sure that it is enabled. If it doesn't say VT-x that is ok, it should say VT-d or the like.
Just use following:
FOR JAVA USERS
In case you are using activity --> AlertDialog.Builder builder = new AlertDialog.Builder(this);
OR
AlertDialog.Builder builder = new AlertDialog.Builder(your_activity.this);
In case you are using fragment --> AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
FOR KOTLIN USERS
In case you are using activity --> val builder = AlertDialog.Builder(this)
OR
val builder = AlertDialog.Builder(this@your_activity.this)
In case you are using fragment --> val builder = AlertDialog.Builder(activity!!)
//Simple exercise to demonstrate, assuming the view controller has a //Textfield, Button and a Label. And that the label should display the //userinputs when button clicked. And if you want the keyboard to disappear //when clicken anywhere on the screen + upon clicking Return key in the //keyboard. Dont forget to add "UITextFieldDelegate" and
//"self.userInput.delegate = self" as below
import UIKit
class ViewController: UIViewController,UITextFieldDelegate {
@IBOutlet weak var userInput: UITextField!
@IBAction func transferBtn(sender: AnyObject) {
display.text = userInput.text
}
@IBOutlet weak var display: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//This is important for the textFieldShouldReturn function, conforming to textfieldDelegate and setting it to self
self.userInput.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//This is for the keyboard to GO AWAYY !! when user clicks anywhere on the view
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
//This is for the keyboard to GO AWAYY !! when user clicks "Return" key on the keyboard
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
You can replace the special characters with the desired characters as follows,
import string
specialCharacterText = "H#y #@w @re &*)?"
inCharSet = "!@#$%^&*()[]{};:,./<>?\|`~-=_+\""
outCharSet = " " #corresponding characters in inCharSet to be replaced
splCharReplaceList = string.maketrans(inCharSet, outCharSet)
splCharFreeString = specialCharacterText.translate(splCharReplaceList)
This should work...
JavaScriptSerializer ser = new JavaScriptSerializer();
var records = new ser.Deserialize<List<Record>>(jsonData);
public class Person
{
public string Name;
public int Age;
public string Location;
}
public class Record
{
public Person record;
}
This is surely an encoding problem. You have a different encoding in your database and in your website and this fact is the cause of the problem. Also if you ran that command you have to change the records that are already in your tables to convert those character in UTF-8.
Update: Based on your last comment, the core of the problem is that you have a database and a data source (the CSV file) which use different encoding. Hence you can convert your database in UTF-8 or, at least, when you get the data that are in the CSV, you have to convert them from UTF-8 to latin1.
You can do the convertion following this articles:
I have had the same problem over and over again. Now many users here now I'm famous for my HAX work,
so I solve it by using:
PHP:
echo "<p style="display:none" id=\"hidden-GET\">".$_GET['id']."</p>";
JS:
document.getElementById("hidden-GET").innerHTML;
Simple HAX but working.
The formula would be (original - discounted)/original
. i.e. (365-165)/365 = 0.5479...
Don't know if you solved the problem but if anyone has this problem in future.
$python
>>import numpy
>>print(numpy)
Go to the location printed and delete the numpy
installation found there. You can then use pip
or easy_install
https://wordpress.org/plugins/remove-category-url/ Use this plugin it does the job perfectly of hiding the category-base It does not require any setting just install and activate.
class Test
{
Dictionary<int, string> entities;
public string GetEntity(int code)
{
// java's get method returns null when the key has no mapping
// so we'll do the same
string val;
if (entities.TryGetValue(code, out val))
return val;
else
return null;
}
}
Since the suggestion of a loop implies the request for a procedure type solution. Here is mine.
Any query which works on any single record taken from a table can be wrapped in a procedure to make it run through each row of a table like so:
First delete any existing procedure with the same name, and change the delimiter so your SQL doesn't try to run each line as you're trying to write the procedure.
DROP PROCEDURE IF EXISTS ROWPERROW;
DELIMITER ;;
Then here's the procedure as per your example (table_A and table_B used for clarity)
CREATE PROCEDURE ROWPERROW()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*) FROM table_A INTO n;
SET i=0;
WHILE i<n DO
INSERT INTO table_B(ID, VAL) SELECT (ID, VAL) FROM table_A LIMIT i,1;
SET i = i + 1;
END WHILE;
End;
;;
Then dont forget to reset the delimiter
DELIMITER ;
And run the new procedure
CALL ROWPERROW();
You can do whatever you like at the "INSERT INTO" line which I simply copied from your example request.
Note CAREFULLY that the "INSERT INTO" line used here mirrors the line in the question. As per the comments to this answer you need to ensure that your query is syntactically correct for which ever version of SQL you are running.
In the simple case where your ID field is incremented and starts at 1 the line in the example could become:
INSERT INTO table_B(ID, VAL) VALUES(ID, VAL) FROM table_A WHERE ID=i;
Replacing the "SELECT COUNT" line with
SET n=10;
Will let you test your query on the first 10 record in table_A only.
One last thing. This process is also very easy to nest across different tables and was the only way I could carry out a process on one table which dynamically inserted different numbers of records into a new table from each row of a parent table.
If you need it to run faster then sure try to make it set based, if not then this is fine. You could also rewrite the above in cursor form but it may not improve performance. eg:
DROP PROCEDURE IF EXISTS cursor_ROWPERROW;
DELIMITER ;;
CREATE PROCEDURE cursor_ROWPERROW()
BEGIN
DECLARE cursor_ID INT;
DECLARE cursor_VAL VARCHAR;
DECLARE done INT DEFAULT FALSE;
DECLARE cursor_i CURSOR FOR SELECT ID,VAL FROM table_A;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cursor_i;
read_loop: LOOP
FETCH cursor_i INTO cursor_ID, cursor_VAL;
IF done THEN
LEAVE read_loop;
END IF;
INSERT INTO table_B(ID, VAL) VALUES(cursor_ID, cursor_VAL);
END LOOP;
CLOSE cursor_i;
END;
;;
Remember to declare the variables you will use as the same type as those from the queried tables.
My advise is to go with setbased queries when you can, and only use simple loops or cursors if you have to.
//By using jquery json parser
var obj = $.parseJSON('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(obj['jobtitel']);
//By using javasript json parser
var t = JSON.parse('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(t['jobtitel'])
As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON strings use the native JSON.parse method instead.
I use this function (SQL Server 2005 and above).
create function [dbo].[Split]
(
@string nvarchar(4000),
@delimiter nvarchar(10)
)
returns @table table
(
[Value] nvarchar(4000)
)
begin
declare @nextString nvarchar(4000)
declare @pos int, @nextPos int
set @nextString = ''
set @string = @string + @delimiter
set @pos = charindex(@delimiter, @string)
set @nextPos = 1
while (@pos <> 0)
begin
set @nextString = substring(@string, 1, @pos - 1)
insert into @table
(
[Value]
)
values
(
@nextString
)
set @string = substring(@string, @pos + len(@delimiter), len(@string))
set @nextPos = @pos
set @pos = charindex(@delimiter, @string)
end
return
end
can be two reason
You are correct. You did exactly the right thing, checking the query plan rather than trying to second-guess the optimiser. :-)
Super simple explanation:
Fact table: a data table that maps lookup IDs together. Is usually one of the main tables central to your application.
Dimension table: a lookup table used to store values (such as city names or states) that are repeated frequently in the fact table.
I solved the same problem by installing "matplotlib".
If your PC is secure or you don't care about password security, this can be achieved very simply. Assuming that the remote repository is on GitHub and origin
is your local name for the remote repository, use this command
git remote set-url --push origin https://<username>:<password>@github.com/<repo>
The --push
flag ensures this changes the URL of the repository for the git push
command only. (The question asked in the original post is about git push
command only. Requiring a username+password only for push operations is the normal setup for public repositories on GitHub . Note that private repositories on GitHub would also require a username+password for pull and fetch operations, so for a private repository you would not want to use the --push flag
...)
WARNING: This is inherently unsecure because:
your ISP, or anyone logging your network accesses, can easily see the password in plain text in the URL;
anyone who gains access to your PC can view your password using git remote show origin
.
That's why using an SSH key is the accepted answer.
Even an SSH key is not totally secure. Anyone who gains access to your PC can still, for example, make pushes which wreck your repository or - worse - push commits making subtle changes to your code. (All pushed commits are obviously highly visible on GitHub. But if someone wanted to change your code surreptitiously, they could --amend
a previous commit without changing the commit message, and then force push it. That would be stealthy and quite hard to notice in practice.)
But revealing your password is worse. If an attacker gains knowledge of your username+password, they can do things like lock you out of your own account, delete your account, permanently delete the repository, etc.
Alternatively - for simplicity and security - you can supply only your username in the URL, so that you will have to type your password every time you git push
but you will not have to give your username each time. (I quite like this approach, having to type the password gives me a pause to think each time I git push
, so I cannot git push
by accident.)
git remote set-url --push origin https://<username>@github.com/<repo>
For the fastest way $ cd "project"
Here's another way:
>>> L = range (11)
>>> map(lambda x: x if x%2 else None, L)
[None, 1, None, 3, None, 5, None, 7, None, 9, None]
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.
class A {
void msg() {
System.out.println("From A");
}
}
class B {
void msg() {
System.out.println("From B");
}
}
class C extends A,B { // suppose if this was possible
public static void main(String[] args) {
C obj = new C();
obj.msg(); // which msg() method would be invoked?
}
}
Can you clarify your question? What is "ohHover" in this case and how does it correspond to a delay in hover time?
That said, I think what you probably want is...
var timeout;
element.onmouseover = function(e) {
timeout = setTimeout(function() {
// ...
}, delayTimeMs)
};
element.onmouseout = function(e) {
if(timeout) {
clearTimeout(timeout);
}
};
Or addEventListener
/attachEvent
or your favorite library's event abstraction method.
Another library that supports this is jOO?, and its Seq.distinct(Function<T,U>)
method:
Seq.seq(persons).distinct(Person::getName).toList();
Under the hood, it does practically the same thing as the accepted answer, though.
Additional information about removing/uninstalling composer
Answers above did not help me, but what did help me is removing:
Hope this helps.
You can find out all the methods available on a String by opening irb and running:
"MyString".methods.sort
And for a list of the methods available for strings in particular:
"MyString".own_methods.sort
I use this to find out new and interesting things about objects which I might not otherwise have known existed.
The problem is that your Python version and the library you want to use are not same versionally (Python). Even if you install Python's latest version, your PATH might not change properly and automatically. Thus, you should change it manually.After matching their version, it will work.
Ex: When I tried to install Django3, I got same error. I noticed that my PATH still seems C:\python27\Scripts though I already install Python3.8, so that I manually edited my PATH C:\python38\Scripts and reinstalled pip install Django and everything worked well.
A statement contains a keyword.
An expression does not contain a keyword.
print "hello"
is statement, because print
is a keyword.
"hello"
is an expression, but list compression is against this.
The following is an expression statement, and it is true without list comprehension:
(x*2 for x in range(10))
Most common usage for this would be to merge the values of two enums into one group and treat them similarly. For example, see how to join Fruits and Vegatables.
I got this error too but for a different reason. It turns out I had made a typo when I tried to specify the version number as a variable:
dependencies {
// ...
implementation "com.google.android.gms:play-services-location:{$playServices}"
// ...
}
I had defined the variable playServices in gradle.properties in my project's root directory:
playServices=15.0.1
The typo was {$playServices}
which should have said ${playServices}
like this:
dependencies {
// ...
implementation "com.google.android.gms:play-services-location:${playServices}"
// ...
}
That fixed the problem for me.
Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:
type: "GET",
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: function (data) {
alert(data);
});
Add a vertical-align
property to the TD, like this:
<td style="width: 259px; vertical-align: top;">
main page
</td>
When you push a new branch the first time use: >git push -u origin
After that, you can just type a shorter command: >git push
The first-time -u option created a persistent upstream tracking branch with your local branch.
Here's the code:
glPushMatrix();
glTranslatef(18,2,0);
glRotatef(angle, 0, 0, 0.7);
glColor3ub(0,255,255);
glutWireSphere(3,10,10);
glPopMatrix();
You should execute the command on every loop instead of building a huge command Text(btw,StringBuilder is made for this) The underlying Connection will not close and re-open for each loop, let the connection pool manager handle this. Have a look at this link for further informations: Tuning Up ADO.NET Connection Pooling in ASP.NET Applications
If you want to ensure that every command is executed successfully you can use a Transaction and Rollback if needed,
try this
SELECT
Orders.OrderNumber,
LineItems.Quantity,
LineItems.Description
FROM Orders
INNER JOIN (
SELECT
Orders.OrderNumber,
Max(LineItem.LineItemID) AS LineItemID
FROM Orders
INNER JOIN LineItems
ON Orders.OrderNumber = LineItems.OrderNumber
GROUP BY Orders.OrderNumber
) AS Items ON Orders.OrderNumber = Items.OrderNumber
INNER JOIN LineItems
ON Items.LineItemID = LineItems.LineItemID
This is what worked for me
function showErrorMessage(xhr, status, error) {
if (xhr.responseText != "") {
var jsonResponseText = $.parseJSON(xhr.responseText);
var jsonResponseStatus = '';
var message = '';
$.each(jsonResponseText, function(name, val) {
if (name == "ResponseStatus") {
jsonResponseStatus = $.parseJSON(JSON.stringify(val));
$.each(jsonResponseStatus, function(name2, val2) {
if (name2 == "Message") {
message = val2;
}
});
}
});
alert(message);
}
}