Use SweetAlert's html
setting.
You can set output html direct to this option:
var hh = "<b>test</b>";
swal({
title: "" + txt + "",
html: "Testno sporocilo za objekt " + hh + "",
confirmButtonText: "V redu",
allowOutsideClick: "true"
});
Or
swal({
title: "" + txt + "",
html: "Testno sporocilo za objekt <b>teste</b>",
confirmButtonText: "V redu",
allowOutsideClick: "true"
});
Probably you are looking for something like this:
Accept "2.0 or 2.0 as an INT but reject 2.1 and "2.1"
num = 2.0
if num.is_a? String num = Float(num) rescue false end
new_num = Integer(num) rescue false
puts num
puts new_num
puts num == new_num
I ended up on this question when searching for an api to decode url in a win32 c++ app. Since the question doesn't quite specify platform assuming windows isn't a bad thing.
InternetCanonicalizeUrl is the API for windows programs. More info here
LPTSTR lpOutputBuffer = new TCHAR[1];
DWORD dwSize = 1;
BOOL fRes = ::InternetCanonicalizeUrl(strUrl, lpOutputBuffer, &dwSize, ICU_DECODE | ICU_NO_ENCODE);
DWORD dwError = ::GetLastError();
if (!fRes && dwError == ERROR_INSUFFICIENT_BUFFER)
{
delete lpOutputBuffer;
lpOutputBuffer = new TCHAR[dwSize];
fRes = ::InternetCanonicalizeUrl(strUrl, lpOutputBuffer, &dwSize, ICU_DECODE | ICU_NO_ENCODE);
if (fRes)
{
//lpOutputBuffer has decoded url
}
else
{
//failed to decode
}
if (lpOutputBuffer !=NULL)
{
delete [] lpOutputBuffer;
lpOutputBuffer = NULL;
}
}
else
{
//some other error OR the input string url is just 1 char and was successfully decoded
}
InternetCrackUrl (here) also seems to have flags to specify whether to decode url
This worked for me - Swift 3
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCell(withIdentifier: "customTableCell") as! CustomTableCell
return headerCell
}
I've come up with the following method, which works for me because in every case the model will have a ModelForm associated with it.
def GetModelData(form, fields):
"""
Extract data from the bound form model instance and return a
dictionary that is easily usable in templates with the actual
field verbose name as the label, e.g.
model_data{"Address line 1": "32 Memory lane",
"Address line 2": "Brainville",
"Phone": "0212378492"}
This way, the template has an ordered list that can be easily
presented in tabular form.
"""
model_data = {}
for field in fields:
model_data[form[field].label] = eval("form.data.%s" % form[field].name)
return model_data
@login_required
def clients_view(request, client_id):
client = Client.objects.get(id=client_id)
form = AddClientForm(client)
fields = ("address1", "address2", "address3", "address4",
"phone", "fax", "mobile", "email")
model_data = GetModelData(form, fields)
template_vars = RequestContext(request,
{
"client": client,
"model_data": model_data
}
)
return render_to_response("clients-view.html", template_vars)
Here is an extract from the template I am using for this particular view:
<table class="client-view">
<tbody>
{% for field, value in model_data.items %}
<tr>
<td class="field-name">{{ field }}</td><td>{{ value }}</td>
</tr>
{% endfor %}
</tbody>
</table>
The nice thing about this method is that I can choose on a template-by-template basis the order in which I would like to display the field labels, using the tuple passed in to GetModelData and specifying the field names. This also allows me to exclude certain fields (e.g. a User foreign key) as only the field names passed in via the tuple are built into the final dictionary.
I'm not going to accept this as the answer because I'm sure someone can come up with something more "Djangonic" :-)
Update: I'm choosing this as the final answer because it is the simplest out of those given that does what I need. Thanks to everyone who contributed answers.
DONT: This is not a solution!
My first approach was:
public int longToInt(long theLongOne) {
return Long.valueOf(theLongOne).intValue();
}
But that merely just casts the long to an int, potentially creating new Long
instances or retrieving them from the Long pool.
The drawbacks
Long.valueOf
creates a new Long
instance if the number is not within Long
's pool range [-128, 127].
The intValue
implementation does nothing more than:
return (int)value;
So this can be considered even worse than just casting the long
to int
.
The first link to sp_generate_inserts is pretty cool, here is a really simple version:
DECLARE @Fields VARCHAR(max); SET @Fields = '[QueueName], [iSort]' -- your fields, keep []
DECLARE @Table VARCHAR(max); SET @Table = 'Queues' -- your table
DECLARE @SQL VARCHAR(max)
SET @SQL = 'DECLARE @S VARCHAR(MAX)
SELECT @S = ISNULL(@S + '' UNION '', ''INSERT INTO ' + @Table + '(' + @Fields + ')'') + CHAR(13) + CHAR(10) +
''SELECT '' + ' + REPLACE(REPLACE(REPLACE(@Fields, ',', ' + '', '' + '), '[', ''''''''' + CAST('),']',' AS VARCHAR(max)) + ''''''''') +' FROM ' + @Table + '
PRINT @S'
EXEC (@SQL)
On my system, I get this result:
INSERT INTO Queues([QueueName], [iSort])
SELECT 'WD: Auto Capture', '10' UNION
SELECT 'Car/Lar', '11' UNION
SELECT 'Scan Line', '21' UNION
SELECT 'OCR', '22' UNION
SELECT 'Dynamic Template', '23' UNION
SELECT 'Fix MICR', '41' UNION
SELECT 'Fix MICR (Supervisor)', '42' UNION
SELECT 'Foreign MICR', '43' UNION
...
You can also use react router dom library useHistory;
`
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
`
Doesn't too much matter. Whatever makes you happy will work. There aren't a lot of silly rules because Python projects can be simple.
/scripts
or /bin
for that kind of command-line interface stuff/tests
for your tests/lib
for your C-language libraries/doc
for most documentation/apidoc
for the Epydoc-generated API docs.And the top-level directory can contain README's, Config's and whatnot.
The hard choice is whether or not to use a /src
tree. Python doesn't have a distinction between /src
, /lib
, and /bin
like Java or C has.
Since a top-level /src
directory is seen by some as meaningless, your top-level directory can be the top-level architecture of your application.
/foo
/bar
/baz
I recommend putting all of this under the "name-of-my-product" directory. So, if you're writing an application named quux
, the directory that contains all this stuff is named /quux
.
Another project's PYTHONPATH
, then, can include /path/to/quux/foo
to reuse the QUUX.foo
module.
In my case, since I use Komodo Edit, my IDE cuft is a single .KPF file. I actually put that in the top-level /quux
directory, and omit adding it to SVN.
ssh user@machine python < script.py - arg1 arg2
Because cat |
is usually not necessary
In many environments (e.g. Heroku), and as a convention, you can set the environment variable PORT
to tell your web server what port to listen on.
So process.env.PORT || 3000
means: whatever is in the environment variable PORT, or 3000 if there's nothing there.
So you pass that to app.listen
, or to app.set('port', ...)
, and that makes your server able to accept a "what port to listen on" parameter from the environment.
If you pass 3000
hard-coded to app.listen()
, you're always listening on port 3000, which might be just for you, or not, depending on your requirements and the requirements of the environment in which you're running your server.
I use both because sometimes they give different, useful error messages.
The Python project was able to find and fix a number of small buglets when one of the core developers first tried compiling with clang.
Here's some more detailed information on what Client, Resource, and Session are all about.
Client:
Here's an example of client-level access to an S3 bucket's objects (at most 1000**):
import boto3
client = boto3.client('s3')
response = client.list_objects_v2(Bucket='mybucket')
for content in response['Contents']:
obj_dict = client.get_object(Bucket='mybucket', Key=content['Key'])
print(content['Key'], obj_dict['LastModified'])
** you would have to use a paginator, or implement your own loop, calling list_objects() repeatedly with a continuation marker if there were more than 1000.
Resource:
Here's the equivalent example using resource-level access to an S3 bucket's objects (all):
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.all():
print(obj.key, obj.last_modified)
Note that in this case you do not have to make a second API call to get the objects; they're available to you as a collection on the bucket. These collections of subresources are lazily-loaded.
You can see that the Resource
version of the code is much simpler, more compact, and has more capability (it does pagination for you). The Client
version of the code would actually be more complicated than shown above if you wanted to include pagination.
Session:
A useful resource to learn more about these boto3 concepts is the introductory re:Invent video.
Update: you can read the more complex answer, which contains more methods and information.
There exists a couple of scripts, which can be used as simple package managers. But as far as I know, none of them allows you to upgrade packages, because it’s not an easy task on Windows since there is not possible to overwrite files in use. So you have to close all Cygwin instances first and then you can use Cygwin’s native setup.exe (which itself does the upgrade via “replace after reboot” method, when files are in use).
The best one for me. Simply because it’s one of the most recent. It works correctly for both platforms - x86 and x86_64. There exists a lot of forks with some additional features. For example the kou1okada fork is one of improved versions.
It has also command line mode. Moreover it allows you to upgrade all installed packages at once.
setup.exe-x86_64.exe -q --packages=bash,vim
Example use:
setup.exe-x86_64.exe -q --packages="bash,vim"
You can create an alias for easier use, for example:
alias cyg-get="/cygdrive/d/path/to/cygwin/setup-x86_64.exe -q -P"
Then you can for example install the Vim package with:
cyg-get vim
use my function as diagnostic certificates issues - see screen
System.Net.ServicePointManager.ServerCertificateValidationCallback = Function(s As Object,
cert As System.Security.Cryptography.X509Certificates.X509Certificate,
chain As System.Security.Cryptography.X509Certificates.X509Chain,
err As System.Net.Security.SslPolicyErrors)
Return True
End Function
According to seppo0010 comment, I used the rename function to do that.
http://nodejs.org/docs/latest/api/fs.html#fs_fs_rename_oldpath_newpath_callback
fs.rename(oldPath, newPath, callback)
Added in: v0.0.2
oldPath <String> | <Buffer> newPath <String> | <Buffer> callback <Function>
Asynchronous rename(2). No arguments other than a possible exception are given to the completion callback.
Another way to do it in Angular:
Markup:
<textarea #inputMessage></textarea>
Add ViewChild()
property:
@ViewChild('inputMessage')
inputMessageRef: ElementRef;
Scroll anywhere you want inside of the component using scrollIntoView()
function:
this.inputMessageRef.nativeElement.scrollIntoView();
The this-operator can simplify your life:
var Y = function(f) {
return (function(g) {
return g(g);
})(function(h) {
return function() {
return f.apply(h(h), arguments);
};
});
};
Then you avoid the extra function:
var fac = Y(function(n) {
return n == 0 ? 1 : n * this(n - 1);
});
Finally, you call fac(5)
.
If you're using Angular's ng-repeat to populate the table hackel's jquery snippet will not work by placing it in the document load event. You'll need to run the snippet after angular has finished rendering the table.
To trigger an event after ng-repeat has rendered try this directive:
var app = angular.module('myapp', [])
.directive('onFinishRender', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function () {
scope.$emit('ngRepeatFinished');
});
}
}
}
});
Complete example in angular: http://jsfiddle.net/ADukg/6880/
I got the directive from here: Use AngularJS just for routing purposes
You can use jasper report.
iReport is a very effective tool to develop jasper reports.
It supports almost all the facilities provided by crystal report like formatting, grouping, creation of charts etc.
Refer the link for tutorial:
Java has a Random class in the java.util package. Using it you can do the following:
Random rnd = new Random();
int randomNumberFromArray = array[rnd.nextInt(3)];
Hope this helps!
easier way. You could make your object inherit from the Error object. Example:
function NotImplementError(message)
{
this.message = message;
Error.call();
Error.call(message);
}
what we are doing is using the function call() which call the constructor of the Error class so is basicly the same thing as implementing a class inheritance in other object oriented languages.
Sets remove duplicate items. In order to do that, the item can't change while in the set. Lists can change after being created, and are termed 'mutable'. You cannot put mutable things in a set.
Lists have an unmutable equivalent, called a 'tuple'. This is how you would write a piece of code that took a list of lists, removed duplicate lists, then sorted it in reverse.
result = sorted(set(map(tuple, my_list)), reverse=True)
Additional note: If a tuple contains a list, the tuple is still considered mutable.
Some examples:
>>> hash( tuple() )
3527539
>>> hash( dict() )
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
hash( dict() )
TypeError: unhashable type: 'dict'
>>> hash( list() )
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
hash( list() )
TypeError: unhashable type: 'list'
You can also use JFormattedTextField
, which is much simpler to use. Example:
public static void main(String[] args) {
NumberFormat format = NumberFormat.getInstance();
NumberFormatter formatter = new NumberFormatter(format);
formatter.setValueClass(Integer.class);
formatter.setMinimum(0);
formatter.setMaximum(Integer.MAX_VALUE);
formatter.setAllowsInvalid(false);
// If you want the value to be committed on each keystroke instead of focus lost
formatter.setCommitsOnValidEdit(true);
JFormattedTextField field = new JFormattedTextField(formatter);
JOptionPane.showMessageDialog(null, field);
// getValue() always returns something valid
System.out.println(field.getValue());
}
SQLite database FAQ: How do I drop a SQLite database?
People used to working with other databases are used to having a "drop database" command, but in SQLite there is no similar command. The reason? In SQLite there is no "database server" -- SQLite is an embedded database, and your database is entirely contained in one file. So there is no need for a SQLite drop database command.
To "drop" a SQLite database, all you have to do is delete the SQLite database file you were accessing.
copy from http://alvinalexander.com/android/sqlite-drop-database-how
Instead of using fake dates like 0000-00-00 00:00:00
or 0001-01-01 00:00:00
(the latter should be accepted as it is a valid date), change your database schema, to allow NULL
values.
ALTER TABLE table_name MODIFY COLUMN date TIMESTAMP NULL
I have created the Fade in and Fade Out animation for Dialogbox using ChrisJD code.
Inside res/style.xml
<style name="AppTheme" parent="android:Theme.Light" />
<style name="PauseDialog" parent="@android:style/Theme.Dialog">
<item name="android:windowAnimationStyle">@style/PauseDialogAnimation</item>
</style>
<style name="PauseDialogAnimation">
<item name="android:windowEnterAnimation">@anim/fadein</item>
<item name="android:windowExitAnimation">@anim/fadeout</item>
</style>
Inside anim/fadein.xml
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator"
android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500" />
Inside anim/fadeout.xml
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/anticipate_interpolator"
android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="500" />
MainActivity
Dialog imageDiaglog= new Dialog(MainActivity.this,R.style.PauseDialog);
One common convention is to use a "_" as a variable name for the elements of the tuple you wish to ignore. For instance:
def f():
return 1, 2, 3
_, _, x = f()
Kenny is right, just want to clear some things out.
border.xml
and put it in the folder res/drawable/
add the code
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#FF00FF00" />
<solid android:color="#ffffff" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="0dp" />
<corners android:radius="4dp" />
</shape>
set back ground like android:background="@drawable/border"
wherever you want the border
Mine first didn't work cause i put the border.xml
in the wrong folder!
Why are you sending it through a post if you already have it on the server (PHP) side?
Why not just save the array to s $_SESSION
variable so you can use it when the form gets submitted, that might make it more "secure" since then the client cannot change the variables by editing the source.
It all depends on what you really want to do.
Byte is not a standard data type in C/C++ but it can still be used the way i suppose you want it. Here is how: Recall that a byte is an eight bit memory size which can represent any of the integers between -128 and 127, inclusive. (There are 256 integers in that range; eight bits can represent 256 -- two raised to the power eight -- different values.). Also recall that a char in C/C++ is one byte (eight bits). So, all you need to do to have a byte data type in C/C++ is to put this code at the top of your source file: #define byte char So you can now declare byte abc[3];
IntVar = int("".join(filter(str.isdigit, StringVar)))
In Android Lollipop and above, define it in your theme style:
<style name="BaseAppTheme" parent="Material.Theme">
...
<item name="android:colorControlActivated">@color/color_switch</item>
</style>
window.addEventListener("scroll",function(){
window.lastScrollTime = new Date().getTime()
});
function is_scrolling() {
return window.lastScrollTime && new Date().getTime() < window.lastScrollTime + 500
}
Change the 500 to the number of milliseconds after the last scroll event at which you consider the user to be "no longer scrolling".
(addEventListener
is better than onScroll
because the former can coexist nicely with any other code that uses onScroll
.)
timeobj = datetime.datetime.strptime(my_time, '%Y-%m-%d %I:%M:%S')
File "/usr/lib/python2.7/_strptime.py", line 335, in _strptime
data_string[found.end():])
ValueError: unconverted data remains:
In my case, the problem was an extra space in the input date string. So I used strip()
and it started to work.
JSONP is the best option, in my opinion. Try to figure out why you get the syntax error - are you sure the received data is not JSON? Then maybe you're using the API wrong somehow.
Another way you could use, but I don't think that it applies in your case, is have an iFrame in the page which src is in the domain you want to call. Have it do the calls for you, and then use JS to communicate between the iFrame and the page. This will bypass the cross domain, but only if you can have the iFrame's src in the domain you want to call.
Uses aliases, so doesn't answer your question exactly but I find these useful for doing what you intend...
alias gitdiff-1="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 2|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff"
alias gitdiff-2="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 3|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff"
alias gitdiff-3="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 4|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff"
alias gitlog-1="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 2|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary"
alias gitlog-2="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 3|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary"
alias gitlog-3="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 4|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary"
If you turn-on 2-Step Verification, you need generate a special app password instead of using your common password. https://myaccount.google.com/security#signin
One angle not so far mentioned is tool sets used for editing the code.
Using Visual Studio Code along with the Extension from lukehoban called Go
will do some auto-magic for you. The Go extension automatically runs gofmt
, golint
etc, and removes and adds import
entries. So at least that part is now automatic.
I will admit its not 100% of the solution to the question, but however useful enough.
I know it's to late to answer this question. But if you are working with collection of type IList<> and you don't care about an order of the returned collection, then this method is working faster. I've used Mark Byers answer and made a little changes. So now method TakeLast is:
public static IEnumerable<T> TakeLast<T>(IList<T> source, int takeCount)
{
if (source == null) { throw new ArgumentNullException("source"); }
if (takeCount < 0) { throw new ArgumentOutOfRangeException("takeCount", "must not be negative"); }
if (takeCount == 0) { yield break; }
if (source.Count > takeCount)
{
for (int z = source.Count - 1; takeCount > 0; z--)
{
takeCount--;
yield return source[z];
}
}
else
{
for(int i = 0; i < source.Count; i++)
{
yield return source[i];
}
}
}
For test I have used Mark Byers method and kbrimington's andswer. This is test:
IList<int> test = new List<int>();
for(int i = 0; i<1000000; i++)
{
test.Add(i);
}
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
IList<int> result = TakeLast(test, 10).ToList();
stopwatch.Stop();
Stopwatch stopwatch1 = new Stopwatch();
stopwatch1.Start();
IList<int> result1 = TakeLast2(test, 10).ToList();
stopwatch1.Stop();
Stopwatch stopwatch2 = new Stopwatch();
stopwatch2.Start();
IList<int> result2 = test.Skip(Math.Max(0, test.Count - 10)).Take(10).ToList();
stopwatch2.Stop();
And here are results for taking 10 elements:
and for taking 1000001 elements results are:
To use am / pm with moment, here is a snippet from a react component
import Moment from 'moment';
const time = Moment().format("hh:mm a")
For reference please remember Moment.js is considered a legacy project that can carry performance overhead
Use this regular expression to match square brackets or single quotes:
/[\[\]']+/g
Replace with the empty string.
console.log("['abc','xyz']".replace(/[\[\]']+/g,''));
_x000D_
psql "sslmode=require host=localhost port=2345 dbname=postgres" --username=some_user
According to the postgres psql documentation, only the connection parameters should go in the conninfo string(that's why in our example, --username is not inside that string)
Open preview mode
follow the below link to fix the issue
Fix - Rendering Problems The Following classes could not be found : android.support.v7.internal
goto appTheme ----> select Holo Theme ---> refresh
Expanding upon the above code from @dreamlax
char *readFile(char *fileName) {
FILE *file = fopen(fileName, "r");
char *code;
size_t n = 0;
int c;
if (file == NULL) return NULL; //could not open file
fseek(file, 0, SEEK_END);
long f_size = ftell(file);
fseek(file, 0, SEEK_SET);
code = malloc(f_size);
while ((c = fgetc(file)) != EOF) {
code[n++] = (char)c;
}
code[n] = '\0';
return code;
}
This gives you the length of the file, then proceeds to read it character by character.
One option is to have a separate model for such manipulations, using the same table:
class NoCallbacksModel < ActiveRecord::Base
set_table_name 'table_name_of_model_that_has_callbacks'
include CommonModelMethods # if there are
:
:
end
(Same approach might make things easier for bypassing validations)
Stephan
A custom class to serialise:
[Serializable]
public class TestClass
{
int x = 2;
int y = 4;
public TestClass(){}
public TestClass(int x, int y)
{
this.x = x;
this.y = y;
}
public int TestFunction()
{
return x + y;
}
}
I have attached the code snippet. Maybe this can help you out.
static void Main(string[] args)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(TestClass));
MemoryStream memoryStream = new MemoryStream();
XmlTextWriter xmlWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
TestClass domain = new TestClass(10, 3);
xmlSerializer.Serialize(xmlWriter, domain);
memoryStream = (MemoryStream)xmlWriter.BaseStream;
string xmlSerializedString = ConvertByteArray2Str(memoryStream.ToArray());
TestClass xmlDomain = (TestClass)DeserializeObject(xmlSerializedString);
Console.WriteLine(xmlDomain.TestFunction().ToString());
Console.ReadLine();
}
Your problem is that class B is not declared as a "new-style" class. Change it like so:
class B(object):
and it will work.
super()
and all subclass/superclass stuff only works with new-style classes. I recommend you get in the habit of always typing that (object)
on any class definition to make sure it is a new-style class.
Old-style classes (also known as "classic" classes) are always of type classobj
; new-style classes are of type type
. This is why you got the error message you saw:
TypeError: super() argument 1 must be type, not classobj
Try this to see for yourself:
class OldStyle:
pass
class NewStyle(object):
pass
print type(OldStyle) # prints: <type 'classobj'>
print type(NewStyle) # prints <type 'type'>
Note that in Python 3.x, all classes are new-style. You can still use the syntax from the old-style classes but you get a new-style class. So, in Python 3.x you won't have this problem.
If you want to check if some string is present in another string, use something like String.contains
If you want to check if some pattern is present in a string, append and prepend the pattern with '.*'. The result will accept strings that contain the pattern.
Example: Suppose you have some regex a(b|c) that checks if a string matches ab
or ac
.*(a(b|c)).*
will check if a string contains a ab
or ac
.
A disadvantage of this method is that it will not give you the location of the match.
Here is an example using a generator's send()
method:
def restartable(seq):
while True:
for item in seq:
restart = yield item
if restart:
break
else:
raise StopIteration
Example Usage:
x = [1, 2, 3, 4, 5]
total = 0
r = restartable(x)
for item in r:
if item == 5 and total < 100:
total += r.send(True)
else:
total += item
You can achieve this by binding an onclick listener and then adding the animate class like this:
$('#button').onClick(function(){
$('#target_element').addClass('animate_class_name');
});
You can get if from your document_cache folder, subfolder (mine is 1946507). Once there, rename the "content" by adding .pdf to the end of the file, save, and open with any pdf reader.
If you are just looking for the files in a single directory (ie you are not trying to traverse a directory tree, which it doesn't look like), why not simply use os.listdir():
import os
for fn in os.listdir('.'):
if os.path.isfile(fn):
print (fn)
in place of os.walk(). You can specify a directory path as a parameter for os.listdir(). os.path.isfile() will determine if the given filename is for a file.
Even though it is an older post but as I came across it while looking for same problem so I thought I will add my two cents as well. Here is my version of Spinner's background with DropDown arrow. Just the complete background, not only the arrow.
Apply on spinner like...
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/spinner_bg" />
spinner_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<color android:color="@color/InputBg" />
</item>
<item android:gravity="center_vertical|right" android:right="8dp">
<layer-list>
<item android:width="12dp" android:height="12dp" android:gravity="center" android:bottom="10dp">
<rotate
android:fromDegrees="45"
android:toDegrees="45">
<shape android:shape="rectangle">
<solid android:color="#666666" />
<stroke android:color="#aaaaaa" android:width="1dp"/>
</shape>
</rotate>
</item>
<item android:width="30dp" android:height="10dp" android:bottom="21dp" android:gravity="center">
<shape android:shape="rectangle">
<solid android:color="@color/InputBg"/>
</shape>
</item>
</layer-list>
</item>
</layer-list>
@color/InputBg
should be replaced by the color you want as your background.
First it fills the background with desired color. Then a child layer-list makes a square and rotates it by 45 degrees and then a second Rectangle with background color covers the top part of rotated square making it look like a down arrow. (There is an extra stroke in rotated rectangle with is not really required)
Some scenarios don't always allow developers to switch scripting language.
My preference is definitely for JavaScript (and I have used it in new projects). However, maintaining older projects is still required and necessary. Unfortunately, these are written in VBScript.
So even though this solution doesn't offer true "try/catch" functionaility, the result is the same, and that's good enough for me to get the job done.
Type
:colorscheme
then Space followed by TAB.
or as Peter said,
:colorscheme
then Space followed by CTRLd
The short version of the command is :colo
so you can use it in the two previous commands, instead of using the "long form".
If you want to find and preview more themes, there are various websites like Vim colors
No CSS required. This should look fine on your page. You can set col-md-*
as per your needs
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="row">_x000D_
<div class="col-md-12">_x000D_
<form class="form-inline" role="form">_x000D_
<div class="col">_x000D_
<div class="form-group">_x000D_
<label for="inputEmail" class="col-sm-3">Email</label>_x000D_
<input type="email" class="form-control col-sm-7" id="inputEmail" placeholder="Email">_x000D_
</div>_x000D_
</div>_x000D_
<div class="col">_x000D_
<div class="form-group">_x000D_
<label for="inputPassword" class="col-sm-3">Email</label>_x000D_
<input type="password" class="form-control col-sm-7" id="inputPassword" placeholder="Email">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<button class="btn btn-primary">Button 1</button>_x000D_
_x000D_
<button class="btn btn-primary">Button 2</button>_x000D_
</form>_x000D_
</div>_x000D_
</div>
_x000D_
It seems that the version "20140702" of the example link in the question was the final version, because I downloaded this file on the 12th November 2014, i.e. the version from the 2nd of July 2014 was still the latest version on 12th of November. When I try manually all the possible versions/dates between today in this date, then I always get a page with error code "404" (file not found), which indicates that no new version was released since the 12th of November.
You can't access element like you did (document.frm_new_user_request
). You have to use the function getElementById
:
document.getElementById("frm_new_user_request")
So getting a value from an input could look like this:
var value = document.getElementById("frm_new_user_request").value
Also you can use some JavaScript framework, e.g. jQuery, which simplifies operations with DOM (Document Object Model) and also hides differences between various browsers from you.
Getting a value from an input using jQuery would look like this:
var value = $("#element).value
var value = $(".element).value
sudo ldconfig
ldconfig creates the necessary links and cache to the most recent shared libraries found in the directories specified on the command line, in the file /etc/ld.so.conf, and in the trusted directories (/lib and /usr/lib).
Generally package manager takes care of this while installing the new library, but not always (specially when you install library with cmake
).
And if the output of this is empty
$ echo $LD_LIBRARY_PATH
Please set the default path
$ LD_LIBRARY_PATH=/usr/local/lib
I didn't need anything robust like storing the string in attributes. I just needed to turn something like MyEnum.BillEveryWeek
into "bill every week" or MyEnum.UseLegacySystem
into "use legacy system"--basically split the enum by its camel-casing into individiual lower-case words.
public static string UnCamelCase(this Enum input, string delimiter = " ", bool preserveCasing = false)
{
var characters = input.ToString().Select((x, i) =>
{
if (i > 0 && char.IsUpper(x))
{
return delimiter + x.ToString(CultureInfo.InvariantCulture);
}
return x.ToString(CultureInfo.InvariantCulture);
});
var result = preserveCasing
? string.Concat(characters)
: string.Concat(characters).ToLower();
var lastComma = result.LastIndexOf(", ", StringComparison.Ordinal);
if (lastComma > -1)
{
result = result.Remove(lastComma, 2).Insert(lastComma, " and ");
}
return result;
}
MyEnum.UseLegacySystem.UnCamelCase()
outputs "use legacy system"
If you have multiple flags set, it will turn that into plain english (comma-delimited except an "and" in place of the last comma).
var myCustomerBehaviour = MyEnum.BillEveryWeek | MyEnum.UseLegacySystem | MyEnum.ChargeTaxes;
Console.WriteLine(myCustomerBehaviour.UnCamelCase());
//outputs "bill every week, use legacy system and charge taxes"
hibernate.hbm2ddl.auto
automatically validates and exports DDL to the schema when the sessionFactory is created.
By default, it does not perform any creation or modification automatically on DB. If the user sets one of the below values then it is doing DDL schema changes automatically.
create - doing creating a schema
<entry key="hibernate.hbm2ddl.auto" value="create">
update - updating existing schema
<entry key="hibernate.hbm2ddl.auto" value="update">
validate - validate existing schema
<entry key="hibernate.hbm2ddl.auto" value="validate">
create-drop - create and drop the schema automatically when a session is starts and ends
<entry key="hibernate.hbm2ddl.auto" value="create-drop">
Here is one that we have saved off to findcol.sql so we can run it easily from within SQLPlus
set verify off
clear break
accept colnam prompt 'Enter Column Name (or part of): '
set wrap off
select distinct table_name,
column_name,
data_type || ' (' ||
decode(data_type,'LONG',null,'LONG RAW',null,
'BLOB',null,'CLOB',null,'NUMBER',
decode(data_precision,null,to_char(data_length),
data_precision||','||data_scale
), data_length
) || ')' data_type
from all_tab_columns
where column_name like ('%' || upper('&colnam') || '%');
set verify on
On the server, try:
netstat -an
and look to see if tcp port 22
is opened (use findstr
in Windows or grep
in Unix).
You can also implement the like queries using Spring Data JPA supported keyword "Containing".
List<Registration> findByPlaceContaining(String place);
To update the answer of overriding the way JSON works (probably not recommended, but super simple), don't use circular-json
(it's deprecated). Instead, use the successor, flatted:
https://www.npmjs.com/package/flatted
Borrowed from the old answer above from @user1541685 , but replaced with the new one:
npm i --save flatted
then in your js file
const CircularJSON = require('flatted');
const json = CircularJSON.stringify(obj);
This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.
After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.
You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .
In this very basic example, we send a request to myAjax.php
when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output
.
The javascript
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'myAjax.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
The HTML
<a href="#" onclick="return getOutput();"> test </a>
<div id="output">waiting for action</div>
The PHP
// file myAjax.php
<?php
echo 'hello world!';
?>
Try it out: http://jsfiddle.net/GRMule/m8CTk/
Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.
Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:
// handles the click event, sends the query
function getOutput() {
$.ajax({
url:'myAjax.php',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
}
Try it out: http://jsfiddle.net/GRMule/WQXXT/
Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.
If this is all you need to do, write the plain javascript once and you're done.
Documentation
XMLHttpRequest
on MDN - https://developer.mozilla.org/en/XMLHttpRequestXMLHttpRequest
on MSDN - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspxjQuery.ajax
- http://api.jquery.com/jQuery.ajax/simple and easier solution:
select extract(hour from systimestamp) from dual;
EXTRACT(HOURFROMSYSTIMESTAMP)
-----------------------------
16
If you have Excel 2010 you can copy your data into another column, than select it and choose Data -> Remove Duplicates. You can then write =COUNTIF($A$1:$A$100,B1)
next to it and copy the formula down. This assumes you have your values in range A1:A100
and the de-duplicated values are in column B.
Try:
EditText edt = (EditText) findViewById(R.id.YourEditText);
RelativeLayout.LayoutParams lp =
new RelativeLayout.LayoutParams
(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT
);
lp.setMargins(25, 0, 0, 0); // move 25 px to right (increase left margin)
edt.setLayoutParams(lp); // lp.setMargins(left, top, right, bottom);
The old fashion emacs bindings can still work in iterm2 and os x terminal:
Preferences -> Profiles -> Keys (sub tab in profiles)
Left/Right option <kbd>?</kbd> key acts as +Esc
(similar in os x terminal)This should enable alt-f and alt-b for moving words by words. (Still ctrl-a and ctrl-e always work as usual)
If set as meta
those old bindings will work while some iterm2 bindings unavailable.
This should works with windows server 2012 and IE.
var alert = driver.SwitchTo().Alert();
alert.SetAuthenticationCredentials("username", "password");
alert.Accept();
Check android studio event log as it could be low storage issue.
emulator: ERROR: Not enough disk space to run AVD 'Nexus_5_API_21'. Exiting...
SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.
Let's suppose you have two databases on the same server - Db1
and Db2
. Db1
has a table called Clients
with a column ClientId
and Db2
has a table called Messages
with a column ClientId
(let's leave asside why those tables are in different databases).
Now, to perform a join on the above-mentioned tables you will be using this query:
select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId
"Allocation Failure" is a cause of GC cycle to kick in.
"Allocation Failure" means that no more space left in Eden to allocate object. So, it is normal cause of young GC.
Older JVM were not printing GC cause for minor GC cycles.
"Allocation Failure" is almost only possible cause for minor GC. Another reason for minor GC to kick could be CMS remark phase (if +XX:+ScavengeBeforeRemark
is enabled).
Use Linq's Union:
using System.Linq;
var l1 = new List<int>() { 1,2,3,4,5 };
var l2 = new List<int>() { 3,5,6,7,8 };
var l3 = l1.Union(l2).ToList();
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
$id = implode(',',$_POST['id']);
echo $id
you cannot echo an array because it will just print out Array. If you wanna print out an array use print_r
.
print_r($_POST['id']);
To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.
class YourClass():
def your_function(self, *args):
self.callable_function(param) # if you need to pass any parameter
def callable_function(self, *params):
print('Your param:', param)
Pandas supports NumPy syntax which allows:
df[len(df) -1:].index[0]
Since Apache library is deprecated, for those who want to use HttpURLConncetion
, I wrote this class to send Get and Post Request with the help of this answer:
public class WebService {
static final String COOKIES_HEADER = "Set-Cookie";
static final String COOKIE = "Cookie";
static CookieManager msCookieManager = new CookieManager();
private static int responseCode;
public static String sendPost(String requestURL, String urlParameters) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
if (msCookieManager.getCookieStore().getCookies().size() > 0) {
//While joining the Cookies, use ',' or ';' as needed. Most of the server are using ';'
conn.setRequestProperty(COOKIE ,
TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
}
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
if (urlParameters != null) {
writer.write(urlParameters);
}
writer.flush();
writer.close();
os.close();
Map<String, List<String>> headerFields = conn.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
for (String cookie : cookiesHeader) {
msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
}
}
setResponseCode(conn.getResponseCode());
if (getResponseCode() == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
// HTTP GET request
public static String sendGet(String url) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla");
/*
* https://stackoverflow.com/questions/16150089/how-to-handle-cookies-in-httpurlconnection-using-cookiemanager
* Get Cookies form cookieManager and load them to connection:
*/
if (msCookieManager.getCookieStore().getCookies().size() > 0) {
//While joining the Cookies, use ',' or ';' as needed. Most of the server are using ';'
con.setRequestProperty(COOKIE ,
TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
}
/*
* https://stackoverflow.com/questions/16150089/how-to-handle-cookies-in-httpurlconnection-using-cookiemanager
* Get Cookies form response header and load them to cookieManager:
*/
Map<String, List<String>> headerFields = con.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
for (String cookie : cookiesHeader) {
msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
}
}
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
public static void setResponseCode(int responseCode) {
WebService.responseCode = responseCode;
Log.i("Milad", "responseCode" + responseCode);
}
public static int getResponseCode() {
return responseCode;
}
}
If you simply want to create a new branch without immediately changing to it, you could do the following:
git branch newbranch v1.0
This is a simple and maybe not the best solution, but it works.
On the line above the line you get your error, paste this:
// eslint-disable-next-line no-restricted-globals
The correct form, based on the original syntax, and correctly normalized is:
def gaussian(x, mu, sig):
return 1./(np.sqrt(2.*np.pi)*sig)*np.exp(-np.power((x - mu)/sig, 2.)/2)
For Swift 4.0 and iOS 10
extension UIImage {
func resizeImage(_ dimension: CGFloat, opaque: Bool, contentMode: UIViewContentMode = .scaleAspectFit) -> UIImage {
var width: CGFloat
var height: CGFloat
var newImage: UIImage
let size = self.size
let aspectRatio = size.width/size.height
switch contentMode {
case .scaleAspectFit:
if aspectRatio > 1 { // Landscape image
width = dimension
height = dimension / aspectRatio
} else { // Portrait image
height = dimension
width = dimension * aspectRatio
}
default:
fatalError("UIIMage.resizeToFit(): FATAL: Unimplemented ContentMode")
}
if #available(iOS 10.0, *) {
let renderFormat = UIGraphicsImageRendererFormat.default()
renderFormat.opaque = opaque
let renderer = UIGraphicsImageRenderer(size: CGSize(width: width, height: height), format: renderFormat)
newImage = renderer.image {
(context) in
self.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
}
} else {
UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), opaque, 0)
self.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
}
return newImage
}
}
To send to both remote with one command, you can create a alias for it:
git config alias.pushall '!git push origin devel && git push github devel'
With this, when you use the command git pushall
, it will update both repositories.
Use Range("A1").Text
instead of .Value
post comment edit:
Why?
Because the .Text
property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92
then <- Text
will return exactly what it in the cell including any formatting.
The .Value
and .Value2
properties return what's stored in the cell under the hood excluding formatting. Specially .Value2
for date types, it will return the decimal representation.
If you want to dig deeper into the meaning and performance, I just found this article
which seems like a good guide
another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
now,
paste this code in a module
Sub main()
Dim ws As Worksheet, i&, j&
Set ws = Sheets(1)
For i = 3 To 7
For j = 1 To 4
Debug.Print _
"row " & i & vbTab & vbTab & _
Cells(i, j).Text & vbTab & _
Cells(i, j).Value & vbTab & _
Cells(i, j).Value2
Next j
Next i
End Sub
and Analyse
the output! Its really easy and there isn't much more i can do to help :)
.TEXT .VALUE .VALUE2
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 4 1 1 1
row 4 1 1 1
row 4 01/01/1900 31/12/1899 1
row 4 1.00% 0.01 0.01
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 6 63 63 63
row 6 =7*9 =7*9 =7*9
row 6 03/03/1900 03/03/1900 63
row 6 6300.00% 63 63
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013 29/05/2013 29/05/2013
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013% 29/05/2013% 29/05/2013%
I had similar issue recently. Regional settings were properly setup both in app and database server. However, execution of SQL resulted in
"The conversion of a varchar data type to a datetime data type resulted in an out-of-range value".
The problem was the default language of the db user.
To check or change it in SSMS go to Security -> Logins and right-click the username of the user that runs the queries. Select properties -> general and make sure the default language at the bottom of the dialog is what you expect.
Repeat this for all users that run queries.
You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.
Use this: $newDate = $dateInDB->format('Y-m-d');
Set decoding to true
Your decoding is not set to true. If you don't have access to set the source to true. The code below will fix it for you.
$WorkingArray = json_decode(json_encode($data),true);
For questions like this, it is always worth taking a look in the manual first. Date and time functions in the mySQL manual
CURDATE()
returns the DATE part of the current time. Manual on CURDATE()
NOW()
returns the date and time portions as a timestamp in various formats, depending on how it was requested. Manual on NOW().
Here is a solution using boxplot.stats
# create a dummy data frame with outliers
df = data.frame(y = c(-100, rnorm(100), 100))
# create boxplot that includes outliers
p0 = ggplot(df, aes(y = y)) + geom_boxplot(aes(x = factor(1)))
# compute lower and upper whiskers
ylim1 = boxplot.stats(df$y)$stats[c(1, 5)]
# scale y limits based on ylim1
p1 = p0 + coord_cartesian(ylim = ylim1*1.05)
The best way I found, aside of using a dedicated commit GUI, is to use git difftool -d
- This opens your diff tool in directory comparison mode, comparing HEAD with current dirty folder.
First of all, self is a conventional name, you could put anything else (being coherent) in its stead.
It refers to the object itself, so when you are using it, you are declaring that .name and .age are properties of the Student objects (note, not of the Student class) you are going to create.
class Student:
#called each time you create a new Student instance
def __init__(self,name,age): #special method to initialize
self.name=name
self.age=age
def __str__(self): #special method called for example when you use print
return "Student %s is %s years old" %(self.name,self.age)
def call(self, msg): #silly example for custom method
return ("Hey, %s! "+msg) %self.name
#initializing two instances of the student class
bob=Student("Bob",20)
alice=Student("Alice",19)
#using them
print bob.name
print bob.age
print alice #this one only works if you define the __str__ method
print alice.call("Come here!") #notice you don't put a value for self
#you can modify attributes, like when alice ages
alice.age=20
print alice
In my case it was simply that I had a variable named the same as a function.
Example:
def cleanCache = functionReturningABoolean()
if( cleanCache ){
echo "Clean cache option is true, do not uninstall previous features / urls"
uninstallCmd = ""
// and we call the cleanCache method
cleanCache(userId, serverName)
}
...
and later in my code I have the function:
def cleanCache(user, server){
//some operations to the server
}
Apparently the Groovy language does not support this (but other languages like Java does).
I just renamed my function to executeCleanCache
and it works perfectly (or you can also rename your variable whatever option you prefer).
You can use bit.ly api to create facebook short urls find the documentation here http://api.bitly.com
You're missing a reference to System.Linq.
Add
using System.Linq
to get access to the ToList() function on the current code file.
To give a little bit of information over why this is necessary, Enumerable.ToList<TSource>
is an extension method. Extension methods are defined outside the original class that it targets. In this case, the extension method is defined on System.Linq
namespace.
In my case, I was missing the name of the Angular application in the html file. For example, I had included this file to be start of my application code. I had assumed it was being ran, but it wasn't.
app.module.js
(function () {
'use strict';
angular
.module('app', [
// Other dependencies here...
])
;
})();
However, when I declared the app in the html I had this:
index.html
<html lang="en" ng-app>
But to reference the Angular application by the name I used, I had to use:
index.html (Fixed)
<html lang="en" ng-app="app">
The above error is a linker error... the linker a program that takes one or more objects generated by a compiler and combines them into a single executable program.
You must add -lboost_system
to you linker flags which indicates to the linker that it must look for symbols like boost::system::system_category()
in the library libboost_system.so
.
If you have main.cpp, either:
g++ main.cpp -o main -lboost_system
OR
g++ -c -o main.o main.cpp
g++ main.o -lboost_system
Use Below code:
private void getCallDeatils() {
StringBuffer stringBuffer = new StringBuffer();
Cursor managedCursor = getActivity().managedQuery(CallLog.Calls.CONTENT_URI, null, null, null, null);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
stringBuffer.append("Call Deatils");
while (managedCursor.moveToNext()) {
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String reportDate = df.format(callDayTime);
String callDuration = managedCursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
stringBuffer.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- " + dir + " \nCall Date:--- " +callDate + " \nCall duration in sec :--- " + callDuration);
stringBuffer.append("\n----------------------------------");
logs.add(new LogClass(phNumber,dir,reportDate,callDuration));
}
rpm -qa openssl
yum clean all && yum update "openssl*"
lsof -n | grep ssl | grep DEL
cd /usr/src
wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz
tar -zxf openssl-1.0.1g.tar.gz
cd openssl-1.0.1g
./config --prefix=/usr --openssldir=/usr/local/openssl shared
./config
make
make test
make install
cd /usr/src
rm -rf openssl-1.0.1g.tar.gz
rm -rf openssl-1.0.1g
and
openssl version
For any CSS3-enabled browser you can use an adjacent sibling selector for styling your labels
input:checked + label {
color: white;
}
MDN's browser compatibility table says essentially all of the current, popular browsers (Chrome, IE, Firefox, Safari), on both desktop and mobile, are compatible.
Use HH
for 24 hour hours format:
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
Or the tt
format specifier for the AM/PM
part:
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt")
Take a look at the custom Date and Time format strings documentation.
Consider you've created a procedure like below.
CREATE OR REPLACE PROCEDURE GET_FULL_NAME like
(
FIRST_NAME IN VARCHAR2,
LAST_NAME IN VARCHAR2,
FULL_NAME OUT VARCHAR2
) IS
BEGIN
FULL_NAME:= FIRST_NAME || ' ' || LAST_NAME;
END GET_FULL_NAME;
In Oracle SQL Developer, you can run this procedure in two ways.
1. Using SQL Worksheet
Create a SQL Worksheet and write PL/SQL anonymous block like this and hit f5
DECLARE
FULL_NAME Varchar2(50);
BEGIN
GET_FULL_NAME('Foo', 'Bar', FULL_NAME);
Dbms_Output.Put_Line('Full name is: ' || FULL_NAME);
END;
2. Using GUI Controls
Expand Procedures
Right click on the procudure you've created and Click Run
In the pop-up window, Fill the parameters and Click OK.
Cheers!
Controller as version (recommended)
Here the template
<div ng-app="example" ng-controller="myController as $ctrl">
<input type="text" ng-model="$ctrl.searchText" />
<button ng-click="$ctrl.check()">Check!</button>
{{ $ctrl.searchText }}
</div>
The JS
angular.module('example', [])
.controller('myController', function() {
var vm = this;
vm.check = function () {
console.log(vm.searchText);
};
});
An example: http://codepen.io/Damax/pen/rjawoO
The best will be to use component with Angular 2.x or Angular 1.5 or upper
########Old way (NOT recommended)
This is NOT recommended because a string is a primitive, highly recommended to use an object instead
Try this in your markup
<input type="text" ng-model="searchText" />
<button ng-click="check(searchText)">Check!</button>
{{ searchText }}
and this in your controller
$scope.check = function (searchText) {
console.log(searchText);
}
Due to PermGen removal some options were removed (like -XX:MaxPermSize
), but options -Xms
and -Xmx
work in Java 8. It's possible that under Java 8 your application simply needs somewhat more memory. Try to increase -Xmx
value. Alternatively you can try to switch to G1 garbage collector using -XX:+UseG1GC
.
Note that if you use any option which was removed in Java 8, you will see a warning upon application start:
$ java -XX:MaxPermSize=128M -version
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=128M; support was removed in 8.0
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b18)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)
This works perfectly fine for me:
AdapterChart adapterChart = new AdapterChart(getContext(),messageList);
recyclerView.setAdapter(adapterChart);
recyclerView.scrollToPosition(recyclerView.getAdapter().getItemCount()-1);
sudo apt install libssl-dev
works on ubuntu 18.04.
defaultOrder contain a array where key is a column name and value is a SORT_DESC
or SORT_ASC
that's why below code not working.
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => ['defaultOrder'=>'topic_order asc']
]);
Correct Way
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'topic_order' => SORT_ASC,
]
],
]);
Note: If a query already specifies the orderBy clause, the new ordering instructions given by end users (through the sort configuration) will be appended to the existing orderBy clause. Any existing limit and offset clauses will be overwritten by the pagination request from end users (through the pagination configuration).
You can detail learn from Yii2 Guide of Data Provider
Sorting By passing Sort object in query
$sort = new Sort([
'attributes' => [
'age',
'name' => [
'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Name',
],
],
]);
$models = Article::find()
->where(['status' => 1])
->orderBy($sort->orders)
->all();
There is a statistics library if you are using python >= 3.4
https://docs.python.org/3/library/statistics.html
You may use it's mean method like this. Let's say you have a list of numbers of which you want to find mean:-
list = [11, 13, 12, 15, 17]
import statistics as s
s.mean(list)
It has other methods too like stdev, variance, mode, harmonic mean, median etc which are too useful.
An other solution rm(list=ls(pattern="temp"))
, remove all objects matching the pattern.
You need to use parentheses: myList.insert([1, 2, 3])
. When you leave out the parentheses, python thinks you are trying to access myList.insert
at position 1, 2, 3
, because that's what brackets are used for when they are right next to a variable.
To add an image to left, right, top or bottom, you can use attributes like this:
android:drawableLeft
android:drawableRight
android:drawableTop
android:drawableBottom
The sample code is given above. You can also achieve this using relative layout.
Yes; change your where to be:
where T:BaseFruit, new()
However, this only works with parameterless constructors. You'll have to have some other means of setting your property (setting the property itself or something similar).
this is one:
ls -l . | egrep -c '^-'
Note:
ls -1 | wc -l
Which means:
ls
: list files in dir
-1
: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too
|
: pipe output onto...
wc
: "wordcount"
-l
: count l
ines.
I faced similar issue while running the datanode. The following steps were useful.
Go to */hadoop_store/hdfs directory where you have created namenode and datanode as sub-directories. (The paths configured in [hadoop_directory]/etc/hadoop/hdfs-site.xml). Use
rm -r namenode
rm -r datanode
In */hadoop_store/hdfs directory use
sudo mkdir namenode
sudo mkdir datanode
In case of permission issue, use
chmod -R 755 namenode
chmod -R 755 datanode
In [hadoop_directory]/bin use
hadoop namenode -format (To format your namenode)
Search for LISTEN directive in the apache config files (httpd.conf, apache2.conf, listen.conf,...) and if you see localhost, or 127.0.0.1, then you need to overwrite with your public ip.
The git diff
command typically expects one or more commit hashes to generate your diff. You seem to be supplying the name of a remote.
If you had a branch named origin
, the commit hash at tip of the branch would have been used if you supplied origin
to the diff command, but currently (with no corresponding branch) the command will produce the error you're seeing. It may be the case that you were previously working with a branch named origin
.
An alternative, if you're trying to view the difference between your local branch, and a branch on a remote would be something along the lines of:
git diff origin/<branchname>
git diff <branchname> origin/<branchname>
Edit: Having read further, I realise I'm slightly wrong, git diff origin
is shorthand for diffing against the head of the specified remote, so git diff origin
= git diff origin/HEAD
(compare local git branch with remote branch?, Why is "origin/HEAD" shown when running "git branch -r"?)
It sounds like your origin does not have a HEAD, in my case this is because my remote is a bare repository that has never had a HEAD set.
Running git branch -r
will show you if origin/HEAD
is set, and if so, which branch it points at (e.g. origin/HEAD -> origin/<branchname>
).
Here is the answer with some explanation.
st = "Hey, you - what are you doing here!?"
# replace all the non alpha-numeric with space and then join.
new_string = ''.join([x.replace(x, ' ') if not x.isalnum() else x for x in st])
# output of new_string
'Hey you what are you doing here '
# str.split() will remove all the empty string if separator is not provided
new_list = new_string.split()
# output of new_list
['Hey', 'you', 'what', 'are', 'you', 'doing', 'here']
# we can join it to get a complete string without any non alpha-numeric character
' '.join(new_list)
# output
'Hey you what are you doing'
or in one line, we can do like this:
(''.join([x.replace(x, ' ') if not x.isalnum() else x for x in st])).split()
# output
['Hey', 'you', 'what', 'are', 'you', 'doing', 'here']
updated answer
Depends on your use case. There are applications where the runtime of a for loop needs to be constant (e.g. to satisfy some timing constraints, or to hide your data internals from timing based attacks).
In those cases it will even make sense to set a flag and only check the flag value AFTER all the for
loop iterations have actually run. Of course, all the for loop iterations need to run code that still takes about the same time.
If you do not care about the run time... use break;
and continue;
to make the code easier to read.
See the UIScreen Reference: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIScreen_Class/Reference/UIScreen.html
if([[UIScreen mainScreen] respondsToSelector:NSSelectorFromString(@"scale")])
{
if ([[UIScreen mainScreen] scale] < 1.1)
NSLog(@"Standard Resolution Device");
if ([[UIScreen mainScreen] scale] > 1.9)
NSLog(@"High Resolution Device");
}
I found a lot of answers, but probably the best solution for me is
.parent {
overflow: hidden;
}
.parent .floatLeft {
# your other styles
float: left;
margin-bottom: -99999px;
padding-bottom: 99999px;
}
You can check other solutions here http://css-tricks.com/fluid-width-equal-height-columns/
Use
$(document).on("click", "#btn_a", function(){
alert ('button clicked');
});
to add the listener for the dynamically created button.
alert($("#btn_a").val());
will give you the value of the button
It surprises me that this hasn't been mentioned yet, so for the sake of completeness...
You can perform list unpacking with the "splat operator": *
, which will also copy elements of your list.
old_list = [1, 2, 3]
new_list = [*old_list]
new_list.append(4)
old_list == [1, 2, 3]
new_list == [1, 2, 3, 4]
The obvious downside to this method is that it is only available in Python 3.5+.
Timing wise though, this appears to perform better than other common methods.
x = [random.random() for _ in range(1000)]
%timeit a = list(x)
%timeit a = x.copy()
%timeit a = x[:]
%timeit a = [*x]
#: 2.47 µs ± 38.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
#: 2.47 µs ± 54.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
#: 2.39 µs ± 58.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
#: 2.22 µs ± 43.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Twitter Bootstrap v3.0.3 has a class: center-block
Center content blocks
Set an element to display: block and center via margin. Available as a mixin and class.
Just need to add a class .center-block
in the img
tag, looks like this
<div class="container">
<div class="row">
<div class="span4"></div>
<div class="span4"><img class="center-block" src="logo.png" /></div>
<div class="span4"></div>
</div>
</div>
In Bootstrap already has css style call .center-block
.center-block {
display: block;
margin-left: auto;
margin-right: auto;
}
You can see a sample from here
I had this problem, but not via the Header. My placeholder was in the body. So I replaced all the <%=
with <%#
and did
protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();
}
and it worked.
just replace your code:
old code:
$("#dateSelect").datepicker({
showOtherMonths: true,
selectOtherMonths: true,
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'yy-mm-dd'
});
new code:
$("#dateSelect").datepicker({
showOtherMonths: true,
selectOtherMonths: true,
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'yy-mm-dd',
minDate: 0
});
(?!Andrea)
This is not exactly an inverted match, but it's the best you can directly do with regex. Not all platforms support them though.
Pure html is not able to do what you want. My suggestion would be to write a simple javascript function to do the roudning for you.
They are indeed fools. If you look at RFC 3986 Appendix A, you will see that "space" is simply not mentioned anywhere in the grammar for defining a URL. Since it's not mentioned anywhere in the grammar, the only way to encode a space is with percent-encoding (%20
).
In fact, the RFC even states that spaces are delimiters and should be ignored:
In some cases, extra whitespace (spaces, line-breaks, tabs, etc.) may have to be added to break a long URI across lines. The whitespace should be ignored when the URI is extracted.
and
For robustness, software that accepts user-typed URI should attempt to recognize and strip both delimiters and embedded whitespace.
Curiously, the use of +
as an encoding for space isn't mentioned in the RFC, although it is reserved as a sub-delimeter. I suspect that its use is either just convention or covered by a different RFC (possibly HTTP).
Verify your code with JSLint. It will usually find a ton of small errors, so the warning "JSLint may hurt your feelings" is pretty spot on. =)
You can use a third-party importer
to customise @import
semantics.
node-sass-import-once, which works with node-sass (for Node.js) can inline import CSS files.
Example of direct usage:
var sass = require('node-sass');,
importOnce = require('node-sass-import-once');
sass.render({
file: "input.scss",
importer: importOnce,
importOnce: {
css: true,
}
});
Example grunt-sass config:
var importOnce = require("node-sass-import-once");
grunt.loadNpmTasks("grunt-sass");
grunt.initConfig({
sass: {
options: {
sourceMap: true,
importer: importOnce
},
dev: {
files: {
"dist/style.css": "scss/**/*.scss"
}
}
});
Note that node-sass-import-once cannot currently import Sass partials without an explicit leading underscore. For example with the file partials/_partial.scss
:
@import partials/_partial.scss
succeeds@import * partials/partial.scss
failsIn general, be aware that a custom importer could change any import semantics. Read the docs before you start using it.
simply you can use jquery plugin to get/set the content of the div.
var divContent = $('#'DIV1).html(); $('#'DIV2).html(divContent );
for this you need to include jquery library.
I like the solution from realcrowd the best.
HTML:
<form role="form" id="form" name="form" autocomplete="off" novalidate rc-submit="signup()">
<div class="form-group" ng-class="{'has-error': rc.form.hasError(form.firstName)}">
<label for="firstName">Your First Name</label>
<input type="text" id="firstName" name="firstName" class="form-control input-sm" placeholder="First Name" ng-maxlength="40" required="required" ng-model="owner.name.first"/>
<div class="help-block" ng-show="rc.form.hasError(form.firstName)">{{rc.form.getErrMsg(form.firstName)}}</div>
</div>
</form>
javascript:
//define custom submit directive
var rcSubmitDirective = {
'rcSubmit': ['$parse', function ($parse) {
return {
restrict: 'A',
require: ['rcSubmit', '?form'],
controller: ['$scope', function ($scope) {
this.attempted = false;
var formController = null;
this.setAttempted = function() {
this.attempted = true;
};
this.setFormController = function(controller) {
formController = controller;
};
this.hasError = function (fieldModelController) {
if (!formController) return false;
if (fieldModelController) {
return fieldModelController.$invalid && this.attempted;
} else {
return formController && formController.$invalid && this.attempted;
}
};
this.getErrMsg=function(ctrl){
var e=ctrl.$error;
var errMsg;
if (e.required){
errMsg='Please enter a value';
}
return errMsg;
}
}],
compile: function(cElement, cAttributes, transclude) {
return {
pre: function(scope, formElement, attributes, controllers) {
var submitController = controllers[0];
var formController = (controllers.length > 1) ? controllers[1] : null;
submitController.setFormController(formController);
scope.rc = scope.rc || {};
scope.rc[attributes.name] = submitController;
},
post: function(scope, formElement, attributes, controllers) {
var submitController = controllers[0];
var formController = (controllers.length > 1) ? controllers[1] : null;
var fn = $parse(attributes.rcSubmit);
formElement.bind('submit', function (event) {
submitController.setAttempted();
if (!scope.$$phase) scope.$apply();
if (!formController.$valid) return false;
scope.$apply(function() {
fn(scope, {$event:event});
});
});
}
};
}
};
}]
};
app.directive(rcSubmitDirective);
The official csv
documentation recommends open
ing the file with newline=''
on all platforms to disable universal newlines translation:
with open('output.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
...
The CSV writer terminates each line with the lineterminator
of the dialect, which is \r\n
for the default excel
dialect on all platforms.
On Windows, always open your files in binary mode ("rb"
or "wb"
), before passing them to csv.reader
or csv.writer
.
Although the file is a text file, CSV is regarded a binary format by the libraries involved, with \r\n
separating records. If that separator is written in text mode, the Python runtime replaces the \n
with \r\n
, hence the \r\r\n
observed in the file.
See this previous answer.
On SQL Server? and on the same database server? Use three part naming.
INSERT INTO bar..tblFoobar( *fieldlist* )
SELECT *fieldlist* FROM foo..tblFoobar
This just moves the data. If you want to move the table definition (and other attributes such as permissions and indexes), you'll have to do something else.
//Make array
var array = ["1","2","3","4","5","6","7","8","9","10"]
//Loop
for(var i = 0; i < array.length; i++){
console.log((i+1) + " --> " + array[i])
}
For the ACTUAL number for i
, you need to change (i+1)
to i
or (i)
, if you want.
Hope this helped.
For me this code worked best:
private func getCoordinate(_ view: UIView) -> CGPoint {
var x = view.frame.origin.x
var y = view.frame.origin.y
var oldView = view
while let superView = oldView.superview {
x += superView.frame.origin.x
y += superView.frame.origin.y
if superView.next is UIViewController {
break //superView is the rootView of a UIViewController
}
oldView = superView
}
return CGPoint(x: x, y: y)
}
np.convolve
needs a flattened array as one of it's inputs, you can use numpy.ndarray.flatten()
which is quite fast, find it here.
First, we're talking about packaging a Node.js app for workshops, demos, etc. where it can be handy to have an app "just running" without the need for the end user to care about installation and dependencies.
You can try the following setup:
npm install
all dependencies (via package.json) to the local node_modules directory. It is important to perform this step on each platform you want to support separately, in case of binary dependencies.which node
.For Windows:
Create a self extracting archive, 7zip_extra supports a way to execute a command right after extraction, see: http://www.msfn.org/board/topic/39048-how-to-make-a-7-zip-switchless-installer/.
For OS X/Linux:
You can use tools like makeself or unzipsfx (I don't know if this is compiled with CHEAP_SFX_AUTORUN defined by default).
These tools will extract the archive to a temporary directory, execute the given command (e.g. node app.js
) and remove all files when finished.
Methods shown here are deprecated/outdated but this is still working.Require API 13
check it out
Display disp= getWindowManager().getDefaultDisplay();
Point dimensions = new Point();
disp.getSize(size);
int width = size.x;
int height = size.y;
SELECT a.table_name, a.column_name, a.constraint_name, c.owner,
-- referenced pk
c.r_owner, c_pk.table_name r_table_name, c_pk.constraint_name r_pk
FROM all_cons_columns a
JOIN all_constraints c ON a.owner = c.owner
AND a.constraint_name = c.constraint_name
JOIN all_constraints c_pk ON c.r_owner = c_pk.owner
AND c.r_constraint_name = c_pk.constraint_name
WHERE c.constraint_type = 'R'
AND a.table_name :=TABLE_NAME
AND c.owner :=OWNER_NAME;
I had a similar problem with height except my chart was inside a bootstrap modal popup, which I'm already controlling the size of with css. However, for some reason when the window was resized horizontally the height of the chart container would expand indefinitely. If you were to drag the window back and forth it would expand vertically indefinitely. I also don't like hard-coded height/width solutions.
So, if you're doing this in a modal, combine this solution with a window resize event.
// from link
$('#ChartModal').on('show.bs.modal', function() {
$('.chart-container').css('visibility', 'hidden');
});
$('#ChartModal').on('shown.bs.modal.', function() {
$('.chart-container').css('visibility', 'initial');
$('#chartbox').highcharts().reflow()
//added
ratio = $('.chart-container').width() / $('.chart-container').height();
});
Where "ratio" becomes a height/width aspect ratio, that will you resize when the bootstrap modal resizes. This measurement is only taken when he modal is opened. I'm storing ratio as a global but that's probably not best practice.
$(window).on('resize', function() {
//chart-container is only visible when the modal is visible.
if ( $('.chart-container').is(':visible') ) {
$('#chartbox').highcharts().setSize(
$('.chart-container').width(),
($('.chart-container').width() / ratio),
doAnimation = true );
}
});
So with this, you can drag your screen to the side (resizing it) and your chart will maintain its aspect ratio.
Widescreen
vs smaller
(still fiddling around with vw units, so everything in the back is too small to read lol!)
Use java.util.concurrent.TimeUnit, and use this simple method:
private static long timeDiff(Date date, Date date2, TimeUnit unit) {
long milliDiff=date2.getTime()-date.getTime();
long unitDiff = unit.convert(milliDiff, TimeUnit.MILLISECONDS);
return unitDiff;
}
For example:
SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
Date firstDate = sdf.parse("06/24/2017 04:30:00");
Date secondDate = sdf.parse("07/24/2017 05:00:15");
Date thirdDate = sdf.parse("06/24/2017 06:00:15");
System.out.println("days difference: "+timeDiff(firstDate,secondDate,TimeUnit.DAYS));
System.out.println("hours difference: "+timeDiff(firstDate,thirdDate,TimeUnit.HOURS));
System.out.println("minutes difference: "+timeDiff(firstDate,thirdDate,TimeUnit.MINUTES));
System.out.println("seconds difference: "+timeDiff(firstDate,thirdDate,TimeUnit.SECONDS));
I found it after looking through the documentation again. What I was looking for were the __filename
and __dirname
module-level variables.
__filename
is the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/kyle/some/dir/file.js
)__dirname
is the directory name of the current module. (ex:/home/kyle/some/dir
)The best way to align a div in center both horizontally and vertically will be
HTML
<div></div>
CSS:
div {
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 100px;
height: 100px;
background-color: blue;
}
The intended use for App_Data is to store database related file. Usually SQL Server Express .mdf files.
If you want any java
process, not just ant or Tomcat, to pick up options like -Xmx
use the environment variable _JAVA_OPTIONS
.
In bash: export _JAVA_OPTIONS="-Xmx1g"
The text 'dasda' will never not be within a tag, right? Semantically and to be valid HTML it as to be, just add the clear class to that:
The result integer value is out of the range which an integer data type can hold.
Try using Int64
To make life easier when entering multiple dates/times it is possible to use a custom format to remove the need to enter the colon, and the leading "hour" 0. This however requires a second field for the numerical date to be stored, as the displayed date from the custom format is in base 10.
Displaying a number as a time (no need to enter colons, but no time conversion)
For displaying the times on the sheet, and for entering them without having to type the colon set the cell format to custom and use:
0/:00
Then enter your time. For example, if you wanted to enter 62:30, then you would simply type 6230 and your custom format would visually insert a colon 2 decimal points from the right.
If you only need to display the times, stop here.
Converting number to time
If you need to be able to calculate with the times, you will need to convert them from base 10 into the time format.
This can be done with the following formula (change A2
to the relevant cell reference):
=TIME(0,TRUNC(A2/100),MOD(A2,100))
=TIME
starts the number to time conversion0,
at the beginning of the formula, as the format is always hh,mm,ss
(to display hours and minutes instead of minutes and seconds, place the 0 at the end of the formula).TRUNC(A2/100),
discards the rightmost 2 digits.MOD(A2,100)
keeps the rightmost 2 digits and discards everything to the left.The above formula was found and adapted from this article: PC Mag.com - Easy Date and Time Entry in Excel
Alternatively, you could skip the 0/:00
custom formatting, and just enter your time in a cell to be referenced of the edge of the visible workspace or on another sheet as you would for the custom formatting (ie: 6230 for 62:30)
Then change the display format of the cells with the formula to [m]:ss
as @Sean Chessire suggested.
Here is a screen shot to show what I mean.
select *
from emp
where rownum <= &upperlimit
minus
select *
from emp
where rownum <= &lower limit ;
SELECT CASE CHARINDEX(' ', @Foo, 1)
WHEN 0 THEN @Foo -- empty or single word
ELSE SUBSTRING(@Foo, 1, CHARINDEX(' ', @Foo, 1) - 1) -- multi-word
END
You could perhaps use this in a UDF:
CREATE FUNCTION [dbo].[FirstWord] (@value varchar(max))
RETURNS varchar(max)
AS
BEGIN
RETURN CASE CHARINDEX(' ', @value, 1)
WHEN 0 THEN @value
ELSE SUBSTRING(@value, 1, CHARINDEX(' ', @value, 1) - 1) END
END
GO -- test:
SELECT dbo.FirstWord(NULL)
SELECT dbo.FirstWord('')
SELECT dbo.FirstWord('abc')
SELECT dbo.FirstWord('abc def')
SELECT dbo.FirstWord('abc def ghi')
<html>
<head></head>
<body>
<script>
var a = document.createElement('a');
var linkText = document.createTextNode("my title text");
a.appendChild(linkText);
a.title = "my title text";
a.href = "http://example.com";
document.body.appendChild(a);
</script>
</body>
</html>
Does the column allow null?
Seems to work. Just tested with phpMyAdmin, the column is of type int that allows nulls:
INSERT INTO `database`.`table` (`column`) VALUES (NULL);
<body onload="window.print()">
or
window.onload = function() { window.print(); }
$("#myDiv").hide();
will set the css display to none. if you need to set visibility to hidden as well, could do this via
$("#myDiv").css("visibility", "hidden");
or combine both in a chain
$("#myDiv").hide().css("visibility", "hidden");
or write everything with one css() function
$("#myDiv").css({
display: "none",
visibility: "hidden"
});
as outerHTML is IE only, use this function:
function getOuterHtml(node) {
var parent = node.parentNode;
var element = document.createElement(parent.tagName);
element.appendChild(node);
var html = element.innerHTML;
parent.appendChild(node);
return html;
}
creates a bogus empty element of the type parent and uses innerHTML on it and then reattaches the element back into the normal dom
Click
is an event that fires immediately after you release the mouse button. So if you want to check in the handler for button2.Click
if button1
was clicked before, all you could do is have a handler for button1.Click
which sets a bool flag of your own making to true.
private bool button1WasClicked = false;
private void button1_Click(object sender, EventArgs e)
{
button1WasClicked = true;
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox2.Text == textBox3.Text && button1WasClicked)
{
StreamWriter myWriter = File.CreateText(@"c:\Program Files\text.txt");
myWriter.WriteLine(textBox1.Text);
myWriter.WriteLine(textBox2.Text);
button1WasClicked = false;
}
}
The accepted answer is correct. However, I needed a little bit more clarity, so in case someone else does too:
Leaflet allows events to fire on virtually anything you do on its map, in this case a marker.
So you could create a marker as suggested by the question above:
L.marker([10.496093,-66.881935]).addTo(map).on('mouseover', onClick);
Then create the onClick function:
function onClick(e) {
alert(this.getLatLng());
}
Now anytime you mouseover that marker it will fire an alert of the current lat/long.
However, you could use 'click', 'dblclick', etc. instead of 'mouseover' and instead of alerting lat/long you can use the body of onClick to do anything else you want:
L.marker([10.496093,-66.881935]).addTo(map).on('click', function(e) {
console.log(e.latlng);
});
Here is the documentation: http://leafletjs.com/reference.html#events
DECLARE @dd VARCHAR(200) = 'Net Operating Loss - 2007';
SELECT SUBSTRING(@dd, 1, CHARINDEX('-', @dd) -1) F1,
SUBSTRING(@dd, CHARINDEX('-', @dd) +1, LEN(@dd)) F2
In random.random() the output lies between 0 & 1 , and it takes no input parameters
Whereas random.uniform() takes parameters , wherein you can submit the range of the random number.
e.g.
import random as ra
print ra.random()
print ra.uniform(5,10)
OUTPUT:-
0.672485369423
7.9237539416
Make sure you url encode all of the query params in your url.
In my case there was a space ' ' in my url, and I was making an API call using curl, and my api server was giving this error.
Means the following url
http://somedomain.com?key=some value with space
should be
http://somedomain.com/?key=some%20value%20with%20space
I think the previous answers are correct, but here is another example (just a f.y.i, success() and error() are deprecated according to AngularJS Main page:
$http
.get('http://someendpoint/maybe/returns/JSON')
.then(function(response) {
return response.data;
}).catch(function(e) {
console.log('Error: ', e);
throw e;
}).finally(function() {
console.log('This finally block');
});
The answer of Uttam didnt work for me. I just got null when I do:
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);
In my case, bitmapdata only has the buffer of the pixels, so it is imposible for the function decodeByteArray to guess which the width, the height and the color bits use. So I tried this and it worked:
//Create bitmap with width, height, and 4 bytes color (RGBA)
Bitmap bmp = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
ByteBuffer buffer = ByteBuffer.wrap(bitmapdata);
bmp.copyPixelsFromBuffer(buffer);
Check https://developer.android.com/reference/android/graphics/Bitmap.Config.html for different color options
If you are talking about tag stripping, it is relatively straight forward if you don't have to worry about things like <script>
tags. If all you need to do is display the text without the tags you can accomplish that with a regular expression:
<[^>]*>
If you do have to worry about <script>
tags and the like then you'll need something a bit more powerful then regular expressions because you need to track state, omething more like a Context Free Grammar (CFG). Althought you might be able to accomplish it with 'Left To Right' or non-greedy matching.
If you can use regular expressions there are many web pages out there with good info:
If you need the more complex behaviour of a CFG I would suggest using a third party tool, unfortunately I don't know of a good one to recommend.
Which version of IIS is your host running? One thing to try is to put a dummy default.aspx file in the root folder (this will not be used when MVC is working, but can get rid of this problem).
Either I don't understand your question, or Enumerable#find is the thing you were looking for.
Simple way is to reset the index of the DataFrame prior to filtering:
df_reset = df.reset_index()
df_reset[df_reset['BoolCol']].index.tolist()
Bit hacky, but it's quick!
We can use IF condition in SELECT query as below:
Suppose that for anything with "ABC","ABC1","ABC2","ABC3",..., we want to replace with "ABC" then using REGEXP and IF() condition in the SELECT query, we can achieve this.
Syntax:
SELECT IF(column_name REGEXP 'ABC[0-9]$','ABC',column_name)
FROM table1
WHERE column_name LIKE 'ABC%';
Example:
SELECT IF('ABC1' REGEXP 'ABC[0-9]$','ABC','ABC1');
Using the sh module (pip install sh):
from sh import tail
# runs forever
for line in tail("-f", "/var/log/some_log_file.log", _iter=True):
print(line)
[update]
Since sh.tail with _iter
=True is a generator, you can:
import sh
tail = sh.tail("-f", "/var/log/some_log_file.log", _iter=True)
Then you can "getNewData" with:
new_data = tail.next()
Note that if the tail buffer is empty, it will block until there is more data (from your question it is not clear what you want to do in this case).
[update]
This works if you replace -f with -F, but in Python it would be locking. I'd be more interested in having a function I could call to get new data when I want it, if that's possible. – Eli
A container generator placing the tail call inside a while True loop and catching eventual I/O exceptions will have almost the same effect of -F.
def tail_F(some_file):
while True:
try:
for line in sh.tail("-f", some_file, _iter=True):
yield line
except sh.ErrorReturnCode_1:
yield None
If the file becomes inaccessible, the generator will return None. However it still blocks until there is new data if the file is accessible. It remains unclear for me what you want to do in this case.
Raymond Hettinger approach seems pretty good:
def tail_F(some_file):
first_call = True
while True:
try:
with open(some_file) as input:
if first_call:
input.seek(0, 2)
first_call = False
latest_data = input.read()
while True:
if '\n' not in latest_data:
latest_data += input.read()
if '\n' not in latest_data:
yield ''
if not os.path.isfile(some_file):
break
continue
latest_lines = latest_data.split('\n')
if latest_data[-1] != '\n':
latest_data = latest_lines[-1]
else:
latest_data = input.read()
for line in latest_lines[:-1]:
yield line + '\n'
except IOError:
yield ''
This generator will return '' if the file becomes inaccessible or if there is no new data.
[update]
The second to last answer circles around to the top of the file it seems whenever it runs out of data. – Eli
I think the second will output the last ten lines whenever the tail process ends, which with -f
is whenever there is an I/O error. The tail --follow --retry
behavior is not far from this for most cases I can think of in unix-like environments.
Perhaps if you update your question to explain what is your real goal (the reason why you want to mimic tail --retry), you will get a better answer.
The last answer does not actually follow the tail and merely reads what's available at run time. – Eli
Of course, tail will display the last 10 lines by default... You can position the file pointer at the end of the file using file.seek, I will left a proper implementation as an exercise to the reader.
IMHO the file.read() approach is far more elegant than a subprocess based solution.
Another approach is using regex , as show below , you can use the empty regex pattern and achieve the same using ng-pattern
HTML :
<body ng-app="app" ng-controller="formController">
<form name="myform">
<input name="myfield" ng-model="somefield" ng-minlength="5" ng-pattern="mypattern" required>
<span ng-show="myform.myfield.$error.pattern">Please enter!</span>
<span ng-show="!myform.myfield.$error.pattern">great!</span>
</form>
Controller:@formController :
var App = angular.module('app', []);
App.controller('formController', function ($scope) {
$scope.mypattern = /^\s*$/g;
});
on archlinux I faced this error and the problem was that the mysqld
-service wasn't running.
However I couldn't enable the mysql-service with systemctl start mysqld
as instructed in the Archlinux documentation. I think the error was something like
mysqld.service not found
I first needed to restart the system.
Then I entered the command again (and entered systemctl enable mysqld
) and now mysql
was able to find the created mysql.sock
.
MediaWiki's API is running on Wikipedia (docs). You can also use the Special:Export feature to dump data and parse it yourself.
I had this problem. Solution for me was to remove links to Vue.js files. Vue.js and JQuery have some conflicts in datepicker and datetimepicker functions.
You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.
new BigInteger(bytes).intValue();
or to denote polarity:
new BigInteger(1, bytes).intValue();
@last_run_time
is a 9.4. User-Defined Variables and last_run_time datetime
one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.
Try: SELECT last_run_time;
UPDATE
Example:
/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$
CREATE PROCEDURE `sp_test`()
BEGIN
DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
DECLARE last_run_time DATETIME DEFAULT NULL;
DECLARE current_run_time DATETIME DEFAULT NOW();
-- Define the last run time
SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);
-- if there is no last run time found then use yesterday as starting point
IF(last_run_time IS NULL) THEN
SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
END IF;
SELECT last_run_time;
-- Insert variables in table2
INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$
DELIMITER ;
Assuming your cursor sits at the beginning of the block:
V/^$<CR>d (where <CR> is the enter/return key)
V
/^$<CR>
d
A more robust solution:
:set nowrapscan
:nnoremap D V/^\s*$\\|\%$<CR>d
:set nowrapscan
D
key (to the following commands): :nnoremap D
V
/^\s*$\\|\%$<CR>
d
A good practice would be based on readability, e.g.:
string str ("Test string");
for (int index = 0, auto it = str.begin(); it < str.end(); ++it)
cout << index++ << *it;
Or:
string str ("Test string");
for (int index = 0, auto it = str.begin(); it < str.end(); ++it, ++index)
cout << index << *it;
Or your original:
string str ("Test string");
int index = 0;
for (auto it = str.begin() ; it < str.end(); ++it, ++index)
cout << index << *it;
Etc. Whatever is easiest and cleanest to you.
It's not clear there is any one best practice as you'll need a counter variable somewhere. The question seems to be whether where you define it and how it is incremented works well for you.
Use a version GET
variable to prevent browser caching.
Appending ?v=AUTO_INCREMENT_VERSION
to the end of your url prevents browser caching - avoiding any and all cached scripts.
Another interesting variant question can be:
How would you make "12345"
as "12 23 34 45"
without using another string?
Will following do?
for(int i=0; i < a.size()-1; ++i)
{
//b = a.substr(i, 2);
c = atoi((a.substr(i, 2)).c_str());
cout << c << " ";
}
select directory_path from dba_directories where upper(directory_name) = 'CSVDIR'
You can simplify to:
WHERE a.Country = COALESCE(NULLIF(@Country,0), a.Country);
You need to change the loop from for ($i=1; $i<count($files); $i++)
to for ($i=0; $i<count($files); $i++)
:
So the correct code is
<?php
$files = glob("images/*.*");
for ($i=0; $i<count($files); $i++) {
$image = $files[$i];
print $image ."<br />";
echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
}
?>
Just create a single view Model with all the needed information in it, normaly what I do is create a model for every view so I can be specific on every view, either that or make a parent model and inherit it. OR make a model which includes both the views.
Personally I would just add them into one model but thats the way I do it:
public class xViewModel
{
public int PersonID { get; set; }
public string PersonName { get; set; }
public int OrderID { get; set; }
public int TotalSum { get; set; }
}
@model project.Models.Home.xViewModel
@using(Html.BeginForm())
{
@Html.EditorFor(x => x.PersonID)
@Html.EditorFor(x => x.PersonName)
@Html.EditorFor(x => x.OrderID)
@Html.EditorFor(x => x.TotalSum)
}
Maybe because you may need to create Db Resource and Pool manually on the Glassfish server like this,
In Netbeans -> Projects, Open Server Resources -> glassfish-resources.xml We have to create JDBC Resource and JDBC Connection Pool Manually on Glassfish. I am using my values here, don't use them, see your .xml !
Value of jndi-name is your JDBC Resource and Value of pool-name is your JDBC Connection Pool.
Open Browser for Glassfish Admin, https://localhost:4848/
Go to, JDBC Connection Pool -> New: 1) Pool Name: mysql_customersdb_rootPool 2) Resource Type: javax.sql.ConnectionPoolDataSource 3) Database Driver Vendor: MySql
Press Next,
URL: jdbc:mysql://localhost:3306/customersdb?zeroDateTimeBehavior=convertToNull Url: jdbc:mysql://localhost:3306/customersdb?zeroDateTimeBehavior=convertToNull User: root Password: root
JDBC Resources -> New
JNDI Name: CustomersDS Pool Name: mysql_customersdb_rootPool
Press Ok.
Right Click your Project and Press Run :)
Just a quick addition to Ahmad's answer. You can't use getSupportActionBar().setTitle anymore when using a custom view with a TextView. So to set the title when you have multiple Activities with this custom ActionBar (using this one xml), in your onCreate() method after you assign a custom view:
TextView textViewTitle = (TextView) findViewById(R.id.mytext);
textViewTitle.setText(R.string.title_for_this_activity);
In the AndroidManifest.xml, under the application tag, you can set the theme of your choice. To customize the theme, press Ctrl + Click
on android:theme = "@style/AppTheme"
in the Android manifest file. It will open styles.xml
file where you can change the parent attribute of the style tag.
At parent=
in styles.xml
you can browse all available styles by using auto-complete inside the ""
. E.g. try parent="Theme."
with your cursor right after the .
and then pressing Ctrl + Space
.
You can also preview themes in the preview window in Android Studio.
try this :
SET @StartDate = DATE_SUB(DATE(NOW()),INTERVAL (DAY(NOW())-1) DAY);
SET @EndDate = ADDDATE(CURDATE(),1);
select * from table where (date >= @StartDate and date < @EndDate);
What you are asking is pretty straight forward
execute query against your db to get resultset or use API to get the resultset
loop through the resultset or simply the result using php
In each iteration simply format the output as an element
the following refernce should help
Getting Datafrom MySQL database
hope this helps :)
React Router V5
If you want the pathName as a string ('/' or 'users'), you can use the following:
// React Hooks: React Router DOM
let history = useHistory();
const location = useLocation();
const pathName = location.pathname;
It's built in Eclipse since ages. Which Eclipse version are you using? How were you trying to create a new JUnit test case? It should be File > New > Other > Java - JUnit - JUnit Test Case (you can eventually enter Filter text "junit").
As Charles Duffey has stated, XML parsers are best parsed with a proper XML parsing tools. For one time job the following should work.
grep -oPm1 "(?<=<title>)[^<]+"
$ echo "$data"
<item>
<title>15:54:57 - George:</title>
<description>Diane DeConn? You saw Diane DeConn!</description>
</item>
<item>
<title>15:55:17 - Jerry:</title>
<description>Something huh?</description>
$ title=$(grep -oPm1 "(?<=<title>)[^<]+" <<< "$data")
$ echo "$title"
15:54:57 - George:
I've found that there are some files that may affect the $PATH
variable in macOS (works for me, 10.11 El Capitan), listed below:
As the top voted answer said, vi /etc/paths
, which is recommended from my point of view.
Also don't forget the /etc/paths.d
directory, which contains files may affect the $PATH
variable, set the git
and mono-command
path in my case. You can ls -l /etc/paths.d
to list items and rm /etc/paths.d/path_you_dislike
to remove items.
If you're using a "bash" environment (the default Terminal.app
, for example), you should check out ~/.bash_profile
or ~/.bashrc
. There may be not that file yet, but these two files have effects on the $PATH
.
If you're using a "zsh" environment (Oh-My-Zsh, for example), you should check out ~./zshrc
instead of ~/.bash*
thing.
And don't forget to restart all the terminal windows, then echo $PATH
. The $PATH
string will be PATH_SET_IN_3&4:PATH_SET_IN_1:PATH_SET_IN_2
.
Noticed that the first two ways (/etc/paths
and /etc/path.d
) is in /
directory which will affect all the accounts in your computer while the last two ways (~/.bash*
or ~/.zsh*
) is in ~/
directory (aka, /Users/yourusername/
) which will only affect your account settings.
Same solution as zGnep but using xml:
android:background="@null"
@ThoAppelsin in his comment to question posted is right. The code snippet posted in the question it is valid and with no errors. The error you have must be because other bad syntax in any other place of your c source file. enum{a,b,c};
defines three symbolic constants (a
, b
and c
) which are integers with values 0
,1
and 2
respectively, but when we use enum
it is because we don't usually care about the specific integer value, we care more about the meaning of the symbolic constant name.
This means you can have this:
#include <stdio.h>
enum {a,b,c};
int main(){
printf("%d\n",b);
return 0;
}
and this will output 1
.
This also will be valid:
#include <stdio.h>
enum {a,b,c};
int bb=b;
int main(){
printf("%d\n",bb);
return 0;
}
and will output the same as before.
If you do this:
enum {a,b,c};
enum {a,b,c};
you will have an error, but if you do this:
enum alfa{a,b,c};
enum alfa;
you will not have any error.
you can do this:
enum {a,b,c};
int aa=a;
and aa
will be an integer variable with value 0
. but you can also do this:
enum {a,b,c} aa= a;
and will have the same effect (that is, aa
being an int
with 0
value).
you can also do this:
enum {a,b,c} aa= a;
aa= 7;
and aa
will be int
with value 7
.
because you cannot repeat symbolic constant definition with the use of enum
, as i have said previously, you must use tags if you want to declare int
vars with the use of enum
:
enum tag1 {a,b,c};
enum tag1 var1= a;
enum tag1 var2= b;
the use of typedef
it is to safe you from writing each time enum tag1
to define variable. With typedef
you can just type Tag1
:
typedef enum {a,b,c} Tag1;
Tag1 var1= a;
Tag1 var2= b;
You can also have:
typedef enum tag1{a,b,c}Tag1;
Tag1 var1= a;
enum tag1 var2= b;
Last thing to say it is that since we are talking about defined symbolic constants it is better to use capitalized letters when using enum
, that is for example:
enum {A,B,C};
instead of
enum {a,b,c};
I'm guessing that when you enter a value into the totals field that value expression somehow gets overwritten.
However, you can take an alternative approach: Create a field for the total value and when either one
or two
changes update that field.
<li>Total <input type="text" ng-model="total">{{total}}</li>
And change the javascript:
function TodoCtrl($scope) {
$scope.$watch('one * two', function (value) {
$scope.total = value;
});
}
Example fiddle here.
Have you checked MZTools?? It does a lot of cool stuff...
If I'm not wrong, one of the functionalities it offers is to set your own shortcuts.