You can install pywin32 wheel packages from PYPI with PIP by pointing to this package: https://pypi.python.org/pypi/pypiwin32 No need to worry about first downloading the package, just use pip:
pip install pypiwin32
Currently I think this is "the easiest" way to get in working :) Hope this helps.
related @4Oh4 solution a smooth change for a list of files to watch;
import os
import sys
import time
class Watcher(object):
running = True
refresh_delay_secs = 1
# Constructor
def __init__(self, watch_files, call_func_on_change=None, *args, **kwargs):
self._cached_stamp = 0
self._cached_stamp_files = {}
self.filenames = watch_files
self.call_func_on_change = call_func_on_change
self.args = args
self.kwargs = kwargs
# Look for changes
def look(self):
for file in self.filenames:
stamp = os.stat(file).st_mtime
if not file in self._cached_stamp_files:
self._cached_stamp_files[file] = 0
if stamp != self._cached_stamp_files[file]:
self._cached_stamp_files[file] = stamp
# File has changed, so do something...
file_to_read = open(file, 'r')
value = file_to_read.read()
print("value from file", value)
file_to_read.seek(0)
if self.call_func_on_change is not None:
self.call_func_on_change(*self.args, **self.kwargs)
# Keep watching in a loop
def watch(self):
while self.running:
try:
# Look for changes
time.sleep(self.refresh_delay_secs)
self.look()
except KeyboardInterrupt:
print('\nDone')
break
except FileNotFoundError:
# Action on file not found
pass
except Exception as e:
print(e)
print('Unhandled error: %s' % sys.exc_info()[0])
# Call this function each time a change happens
def custom_action(text):
print(text)
# pass
watch_files = ['/Users/mexekanez/my_file.txt', '/Users/mexekanez/my_file1.txt']
# watcher = Watcher(watch_file) # simple
if __name__ == "__main__":
watcher = Watcher(watch_files, custom_action, text='yes, changed') # also call custom action function
watcher.watch() # start the watch going
int max = items.Max(i => i.ID);
var item = items.First(x => x.ID == max);
This assumes there are elements in the items collection of course.
git show <revhash>
Documentation here. Or if that doesn't work, try Google Code's GIT Documentation
Get your scrolling feature easily. It also supports Animated/Smooth scrolling as an additional feature. Details for Angular Scroll library:
Github - https://github.com/oblador/angular-scroll
Bower: bower install --save angular-scroll
npm : npm install --save angular-scroll
Minfied version - only 9kb
Smooth Scrolling (animated scrolling) - yes
Scroll Spy - yes
Documentation - excellent
Demo - http://oblador.github.io/angular-scroll/
Hope this helps.
Four easy steps
./adb kill-server
./adb start-server
replug the device, unlock it and accept the new key
Please check the access to drives.First create one folder and go to folder properties ,
You may find the security tab ,click on that check whether your user id having the access or not.
if couldn't find the your id,please click the add buttion and give user name with full access.
int index = dt.Rows.IndexOf(row);
But you're probably better off using a for loop instead of foreach.
You need to merge the remote branch into your current branch by running git pull
.
If your local branch is already up-to-date, you may also need to run git pull --rebase
.
A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.
You can simplify this code to:
DirectorySearcher searcher = new DirectorySearcher();
searcher.Filter = "(&(objectCategory=user)(cn=steve.evans))";
SearchResultCollection results = searcher.FindAll();
if (results.Count == 1)
{
//do what you want to do
}
else if (results.Count == 0)
{
//user does not exist
}
else
{
//found more than one user
//something is wrong
}
If you can narrow down where the user is you can set searcher.SearchRoot to a specific OU that you know the user is under.
You should also use objectCategory instead of objectClass since objectCategory is indexed by default.
You should also consider searching on an attribute other than CN. For example it might make more sense to search on the username (sAMAccountName) since it's guaranteed to be unique.
with 'exists?':
Business.exists? user_id: current_user.id #=> 1 or nil
with 'any?':
Business.where(:user_id => current_user.id).any? #=> true or false
If you use something with .where, be sure to avoid trouble with scopes and better use .unscoped
Business.unscoped.where(:user_id => current_user.id).any?
The accepted answer work when you have a single line string(the email) but if you have a
multiline string, the error will remain.
Please look into this matter:
<!-- start: definition-->
@{
dynamic item = new System.Dynamic.ExpandoObject();
item.MultiLineString = @"a multi-line
string";
item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
function Getinfo(text) {
alert(text);
}
</script>
Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:
<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>
We experienced this on a HostGator account (who place inode limits on all their hosting) following a spam attack. It left vast numbers of queue records in /root/.cpanel/comet. If this happens and you find you have no free inodes, you can run this cpanel utility through shell:
/usr/local/cpanel/bin/purge_dead_comet_files
Console.OutputEncoding Property
https://docs.microsoft.com/en-us/dotnet/api/system.console.outputencoding
Note that successfully displaying Unicode characters to the console requires the following:
- The console must use a TrueType font, such as Lucida Console or Consolas, to display characters.
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
In my case, I needed to allow many inactives and only one combination of two keys active, like this:
UUL_USR_IDF UUL_UND_IDF UUL_ATUAL
137 18 0
137 19 0
137 20 1
137 21 0
This seems to work:
CREATE UNIQUE NONCLUSTERED INDEX UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL
ON USER_UND(UUL_USR_IDF, UUL_ATUAL)
WHERE UUL_ATUAL = 1;
Here are my test cases:
SELECT * FROM USER_UND WHERE UUL_USR_IDF = 137
insert into USER_UND values (137, 22, 1) --I CAN NOT => Cannot insert duplicate key row in object 'dbo.USER_UND' with unique index 'UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL'. The duplicate key value is (137, 1).
insert into USER_UND values (137, 23, 0) --I CAN
insert into USER_UND values (137, 24, 0) --I CAN
DELETE FROM USER_UND WHERE UUL_USR_ID = 137
insert into USER_UND values (137, 22, 1) --I CAN
insert into USER_UND values (137, 27, 1) --I CAN NOT => Cannot insert duplicate key row in object 'dbo.USER_UND' with unique index 'UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL'. The duplicate key value is (137, 1).
insert into USER_UND values (137, 28, 0) --I CAN
insert into USER_UND values (137, 29, 0) --I CAN
Ok, I think I have a pretty cool solution.
Let's say you have file a
and file b
.
You have a def
or a class
in file b
that you want to use in module a
, but you have something else, either a def
, class
, or variable from file a
that you need in your definition or class in file b
.
What you can do is, at the bottom of file a
, after calling the function or class in file a
that is needed in file b
, but before calling the function or class from file b
that you need for file a
, say import b
Then, and here is the key part, in all of the definitions or classes in file b
that need the def
or class
from file a
(let's call it CLASS
), you say from a import CLASS
This works because you can import file b
without Python executing any of the import statements in file b
, and thus you elude any circular imports.
For example:
class A(object):
def __init__(self, name):
self.name = name
CLASS = A("me")
import b
go = B(6)
go.dostuff
class B(object):
def __init__(self, number):
self.number = number
def dostuff(self):
from a import CLASS
print "Hello " + CLASS.name + ", " + str(number) + " is an interesting number."
Voila.
http://llvm.org/docs/FAQ.html#translatecxx
It handles some code, but will fail for more complex implementations as it hasn't been fully updated for some of the modern C++ conventions. So try compiling your code frequently until you get a feel for what's allowed.
Usage sytax from the command line is as follows for version 9.0.1:
clang -c CPPtoC.cpp -o CPPtoC.bc -emit-llvm
clang -march=c CPPtoC.bc -o CPPtoC.c
For older versions (unsure of transition version), use the following syntax:
llvm-g++ -c CPPtoC.cpp -o CPPtoC.bc -emit-llvm
llc -march=c CPPtoC.bc -o CPPtoC.c
Note that it creates a GNU flavor of C and not true ANSI C. You will want to test that this is useful for you before you invest too heavily in your code. For example, some embedded systems only accept ANSI C.
Also note that it generates functional but fairly unreadable code. I recommend commenting and maintain your C++ code and not worrying about the final C code.
EDIT : although official support of this functionality was removed, but users can still use this unofficial support from Julia language devs, to achieve mentioned above functionality.
Since 2.0 beta :)
import { APP_BASE_HREF } from 'angular2/platform/common';
I have a feeling that your ClientID
is not of a string type (zero-terminated char*
or std::string
) but some integral type (e.g. int
) so you need to convert number to the string first:
std::stringstream ss;
ss << ClientID;
query.append(ss.str());
But you can use operator+
as well (instead of append
):
query += ss.str();
Install as npm install font-awesome --save-dev
In your development less file, you can either import the whole font awesome less using @import "node_modules/font-awesome/less/font-awesome.less"
, or look in that file and import just the components that you need. I think this is the minimum for basic icons:
/* adjust path as needed */
@fa_path: "../node_modules/font-awesome/less";
@import "@{fa_path}/variables.less";
@import "@{fa_path}/mixins.less";
@import "@{fa_path}/path.less";
@import "@{fa_path}/core.less";
@import "@{fa_path}/icons.less";
As a note, you still aren't going to save that many bytes by doing this. Either way, you're going to end up including between 2-3k lines of unminified CSS.
You'll also need to serve the fonts themselves from a folder called/fonts/
in your public directory. You could just copy them there with a simple gulp task, for example:
gulp.task('fonts', function() {
return gulp.src('node_modules/font-awesome/fonts/*')
.pipe(gulp.dest('public/fonts'))
})
Following @Erfan's good answer, most of the times in an analysis of aggregate values you want the unique possible combinations of these existing character values:
unique_chars = lambda x: ', '.join(x.unique())
(df
.groupby(['A'])
.agg({'C': unique_chars}))
Swift 4:
// attribute with color red and Bold
var attrs1 = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedStringKey.foregroundColor: UIColor.red]
// attribute with color black and Non Bold
var attrs2 = [NSAttributedStringKey.font: UIFont(name: "Roboto-Regular", size: 20), NSAttributedStringKey.foregroundColor: UIColor.black]
var color1 = NSAttributedString(string: "RED", attributes: attrs1)
var color2 = NSAttributedString(string: " BLACK", attributes: attrs2)
var string = NSMutableAttributedString()
string.append(color1)
string.append(color2)
// print the text with **RED** BLACK
print("Final String : \(string)")
The second step of mongo installation is
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list
Instead of this command do it manually
cd /etc/apt/
nano sources.list
deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse
And save the file,
Continue all process as in installation docs
It works for me:
You may use java.util.Date
class and then use SimpleDateFormat
to format the Date
.
Date date=new Date(millis);
We can use java.time package (tutorial) - DateTime APIs introduced in the Java SE 8.
var instance = java.time.Instant.ofEpochMilli(millis);
var localDateTime = java.time.LocalDateTime
.ofInstant(instance, java.time.ZoneId.of("Asia/Kolkata"));
var zonedDateTime = java.time.ZonedDateTime
.ofInstant(instance,java.time.ZoneId.of("Asia/Kolkata"));
// Format the date
var formatter = java.time.format.DateTimeFormatter.ofPattern("u-M-d hh:mm:ss a O");
var string = zonedDateTime.format(formatter);
Use JavaScript Array includes() Method
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var n = fruits.includes("Mango");
Try it Yourself » link
Definition
The includes() method determines whether an array contains a specified element.
This method returns true if the array contains the element, and false if not.
Another way to make it work:
echo "mysql-server-5.5 mysql-server/root_password password root" | debconf-set-selections
echo "mysql-server-5.5 mysql-server/root_password_again password root" | debconf-set-selections
apt-get -y install mysql-server-5.5
Note that this simply sets the password to "root". I could not get it to set a blank password using simple quotes ''
, but this solution was sufficient for me.
Based on a solution here.
Look for the hidden .android folder in your user home folder. You might rename or delete this folder, recreate your AVD, and restart the emulator. It could be there is a .ini file in that folder that has that setting munged.
I do this with javascript (no library) and CSS - the table body scrolls with the page, and the table does not have to be fixed width or height, although each column must have a width. You can also keep sorting functionality.
Basically:
In HTML, create container divs to position the table header row and the table body, also create a "mask" div to hide the table body as it scrolls past the header
In CSS, convert the table parts to blocks
In Javascript, get the table width and match the mask's width... get the height of the page content... measure scroll position... manipulate CSS to set the table header row position and the mask height
Here's the javascript and a jsFiddle DEMO.
// get table width and match the mask width
function setMaskWidth() {
if (document.getElementById('mask') !==null) {
var tableWidth = document.getElementById('theTable').offsetWidth;
// match elements to the table width
document.getElementById('mask').style.width = tableWidth + "px";
}
}
function fixTop() {
// get height of page content
function getScrollY() {
var y = 0;
if( typeof ( window.pageYOffset ) == 'number' ) {
y = window.pageYOffset;
} else if ( document.body && ( document.body.scrollTop) ) {
y = document.body.scrollTop;
} else if ( document.documentElement && ( document.documentElement.scrollTop) ) {
y = document.documentElement.scrollTop;
}
return [y];
}
var y = getScrollY();
var y = y[0];
if (document.getElementById('mask') !==null) {
document.getElementById('mask').style.height = y + "px" ;
if (document.all && document.querySelector && !document.addEventListener) {
document.styleSheets[1].rules[0].style.top = y + "px" ;
} else {
document.styleSheets[1].cssRules[0].style.top = y + "px" ;
}
}
}
window.onscroll = function() {
setMaskWidth();
fixTop();
}
You could just change the shebang line. I do this all the time on new systems.
If you want pip
to install to a current version of Python installed just update the shebang line to the correct version of pythons path.
For example, to change pip (not pip3) to install to Python 3:
#!/usr/bin/python
To:
#!/usr/bin/python3
Any module you install using pip
should install to Python not Python.
Or you could just change the path.
For anyone who is looking a way to watch a specific file to exist in VBS:
Function bIsFileDownloaded(strPath, timeout)
Dim FSO, fileIsDownloaded
set FSO = CreateObject("Scripting.FileSystemObject")
fileIsDownloaded = false
limit = DateAdd("s", timeout, Now)
Do While Now < limit
If FSO.FileExists(strPath) Then : fileIsDownloaded = True : Exit Do : End If
WScript.Sleep 1000
Loop
Set FSO = Nothing
bIsFileDownloaded = fileIsDownloaded
End Function
Usage:
FileName = "C:\test.txt"
fileIsDownloaded = bIsFileDownloaded(FileName, 5) ' keep watching for 5 seconds
If fileIsDownloaded Then
WScript.Echo Now & " File is Downloaded: " & FileName
Else
WScript.Echo Now & " Timeout, file not found: " & FileName
End If
s=input("Enter any character:")
if s.isalnum():
print("Alpha Numeric Character")
if s.isalpha():
print("Alphabet character")
if s.islower():
print("Lower case alphabet character")
else:
print("Upper case alphabet character")
else:
print("it is a digit")
elif s.isspace():
print("It is space character")
else:
print("Non Space Special Character")
SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, getdate(), 112), 126), '-', ''), 'T', ''), ':', '')
First of all you need to include in your project
using System.Diagnostics;
After that you could write a general method that you could use for different .exe files that you want to use. It would be like below:
public void ExecuteAsAdmin(string fileName)
{
Process proc = new Process();
proc.StartInfo.FileName = fileName;
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.Verb = "runas";
proc.Start();
}
If you want to for example execute notepad.exe then all you do is you call this method:
ExecuteAsAdmin("notepad.exe");
@coldmind answer is correct but lacks details.
The 'NOT NULL constraint failed' occurs when something tries to set None to the 'zipcode' property, while it has not been explicitely allowed.
It usually happens when:
1) your field has Null=False by default, so that the value in the database cannot be None (i.e. undefined) when the object is created and saved in the database (this happens after a objects_set.create() call or setting the .zipcode property and doing a .save() call).
For instance, if somewhere in your code an assignement results in:
model.zipcode = None
this error is raised
2) When creating or updating the database, Django is constrained to find a default value to fill the field, because Null=False by default. It does not find any because you haven't defined any. So this error can not only happen during code execution but also when creating the database?
3) Note that the same error would be returned of you define default=None, or if your default value with an incorrect type, for instance default='00000' instead of 00000 for your field (maybe can there be automatic conversion between char and integers, but I would advise against relying on it. Besides, explicit is better than implicit). Most likely an error would also be raised if the default value violates the max_length property, e.g. 123456
So you'll have to define the field by one of the following:
models.IntegerField(_('zipcode'), max_length=5, Null=True,
blank=True)
models.IntegerField(_('zipcode'), max_length=5, Null=False,
blank=True, default=00000)
models.IntegerField(_('zipcode'), max_length=5, blank=True,
default=00000)
and then make a migration (python3 manage.py makemigration ) and then migrate (python3 manage.py migrate).
For safety you can also delete the last failed migration files in <app_name>/migrations/, there are usually named after this pattern:
<NUMBER>_auto_<DATE>_<HOUR>.py
Finally, if you don't set Null=True, make sure that mode.zipcode = None is never done anywhere.
For a more aesthetic appearance :) can be:
left:-9999em;
top:-9999em;
position for .sNv2 .nav UL
can be replaced by z-index:-1
and z-index:1
for .sNv2 .nav LI:Hover UL
Creating Custom ProgressBar like hotstar.
activity_main.xml
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="@+id/player_progressbar"
android:indeterminateDrawable="@drawable/custom_progress_bar"
/>
custom_progress_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="2000"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="1080" >
<shape
android:innerRadius="35dp"
android:shape="ring"
android:thickness="3dp"
android:useLevel="false" >
<size
android:height="80dp"
android:width="80dp" />
<gradient
android:centerColor="#80b7b4b2"
android:centerY="0.5"
android:endColor="#f4eef0"
android:startColor="#00938c87"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
To some extent, this is going to vary by the "flavour" of RegEx you're using. The following is based on .NET RegEx, which uses \b
for word boundaries. In the last example, it also uses negative lookaround (?<!)
and (?!)
as well as non-capturing parentheses (?:)
Basically, though, if the terms always contain at least one uppercase letter followed by at least one number, you can use
\b[A-Z]+[0-9]+\b
For all-uppercase and numbers (total must be 2 or more):
\b[A-Z0-9]{2,}\b
For all-uppercase and numbers, but starting with at least one letter:
\b[A-Z][A-Z0-9]+\b
The granddaddy, to return items that have any combination of uppercase letters and numbers, but which are not single letters at the beginning of a line and which are not part of a line that is all uppercase:
(?:(?<!^)[A-Z]\b|(?<!^[A-Z0-9 ]*)\b[A-Z0-9]+\b(?![A-Z0-9 ]$))
breakdown:
The regex starts with (?:
. The ?:
signifies that -- although what follows is in parentheses, I'm not interested in capturing the result. This is called "non-capturing parentheses." Here, I'm using the paretheses because I'm using alternation (see below).
Inside the non-capturing parens, I have two separate clauses separated by the pipe symbol |
. This is alternation -- like an "or". The regex can match the first expression or the second. The two cases here are "is this the first word of the line" or "everything else," because we have the special requirement of excluding one-letter words at the beginning of the line.
Now, let's look at each expression in the alternation.
The first expression is: (?<!^)[A-Z]\b
. The main clause here is [A-Z]\b
, which is any one capital letter followed by a word boundary, which could be punctuation, whitespace, linebreak, etc. The part before that is (?<!^)
, which is a "negative lookbehind." This is a zero-width assertion, which means it doesn't "consume" characters as part of a match -- not really important to understand that here. The syntax for negative lookbehind in .NET is (?<!x)
, where x is the expression that must not exist before our main clause. Here that expression is simply ^
, or start-of-line, so this side of the alternation translates as "any word consisting of a single, uppercase letter that is not at the beginning of the line."
Okay, so we're matching one-letter, uppercase words that are not at the beginning of the line. We still need to match words consisting of all numbers and uppercase letters.
That is handled by a relatively small portion of the second expression in the alternation: \b[A-Z0-9]+\b
. The \b
s represent word boundaries, and the [A-Z0-9]+
matches one or more numbers and capital letters together.
The rest of the expression consists of other lookarounds. (?<!^[A-Z0-9 ]*)
is another negative lookbehind, where the expression is ^[A-Z0-9 ]*
. This means what precedes must not be all capital letters and numbers.
The second lookaround is (?![A-Z0-9 ]$)
, which is a negative lookahead. This means what follows must not be all capital letters and numbers.
So, altogether, we are capturing words of all capital letters and numbers, and excluding one-letter, uppercase characters from the start of the line and everything from lines that are all uppercase.
There is at least one weakness here in that the lookarounds in the second alternation expression act independently, so a sentence like "A P1 should connect to the J9" will match J9, but not P1, because everything before P1 is capitalized.
It is possible to get around this issue, but it would almost triple the length of the regex. Trying to do so much in a single regex is seldom, if ever, justfied. You'll be better off breaking up the work either into multiple regexes or a combination of regex and standard string processing commands in your programming language of choice.
You could use a macro, but it’s simpler to use styles. Define a character style that has the desired text color and assign a shortcut key to it, say Alt+R. In order to be able to switch color using just the keyboard, define another character style, say “normal”, that has no special feature—just for use to get normal text after switching to your colored style, and assign another shortcut to it, say Alt+N. Then you would just type text, press Alt+R to switch to colored text, type that text, press Alt+N to resume normal text color, etc.
Though this does not directly answer the question, but I think it is a good alternative to avoid the question altogether.
To avoid all the autoload_paths
or eager_load_paths
hassle, create a "lib" or a "misc" directory under "app" directory. Place codes as you would normally do in there, and Rails will load files just like how it will load (and reload) model files.
A segementation fault is an internal error in php (or, less likely, apache). Oftentimes, the segmentation fault is caused by one of the newer and lesser-tested php modules such as imagemagick or subversion.
Try disabling all non-essential modules (in php.ini
), and then re-enabling them one-by-one until the error occurs. You may also want to update php and apache.
If that doesn't help, you should report a php bug.
There are two intents to call/start calling: ACTION_CALL and ACTION_DIAL.
ACTION_DIAL
will only open the dialer with the number
filled in, but allows the user to actually call or reject the call
. ACTION_CALL
will immediately call the number and requires an extra permission.
So make sure you have the permission
uses-permission android:name="android.permission.CALL_PHONE"
in your AndroidManifest.xml
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dbm.pkg"
android:versionCode="1"
android:versionName="1.0">
<!-- NOTE! Your uses-permission must be outside the "application" tag
but within the "manifest" tag. -->
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:icon="@drawable/icon"
android:label="@string/app_name">
<!-- Insert your other stuff here -->
</application>
<uses-sdk android:minSdkVersion="9" />
</manifest>
I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful
library(dplyr)
iris %>%
mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))
Hello I got the Perfect cod use this code
cd /D "%APPDATA%\Mozilla\Firefox\Profiles"
cd *.default
set ffile=%cd%
echo user_pref("network.proxy.http", "127.0.0.1"); >>prefs.js
echo user_pref("network.proxy.http_port", 8080); >>prefs.js
set ffile=
cd %windir
Try this:
const myString = "Hello World!";_x000D_
console.log(myString.slice(0, -1));
_x000D_
If you're using rails you can also use in_groups_of:
foo.in_groups_of(3)
string.join
connects elements inside list of strings, not ints.
Use this generator expression instead :
values = ','.join(str(v) for v in value_list)
As of version 2.4 of the Maven Dependency Plugin, you can also define a target destination for the artifact by using the -Ddest flag. It should point to a filename (not a directory) for the destination artifact. See the parameter page for additional parameters that can be used
mvn org.apache.maven.plugins:maven-dependency-plugin:2.4:get \
-DremoteRepositories=http://download.java.net/maven/2 \
-Dartifact=robo-guice:robo-guice:0.4-SNAPSHOT \
-Ddest=c:\temp\robo-guice.jar
i had the same problem before
the error code 3417 : the SQL SERVER cannot start the master database, without master db SQL SERVER can't start MSSQLSERVER_3417
The master database records all the system-level information for a SQL Server system. This includes instance-wide metadata such as logon accounts, endpoints, linked servers, and system configuration settings. In SQL Server, system objects are no longer stored in the master database; instead, they are stored in the Resource database. Also, master is the database that records the existence of all other databases and the location of those database files and records the initialization information for SQL Server. Therefore, SQL Server cannot start if the master database is unavailable MSDN Master DB so you need to reconfigure all settings after restoring master db
solutions
There are many ways to skip the first line. In addition to those said by Bakuriu, I would add:
with open(filename, 'r') as f:
next(f)
for line in f:
and:
with open(filename,'r') as f:
lines = f.readlines()[1:]
Install Inspect-it
pip3 install inspect-it --user
Code
import inspect;print(*['\n\x1b[0;36;1m| \x1b[0;32;1m{:25}\x1b[0;36;1m| \x1b[0;35;1m{}'.format(str(x.function), x.filename+'\x1b[0;31;1m:'+str(x.lineno)+'\x1b[0m') for x in inspect.stack()])
you can Make a snippet of this line
it will show you a list of the function call stack with a filename and line number
list from start to where you put this line
You can try:
SELECT id FROM your_table WHERE id = (SELECT MAX(id) FROM your_table)
Where id
is a primary key of the your_table
They have slightly different purposes.
exec()
is for calling a system command, and perhaps dealing with the output yourself. system()
is for executing a system command and immediately displaying the output - presumably text. passthru()
is for executing a system command which you wish the raw return from - presumably something binary.Regardless, I suggest you not use any of them. They all produce highly unportable code.
As noted in another answer, the official word from Microsoft is to open an Access 97 file in Access 2003 and upgrade it to a newer file format. Unfortunately, from now on many people will have difficulty getting their hands on a legitimate copy of Access 2003 (or any other version prior to Access 2013, or whatever the latest version happens to be).
In that case, a possible workaround would be to
I just tried that with a 32-bit version of SQL Server 2008 R2 Express Edition and it worked for me. Access 2013 adamantly refused to have anything to do with the Access 97 file, but SQL Server imported the tables without complaint.
At that point you could import the tables from SQL Server into an Access 2013 database. Or, if your goal was simply to get the data out of the Access 97 file then you could continue to work with it in SQL Server, or move it to some other platform, or whatever.
*Important: The import needs to be done using the older Jet ODBC driver ...
Microsoft Access Driver (*.mdb)
... which ships with Windows but is only available to 32-bit applications. The Access 2013 version of the newer Access Database Engine ("ACE") ODBC driver ...
Microsoft Access Driver (*.mdb, *.accdb)
also refuses to read Access 97 files (with the same error message cited in the question).
If all vectors have equal size, create a matrix and plot it.
Each column is plotted with a different color automatically
Then you can use legend
to indicate columns:
data = randn(100, 5);
figure;
plot(data);
legend(cellstr(num2str((1:size(data,2))')))
Or, if you have a cell with kernels names, use
legend(names)
I ran into a similar issue when building a custom pagination for a site I am working on.
The global variable I created in functions.php was defined and set to 0. I could output this value in my javascript no problem using the method @Karsten outlined above. The issue was with updating the global variable that I initially set to 0 inside the PHP file.
Here is my workaround (hacky? I know!) but after struggling for an hour on a tight deadline the following works:
Inside archive-episodes.php:
<script>
// We define the variable and update it in a php
// function defined in functions.php
var totalPageCount;
</script>
Inside functions.php
<?php
$totalPageCount = WP_Query->max_num_pages; // In my testing scenario this number is 8.
echo '<script>totalPageCount = $totalPageCount;</script>';
?>
To keep it simple, I was outputting the totalPageCount variable in an $ajax.success callback via alert.
$.ajax({
url: ajaxurl,
type: 'POST',
data: {"action": "infinite_scroll", "page_no": pageNumber, "posts_per_page": numResults},
beforeSend: function() {
$(".ajaxLoading").show();
},
success: function(data) {
//alert("DONE LOADING EPISODES");
$(".ajaxLoading").hide();
var $container = $("#episode-container");
if(firstRun) {
$container.prepend(data);
initMasonry($container);
ieMasonryFix();
initSearch();
} else {
var $newItems = $(data);
$container.append( $newItems ).isotope( 'appended', $newItems );
}
firstRun = false;
addHoverState();
smartResize();
alert(totalEpiPageCount); // THIS OUTPUTS THE CORRECT PAGE TOTAL
}
Be it as it may, I hope this helps others! If anyone has a "less-hacky" version or best-practise example I'm all ears.
/*-------- Bootstrap Modal Popup in Center of Screen --------------*/
/*---------------extra css------*/
.modal {
text-align: center;
padding: 0 !important;
}
.modal:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -4px;
}
.modal-dialog {
display: inline-block;
text-align: left;
vertical-align: middle;
}
/*----- Modal Popup -------*/
<div class="modal fade" role="dialog">
<div class="modal-dialog" >
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h5 class="modal-title">Header</h5>
</div>
<div class="modal-body">
body here
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
GIT_DIR should be unset: unset GIT_DIR
It seems like overkill but you can use supervisor to start and stop your simpleHttpserver, and completely manage it as a service.
Or just run it in the foreground as suggested and kill it with control c
You probably want to round the double to 5 decimals or so before comparing since a double can contain very small decimal parts if you have done some calculations with it.
double d = 10.0;
d /= 3.0; // d should be something like 3.3333333333333333333333...
d *= 3.0; // d is probably something like 9.9999999999999999999999...
// d should be 10.0 again but it is not, so you have to use rounding before comparing
d = myRound(d, 5); // d is something like 10.00000
if (fmod(d, 1.0) == 0)
// No decimals
else
// Decimals
If you are using C++ i don't think there is a round-function, so you have to implement it yourself like in: http://www.cplusplus.com/forum/general/4011/
For others who landed in this error and it's not 100% related to the OP question, please check that you are passing the value and it is not null in case of spring-boot: @Value annotation.
ORA-12899: value too large for column "DJ"."CUSTOMERS"."ADDRESS" (actual: 25, maximum: 2
Tells you what the error is. Address can hold maximum of 20 characters, you are passing 25 characters.
Photoshop - right click layer -> blending options -> color overlay change color and save
All the answers provide sufficient details to the question. However, let me add something more.
Why are we using these Interfaces:
Which interface does what:
When to use which interface:
According to http://jtuts.com/2014/08/26/difference-between-crudrepository-and-jparepository-in-spring-data-jpa/
Generally the best idea is to use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.
The JpaRepository should be avoided if possible, because it ties you repositories to the JPA persistence technology, and in most cases you probably wouldn’t even use the extra methods provided by it.
This can be scripted in PL/SQL pretty simply based on the DBA/ALL/USER_CONSTRAINTS system view, but various details make not as trivial as it sounds. You have to be careful about the order in which it is done and you also have to take account of the presence of unique indexes.
The order is important because you cannot drop a unique or primary key that is referenced by a foreign key, and there could be foreign keys on tables in other schemas that reference primary keys in your own, so unless you have ALTER ANY TABLE privilege then you cannot drop those PKs and UKs. Also you cannot switch a unique index to being a non-unique index so you have to drop it in order to drop the constraint (for this reason it's almost always better to implement unique constraints as a "real" constraint that is supported by a non-unique index).
Your method's return value has to be a List<Project>
.
Using select new
you are creating an instance of an anonymous type, instead of a Project
.
using (var client = new UserServicesClient())
{
var list = new AutoCompleteStringCollection();
list.AddRange(client.ListNames(query).ToArray());
comboBoxName.AutoCompleteCustomSource = list;
}
If you want to read CSV file with some lines, so this the solution.
while IFS=, read -ra line
do
test $i -eq 1 && ((i=i+1)) && continue
for col_val in ${line[@]}
do
echo -n "$col_val|"
done
echo
done < "$csvFile"
You can achieve the solution, by doing this:
JavaScript:
var myValue = document.getElementById("@(ViewBag.CC)").value;
or if you want to use jQuery
, then:
jQuery
var myValue = $('#' + '@(ViewBag.CC)').val();
With this query you can execute any stored procedure(With or Without output parameter):
DECLARE @temp varchar(100)
EXEC my_sp
@parameter1 = 1,
@parameter2 = 2,
@parameter3 = @temp output,
@parameter4 = 3,
@parameter5 = 4
PRINT @temp
Here datatype of @temp should be same as @parameter3 within SP.
Hope this helps..
Just found this answer from another link,
npm uninstall @angular-devkit/build-angular
npm install @angular-devkit/[email protected]
I think this is very nice and short
<img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />
But, be careful. The user's browser will be stuck in an endless loop if the onerror image itself generates an error.
EDIT
To avoid endless loop, remove the onerror
from it at once.
<img src="imagenotfound.gif" alt="Image not found" onerror="this.onerror=null;this.src='imagefound.gif';" />
By calling this.onerror=null
it will remove the onerror then try to get the alternate image.
NEW I would like to add a jQuery way, if this can help anyone.
<script>
$(document).ready(function()
{
$(".backup_picture").on("error", function(){
$(this).attr('src', './images/nopicture.png');
});
});
</script>
<img class='backup_picture' src='./images/nonexistent_image_file.png' />
You simply need to add class='backup_picture' to any img tag that you want a backup picture to load if it tries to show a bad image.
Depends on the version, 4 is by value, 5 is by reference.
To replace a string in a single file (currently opened): CTRL + H
For replacing at workspace level use: CTRL + SHIFT + H
if you use fragment u should use
getActivity().onBackPressed();
if you use single activity u can use
finish();
UPDATE ed
SET ed.kWh = ted.kWh
FROM energydata ed
INNER JOIN temp_energydata ted ON ted.webmeterID = ed.webmeterID
web.xml
they are in the servlet container configuration files (server.xml
on tomcat)No. But the default servlet (mapped in a web.xml at a common location in your servlet container) should preferably disable file listings (so that users don't see the contents of your web folders):
listings true
I have had the same error on the test server but not in local. After a few minutes, I discovered that the IDE wasn't synchronized with the pom.xml. Here is how I solve it:
I also had this problem several times and I could 'solve' it by just deleting the messages in the "Problems"-tab and building the project again. Select the project and click on the menu bar Project -> Clean...
select your project again and okay.
I just copied the jre folder to whatever path the message tells me it was missing at, and solved it.
(after editing the JAVA_HOME and editing the eclipse.ini didn't worked (as i probably did something wrong)) (i have no other java applications running so it's not affecting me)
I have the same problem while learning Node.js Here is my solution for it to install jquery
npm install [email protected] --save
npm install popper.js@^1.12.9 --save
If you want to update a single gem to a specific version:
bundle update
> ruby -v
ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-darwin19]
> gem -v
3.0.3
> bundle -v
Bundler version 2.1.4
Probably the most elegant way of doing this is to do it in one step. See val()
.
$("#text").val(function(i, val) {
return val.replace('.', ':');
});
compared to:
var val = $("#text").val();
$("#text").val(val.replace('.', ':'));
From the docs:
.val( function(index, value) )
function(index, value)A function returning the value to set.
This method is typically used to set the values of form fields. For
<select multiple="multiple">
elements, multiple s can be selected by passing in an array.The
.val()
method allows us to set the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value:$('input:text.items').val(function(index, value) { return value + ' ' + this.className; });
This example appends the string " items" to the text inputs' values.
This requires jQuery 1.4+.
Solution using just POST - no $_SESSION
page1.php
<form action="page2.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
page2.php
<?php
// this page outputs the contents of the textarea if posted
$textarea1 = ""; // set var to avoid errors
if(isset($_POST['textarea1'])){
$textarea1 = $_POST['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
Solution using $_SESSION and POST
page1.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
$textarea1 = "";
if(isset($_POST['textarea1'])){
$_SESSION['textarea1'] = $_POST['textarea1'];
}
?>
<form action="page1.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>
page2.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
// this page outputs the textarea1 from the session IF it exists
$textarea1 = ""; // set var to avoid errors
if(isset($_SESSION['textarea1'])){
$textarea1 = $_SESSION['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
WARNING!!! - This contains no validation!!!
This is possible in Java 9.
Stream.generate(() -> null)
.takeWhile(x -> iterator.hasNext())
.map(n -> iterator.next())
.forEach(System.out::println);
You could do this but it is hacky
.application-title {
background:url("/path/to/image.png");
/* set these dims according to your image size */
width:500px;
height:500px;
}
.application-title img {
display:none;
}
Here is a working example:
The problem is that the true y is binary (zeros and ones), while your predictions are not. You probably generated probabilities and not predictions, hence the result :) Try instead to generate class membership, and it should work!
So Why not use powershell to create the list of source files for you. Take a look at this script
param (
[Parameter(Mandatory=$True)]
[string]$root
)
if (-not (Test-Path -Path $root)) {
throw "Error directory does not exist"
}
#get the full path of the root
$rootDir = get-item -Path $root
$fp=$rootDir.FullName;
$files = Get-ChildItem -Path $root -Recurse -File |
Where-Object { ".cpp",".cxx",".cc",".h" -contains $_.Extension} |
Foreach {$_.FullName.replace("${fp}\","").replace("\","/")}
$CMakeExpr = "set(SOURCES "
foreach($file in $files){
$CMakeExpr+= """$file"" " ;
}
$CMakeExpr+=")"
return $CMakeExpr;
Suppose you have a folder with this structure
C:\Workspace\A
--a.cpp
C:\Workspace\B
--b.cpp
Now save this file as "generateSourceList.ps1" for example, and run the script as
~>./generateSourceList.ps1 -root "C:\Workspace" > out.txt
out.txt file will contain
set(SOURCE "A/a.cpp" "B/b.cpp")
Stored as strings:
public class ReadTemps {
public static void main(String[] args) throws IOException {
// TODO code application logic here
// // read KeyWestTemp.txt
// create token1
String token1 = "";
// for-each loop for calculating heat index of May - October
// create Scanner inFile1
Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt")).useDelimiter(",\\s*");
// Original answer used LinkedList, but probably preferable to use ArrayList in most cases
// List<String> temps = new LinkedList<String>();
List<String> temps = new ArrayList<String>();
// while loop
while (inFile1.hasNext()) {
// find next line
token1 = inFile1.next();
temps.add(token1);
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
for (String s : tempsArray) {
System.out.println(s);
}
}
}
For floats:
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class ReadTemps {
public static void main(String[] args) throws IOException {
// TODO code application logic here
// // read KeyWestTemp.txt
// create token1
// for-each loop for calculating heat index of May - October
// create Scanner inFile1
Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt")).useDelimiter(",\\s*");
// Original answer used LinkedList, but probably preferable to use ArrayList in most cases
// List<Float> temps = new LinkedList<Float>();
List<Float> temps = new ArrayList<Float>();
// while loop
while (inFile1.hasNext()) {
// find next line
float token1 = inFile1.nextFloat();
temps.add(token1);
}
inFile1.close();
Float[] tempsArray = temps.toArray(new Float[0]);
for (Float s : tempsArray) {
System.out.println(s);
}
}
}
There is a better way you can handle the import of modules in your React App. Consider doing this:
Add a
jsconfig.json
file to your base folder. That is the same folder containing your package.json. Next define your base URL imports in it:
//jsconfig.json
{
"compilerOptions": {
"baseUrl": "./src"
}
}
Now rather than calling ../../
you can easily do this instead:
import navBar from 'components/header/navBar'
import 'css/header.css'
Notice that 'components/' is different from '../components/'
It's neater this way.
But if you want to import files in the same directory you can do this also:
import logo from './logo.svg'
After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))
HTML:
<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
<label>File to stash:</label>
<input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>
jQuery:
$(function(){
$('#uploadBTN').on('click', function(){
var fd = new FormData($("#fileinfo"));
//fd.append("CustomField", "This is some extra data");
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
In the upload.php
file you can access the data passed with $_FILES['file']
.
Thanks everyone for trying to help:)
I took the answer from here (with some changes) MDN
If you update your libs, you want to commit the lockfile too. It basically states that your project is locked to those specific versions of the libs you are using.
If you commit your changes, and someone pulls your code and updates the dependencies, the lockfile should be unmodified. If it is modified, it means that you have a new version of something.
Having it in the repository assures you that each developer is using the same versions.
If the file is local as your comment about SITE_PATH
suggest, it's pretty simple just execute the script and cache the result in a variable using the output control functions :
function print_xml_data_file()
{
include(XML_DATA_FILE_DIRECTORY . 'cms/data.php');
}
function get_xml_data()
{
ob_start();
print_xml_data_file();
$xml_file = ob_get_contents();
ob_end_clean();
return $xml_file;
}
If it's remote as lot of others said curl
is the way to go. If it isn't present try socket_create
or fsockopen
. If nothing work... change your hosting provider.
I had a problem with the answer by @mwaskorn, namely that
g.set_xticklabels(rotation=30)
fails, because this also requires the labels. A bit easier than the answer by @Aman is to just add
plt.xticks(rotation=45)
You can OpenGL without a wrapper and use it natively in C#. Just as Jeff Mc said, you would have to import all the functions you need with DllImport.
What he left out is having to create context before you can use any of the OpenGL functions. It's not hard, but there are few other not-so-intuitive DllImports that need to be done.
I have created an example C# project in VS2012 with almost the bare minimum necessary to get OpenGL running on Windows box. It only paints the window blue, but it should be enough to get you started. The example can be found at http://www.glinos-labs.org/?q=programming-opengl-csharp. Look for the No Wrapper example at the bottom.
This (mysql_connect, mysql_...) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
(ref: http://php.net/manual/en/function.mysql-connect.php)
Object Oriented:
$mysqli = new mysqli("host", "user", "password");
$mysqli->select_db("db");
Procedural:
$link = mysqli_connect("host","user","password") or die(mysqli_error($link));
mysqli_select_db($link, "db");
Only second approach will work. You can modify collection during iteration using iterator.remove()
only. All other attempts will cause ConcurrentModificationException
.
The solution from Xavier Ho of doubling the width of the stroke and changing the paint-order is brilliant, although only works if the fill is a solid color, with no transparency.
I have developed other approach, more complicated but works for any fill. It also works in ellipses or paths (with the later there are some corner cases with strange behaviour, for example open paths that crosses theirselves, but not much).
The trick is to display the shape in two layers. One without stroke (only fill), and another one only with stroke at double width (transparent fill) and passed through a mask that shows the whole shape, but hides the original shape without stroke.
<svg width="240" height="240" viewBox="0 0 1024 1024">
<defs>
<path id="ld" d="M256,0 L0,512 L384,512 L128,1024 L1024,384 L640,384 L896,0 L256,0 Z"/>
<mask id="mask">
<use xlink:href="#ld" stroke="#FFFFFF" stroke-width="160" fill="#FFFFFF"/>
<use xlink:href="#ld" fill="#000000"/>
</mask>
</defs>
<g>
<use xlink:href="#ld" fill="#00D2B8"/>
<use xlink:href="#ld" stroke="#0081C6" stroke-width="160" fill="red" mask="url(#mask)"/>
</g>
</svg>
I do these steps to solve this problem in Windows Server 2012, IIS 8.5. Should work for other versions too.
Web Server
.NET Extensibility 4.5
, ASP.NET 4.5
and both ISAPI
entriesNET 3.5
, .NET 4.5
, ASP.NET 4.5
Web Server
(all), Management Tools
(IIS Management Console and Management Service), Windows In my opinion, the only proper answer to this question is to try to use the path and let the OS and filesystem validate it. Otherwise you are just reimplementing (and probably poorly) all the validation rules that the OS and filesystem already use and if those rules are changed in the future you will have to change your code to match them.
If anyone is following all the steps and having no success, make sure that you are using the correct user. I was attempting to use "ec2-user" but I needed to use "ubuntu."
WARNING: Security researches have found several poisoned packages on PyPI, including a package named
urllib
, which will 'phone home' when installed. If you usedpip install urllib
some time after June 2017, remove that package as soon as possible.
You can't, and you don't need to.
urllib2
is the name of the library included in Python 2. You can use the urllib.request
library included with Python 3, instead. The urllib.request
library works the same way urllib2
works in Python 2. Because it is already included you don't need to install it.
If you are following a tutorial that tells you to use urllib2
then you'll find you'll run into more issues. Your tutorial was written for Python 2, not Python 3. Find a different tutorial, or install Python 2.7 and continue your tutorial on that version. You'll find urllib2
comes with that version.
Alternatively, install the requests
library for a higher-level and easier to use API. It'll work on both Python 2 and 3.
MySQL support is simple to add. In your DATABASES
dictionary, you will have an entry like this:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DB_NAME',
'USER': 'DB_USER',
'PASSWORD': 'DB_PASSWORD',
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '3306',
}
}
You also have the option of utilizing MySQL option files, as of Django 1.7. You can accomplish this by setting your DATABASES
array like so:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': '/path/to/my.cnf',
},
}
}
You also need to create the /path/to/my.cnf
file with similar settings from above
[client]
database = DB_NAME
host = localhost
user = DB_USER
password = DB_PASSWORD
default-character-set = utf8
With this new method of connecting in Django 1.7, it is important to know the order connections are established:
1. OPTIONS.
2. NAME, USER, PASSWORD, HOST, PORT
3. MySQL option files.
In other words, if you set the name of the database in OPTIONS, this will take precedence over NAME, which would override anything in a MySQL option file.
If you are just testing your application on your local machine, you can use
python manage.py runserver
Adding the ip:port
argument allows machines other than your own to access your development application. Once you are ready to deploy your application, I recommend taking a look at the chapter on Deploying Django on the djangobook
Mysql default character set is often not utf-8, therefore make sure to create your database using this sql:
CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_bin
If you are using Oracle's MySQL connector your ENGINE
line should look like this:
'ENGINE': 'mysql.connector.django',
Note that you will first need to install mysql on your OS.
brew install mysql (MacOS)
Also, the mysql client package has changed for python 3 (MySQL-Client
works only for python 2)
pip3 install mysqlclient
I know this basic method:
1)
<input type=”image” src=”submit.png”> (in any place)
2)
<form name=”print”>
<input type=”hidden” name=”a” value=”<?= $a ?>”>
<input type=”hidden” name=”b” value=”<?= $b ?>”>
<input type=”hidden” name=”c” value=”<?= $c ?>”>
</form>
3)
<script>
$(‘#submit’).click(function(){
open(”,”results”);
with(document.print)
{
method = “POST”;
action = “results.php”;
target = “results”;
submit();
}
});
</script>
Works!
You have to execute your query and add single quote to $email in the query beacuse it's a string, and remove the is_resource($query)
$query is a string, the $result will be the resource
$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($link,$query); //$link is the connection
if(mysqli_num_rows($result) > 0 ){....}
UPDATE
Base in your edit just change:
if(is_resource($query) && mysqli_num_rows($query) > 0 ){
$query = mysqli_fetch_assoc($query);
echo $email . " email exists " . $query["email"] . "\n";
By
if(is_resource($result) && mysqli_num_rows($result) == 1 ){
$row = mysqli_fetch_assoc($result);
echo $email . " email exists " . $row["email"] . "\n";
and you will be fine
UPDATE 2
A better way should be have a Store Procedure that execute the following SQL passing the Email as Parameter
SELECT IF( EXISTS (
SELECT *
FROM `Table`
WHERE `email` = @Email)
, 1, 0) as `Exist`
and retrieve the value in php
Pseudocodigo:
$query = Call MYSQL_SP($EMAIL);
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result)
$exist = ($row['Exist']==1)? 'the email exist' : 'the email doesnt exist';
In a talk about core containers internals in Python at PyCon 2012, Raymond Hettinger is suggesting to use [None] * n
to pre-allocate the length you want.
Slides available as PPT or via Google
The whole slide deck is quite interesting. The presentation is available on YouTube, but it doesn't add much to the slides.
use this polyfill https://github.com/UziTech/js-date-format
var d = new Date("1/1/2014 10:00 am");
d.format("DDDD 'the' DS 'of' MMMM YYYY h:mm TT");
//output: Wednesday the 1st of January 2014 10:00 AM
check what is using your GPU memory with
sudo fuser -v /dev/nvidia*
Your output will look something like this:
USER PID ACCESS COMMAND
/dev/nvidia0: root 1256 F...m Xorg
username 2057 F...m compiz
username 2759 F...m chrome
username 2777 F...m chrome
username 20450 F...m python
username 20699 F...m python
Then kill the PID that you no longer need on htop
or with
sudo kill -9 PID.
In the example above, Pycharm was eating a lot of memory so I killed 20450 and 20699.
If you want the second highest number you can use
=LARGE(E4:E9;2)
although that doesn't account for duplicates so you could get the same result as the Max
If you want the largest number that is smaller than the maximum number you can use this version
=LARGE(E4:E9;COUNTIF(E4:E9;MAX(E4:E9))+1)
Check out from dateutil.relativedelta import *
for adding a specific amount of time to a date, you can continue to use timedelta
for the simple stuff i.e.
use_date = use_date + datetime.timedelta(minutes=+10)
use_date = use_date + datetime.timedelta(hours=+1)
use_date = use_date + datetime.timedelta(days=+1)
use_date = use_date + datetime.timedelta(weeks=+1)
or you can start using relativedelta
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(years=+1)
for the last day of next month:
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
Right now this will provide 29/02/2016
for the penultimate day of next month:
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
use_date = use_date+relativedelta(days=-1)
last Friday of the next month:
use_date = use_date+relativedelta(months=+1, day=31, weekday=FR(-1))
2nd Tuesday of next month:
new_date = use_date+relativedelta(months=+1, day=1, weekday=TU(2))
As @mrroot5 points out dateutil's rrule
functions can be applied, giving you an extra bang for your buck, if you require date occurences.
for example:
Calculating the last day of the month for 9 months from the last day of last month.
Then, calculate the 2nd Tuesday for each of those months.
from dateutil.relativedelta import *
from dateutil.rrule import *
from datetime import datetime
use_date = datetime(2020,11,21)
#Calculate the last day of last month
use_date = use_date+relativedelta(months=-1)
use_date = use_date+relativedelta(day=31)
#Generate a list of the last day for 9 months from the calculated date
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, bymonthday=(-1,)))
print("Last day")
for ld in x:
print(ld)
#Generate a list of the 2nd Tuesday in each of the next 9 months from the calculated date
print("\n2nd Tuesday")
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, byweekday=TU(2)))
for tuesday in x:
print(tuesday)
Last day
2020-10-31 00:00:00
2020-11-30 00:00:00
2020-12-31 00:00:00
2021-01-31 00:00:00
2021-02-28 00:00:00
2021-03-31 00:00:00
2021-04-30 00:00:00
2021-05-31 00:00:00
2021-06-30 00:00:00
2nd Tuesday
2020-11-10 00:00:00
2020-12-08 00:00:00
2021-01-12 00:00:00
2021-02-09 00:00:00
2021-03-09 00:00:00
2021-04-13 00:00:00
2021-05-11 00:00:00
2021-06-08 00:00:00
2021-07-13 00:00:00
This is by no means an exhaustive list of what is available. Documentation is available here: https://dateutil.readthedocs.org/en/latest/
Using the out keyword with a return type of bool, can sometimes reduce code bloat and increase readability. (Primarily when the extra info in the out param is often ignored.) For instance:
var result = DoThing();
if (result.Success)
{
result = DoOtherThing()
if (result.Success)
{
result = DoFinalThing()
if (result.Success)
{
success = true;
}
}
}
vs:
var result;
if (DoThing(out result))
{
if (DoOtherThing(out result))
{
if (DoFinalThing(out result))
{
success = true;
}
}
}
Simply make a div to be the direct child of body (with the class name bg for example), encompassing all other elements in the body, and add this to the CSS file:
.bg {
background-image: url('_images/home.jpg');//Put your appropriate image URL here
background-size: 100% 100%; //You need to put 100% twice here to stretch width and height
}
Refer to this link: https://www.w3schools.com/css/css_rwd_images.asp Scroll down to the part that says:
- If the background-size property is set to "100% 100%", the background image will stretch to cover the entire content area
There it shows the 'img_flowers.jpg' stretching to the size of the screen or browser regardless of how you resize it.
This is what I ended up using, as of 2018:
<section id="top-<?=(is_front_page() ? 'home' : basename(get_permalink()));?>">
map.has(key)
is the latest ECMAScript 2015
way of checking the existance of a key in a map. Refer to this for complete details.
It looks like you want to define Truck as a Class
with properties NumberOfAxles, AxleWeights & AxleSpacings.
This can be defined in a CLASS MODULE (here named clsTrucks)
Option Explicit
Private tID As String
Private tNumberOfAxles As Double
Private tAxleSpacings As Double
Public Property Get truckID() As String
truckID = tID
End Property
Public Property Let truckID(value As String)
tID = value
End Property
Public Property Get truckNumberOfAxles() As Double
truckNumberOfAxles = tNumberOfAxles
End Property
Public Property Let truckNumberOfAxles(value As Double)
tNumberOfAxles = value
End Property
Public Property Get truckAxleSpacings() As Double
truckAxleSpacings = tAxleSpacings
End Property
Public Property Let truckAxleSpacings(value As Double)
tAxleSpacings = value
End Property
then in a MODULE the following defines a new truck and it's properties and adds it to a collection of trucks and then retrieves the collection.
Option Explicit
Public TruckCollection As New Collection
Sub DefineNewTruck()
Dim tempTruck As clsTrucks
Dim i As Long
'Add 5 trucks
For i = 1 To 5
Set tempTruck = New clsTrucks
'Random data
tempTruck.truckID = "Truck" & i
tempTruck.truckAxleSpacings = 13.5 + i
tempTruck.truckNumberOfAxles = 20.5 + i
'tempTruck.truckID is the collection key
TruckCollection.Add tempTruck, tempTruck.truckID
Next i
'retrieve 5 trucks
For i = 1 To 5
'retrieve by collection index
Debug.Print TruckCollection(i).truckAxleSpacings
'retrieve by key
Debug.Print TruckCollection("Truck" & i).truckAxleSpacings
Next i
End Sub
There are several ways of doing this so it really depends on how you intend to use the data as to whether an a class/collection is the best setup or arrays/dictionaries etc.
To make the query run faster in big tables where not every line needs to be updated, you can also choose to only update rows that will be modified:
UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <= 4
AND Value LIKE '%123%'
I suggest using isoFormat
for better appearance on the web pages.
{{ \Carbon\Carbon::parse($blog->created_at)->isoFormat('MMM Do YYYY')}}
The result is
Jan 21st 2021
Try:
string output = YourString.replaceAll("\\s","")
s - indicates space character (tab characters etc)
I had this issue recently. In my case, I had my IDE set to choose which compiler (C or C++) to use on each file according to its extension, and I was trying to call a C function (i.e. from a .c
file) from C++ code.
The .h
file for the C function wasn't wrapped in this sort of guard:
#ifdef __cplusplus
extern "C" {
#endif
// all of your legacy C code here
#ifdef __cplusplus
}
#endif
I could've added that, but I didn't want to modify it, so I just included it in my C++ file like so:
extern "C" {
#include "legacy_C_header.h"
}
(Hat tip to UncaAlby for his clear explanation of the effect of extern "C".)
.grandparent{
display: table;
}
.parent{
display: table-cell
vertical-align: middle
}
This worked for me.
Just use this
$('#multipleSelect').change(function() {
var selectedValues = $(this).val();
});
More simple than that.
List<Integer> arrayIntegers = new ArrayList<>(Arrays.asList(1,2,3));
arrayIntegers.get(1);
In the first line you create the object and in the constructor you pass an array parameter to List.
In the second line you have all the methods of the List class: .get (...)
Take a look at http://developer.android.com/reference/org/json/JSONTokener.html
This might fix your issue.
If you want to set filemode to false in config files recursively (including submodules) :
find -name config | xargs sed -i -e 's/filemode = true/filemode = false/'
from the pandas doc http://pandas.pydata.org/pandas-docs/stable/dsintro.html Series is a one-dimensional labeled array capable of holding any data type. To read data in form of panda Series:
import pandas as pd
ds = pd.Series(data, index=index)
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types.
import pandas as pd
df = pd.DataFrame(data, index=index)
In both of the above index is list
for example: I have a csv file with following data:
,country,popuplation,area,capital
BR,Brazil,10210,12015,Brasile
RU,Russia,1025,457,Moscow
IN,India,10458,457787,New Delhi
To read above data as series and data frame:
import pandas as pd
file_data = pd.read_csv("file_path", index_col=0)
d = pd.Series(file_data.country, index=['BR','RU','IN'] or index = file_data.index)
output:
>>> d
BR Brazil
RU Russia
IN India
df = pd.DataFrame(file_data.area, index=['BR','RU','IN'] or index = file_data.index )
output:
>>> df
area
BR 12015
RU 457
IN 457787
Operations on integers are exact. double
is a floating point data type, and floating point operations are approximate whenever there's a fraction.
double
also takes up twice as much space as int
in many implementations (e.g. most 32-bit systems) .
You can't use UIImagePickerController
, but you can use a custom image picker. I think ELCImagePickerController
is the best option, but here are some other libraries you could use:
Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection
Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker
Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.
/*
Write a function called randUpTo
that accepts a number and returns a
random whole number between 0 and that number?
*/
var randUpTo = function(num) {
return Math.floor(Math.random() * (num - 1) + 0);
};
/*
Write a function called randBetween
that accepts two numbers
representing a range and returns a random whole number between those two
numbers.
*/
var randBetween = function (min, max) {
return Math.floor(Math.random() * (max - min - 1)) + min;
};
/*
Write a function called randFromTill
that accepts two numbers
representing a range and returns a random number between min (inclusive)
and max (exclusive).
*/
var randFromTill = function (min, max) {
return Math.random() * (max - min) + min;
};
/*
Write a function called randFromTo
that accepts two numbers
representing a range and returns a random integer between min (inclusive)
and max (inclusive)
*/
var randFromTo = function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
See ?merge
:
the name "row.names" or the number 0 specifies the row names.
Example:
R> de <- merge(d, e, by=0, all=TRUE) # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0 # replace NA values
R> de
Row.names a b c d e f g h i j k l m n o p q r s
1 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0 0 0 0 0 0 0 0
3 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 21 22 23 24 25 26 27 28 29
t
1 20
2 0
3 30
The following regex will accept YYYY-MM-DD (within the range 1600-2999 year) formatted dates taking into consideration leap years:
^((?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:(?:0[13578]|1[02])(-)31)|((0[1,3-9]|1[0-2])(-)(29|30))))$|^(?:(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(-)02(-)29)$|^(?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:0[1-9])|(?:1[0-2]))(-)(?:0[1-9]|1\d|2[0-8])$
Examples:
You can test it here.
Note: if you want to accept one digit as month or day you can use:
^((?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:(?:0?[13578]|1[02])(-)31)|((0?[1,3-9]|1[0-2])(-)(29|30))))$|^(?:(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(-)0?2(-)29)$|^(?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:0?[1-9])|(?:1[0-2]))(-)(?:0?[1-9]|1\d|2[0-8])$
I have created the above regex starting from this solution
Methods can only declare local variables. That is why the compiler reports an error when you try to declare it as public.
In the case of local variables you can not use any kind of accessor (public, protected or private).
You should also know what the static keyword means. In method checkYourself
, you use the Integer array locations
.
The static keyword distinct the elements that are accessible with object creation. Therefore they are not part of the object itself.
public class Test { //Capitalized name for classes are used in Java
private final init[] locations; //key final mean that, is must be assigned before object is constructed and can not be changed later.
public Test(int[] locations) {
this.locations = locations;//To access to class member, when method argument has the same name use `this` key word.
}
public boolean checkYourSelf(int value) { //This method is accessed only from a object.
for(int location : locations) {
if(location == value) {
return true; //When you use key word return insied of loop you exit from it. In this case you exit also from whole method.
}
}
return false; //Method should be simple and perform one task. So you can get more flexibility.
}
public static int[] locations = {1,2,3};//This is static array that is not part of object, but can be used in it.
public static void main(String[] args) { //This is declaration of public method that is not part of create object. It can be accessed from every place.
Test test = new Test(Test.locations); //We declare variable test, and create new instance (object) of class Test.
String result;
if(test.checkYourSelf(2)) {//We moved outside the string
result = "Hurray";
} else {
result = "Try again"
}
System.out.println(result); //We have only one place where write is done. Easy to change in future.
}
}
Simplest Understanding for default export
is
Export
is ES6's feature which is used to Export a module(file) and use it in some other module(file).
Default Export:
default export
is the convention if you want to export only one object(variable, function, class) from the file(module).Export or Named Export:
It is used to export the object(variable, function, calss) with the same name.
It is used to export multiple objects from one file.
It cannot be renamed when importing in another file, it must have the same name that was used to export it, but we can create its alias by using as
operator.
In React, Vue and many other frameworks the Export is mostly used to export reusable components to make modular based applications.
Use preventDefault()
to stop the event of submit button and in ajax call success submit the form using submit()
:
$('#btnSave').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
var element = this;
$.ajax({
url: "/Home/SaveDetailedInfo",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
$(element).closest("form").submit(); //<------------ submit form
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
This is the syntax of creating primary key
db.< collection >.createIndex( < key and index type specification>, { unique: true } )
Let's take that our database have collection named student and it's document have key named student_id which we need to make a primary key. Then the command should be like below.
db.student.createIndex({student_id:1},{unique:true})
You can check whether this student_id set as primary key by trying to add duplicate value to the student collection.
prefer this document for further informations https://docs.mongodb.com/manual/core/index-unique/#create-a-unique-index
Building on the other answers, I wanted to share an example of using the while loop construct to achieve a do-while behaviour. By using a simple boolean variable in the while condition (initialized to TRUE), and then checking our actual condition later in the if statement. One could also use a break keyword instead of the continue <- FALSE inside the if statement (probably more efficient).
df <- data.frame(X=c(), R=c())
x <- x0
continue <- TRUE
while(continue)
{
xi <- (11 * x) %% 16
df <- rbind(df, data.frame(X=x, R=xi))
x <- xi
if(xi == x0)
{
continue <- FALSE
}
}
It seems that you want to use step parameter of range function. From documentation:
range(start, stop[, step]) This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised). Example:
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5) [0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3) [0, 3, 6, 9]
>>> range(0, -10, -1) [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0) []
>>> range(1, 0) []
In your case to get [0,2,4] you can use:
range(0,6,2)
OR in your case when is a var:
idx = None
for i in range(len(str1)):
if idx and i < idx:
continue
for j in range(len(str2)):
if str1[i+j] != str2[j]:
break
else:
idx = i+j
You can redirect standard input and use a StreamWriter to write to it:
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.UseShellExecute = false;
p.StartInfo = info;
p.Start();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("mysql -u root -p");
sw.WriteLine("mypassword");
sw.WriteLine("use mydb;");
}
}
If there's not any value bigger than the size of the map, you could use arrays, this should be the fastest approach:
public List<String> getList(Map<String, Integer> myMap) {
String[] copyArray = new String[myMap.size()];
for (Entry<String, Integer> entry : myMap.entrySet()) {
copyArray[entry.getValue()] = entry.getKey();
}
return Arrays.asList(copyArray);
}
sed -n 1p /etc/*release |cut -d " " -f1
if tab delimited:
sed -n 1p /etc/*release |cut -f1
Give vertical-align:top;
in a
& span
. Like this:
a, span{
vertical-align:top;
}
Check this http://jsfiddle.net/TFPx8/10/
make
is a GNU command so the only way you can get it on Windows is installing a Windows version like the one provided by GNUWin32. Anyway, there are several options for getting that:
C:\MinGW\bin\mingw32-make.exe
. Otherwise you're missing the mingw32-make additional utilities
. Look for the link at MinGW's HowTo page to get it installed. Once you've got it, you have two choices:1.1 Copy the MinGW make executable to make.exe
:
copy c:\MinGW\bin\mingw32-make.exe c:\MinGW\bin\make.exe
1.2 Create a link to the actual executable, in your PATH. In this case, if you update MinGW, the link is not deleted:
mklink c:\bin\make.exe C:\MinGW\bin\mingw32-make.exe
Other option is using Chocolatey. First you need to install this package manager. Once installed you simlpy need to install make
:
choco install make
Last option is installing a Windows Subsystem for Linux (WSL), so you'll have a Linux distribution of your choice embedded in Windows 10 where you'll be able to install make
, gcc
and all the tools you need to build C programs.
You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.
Here is a sample code I have written, where you can see how the live() method binds chosen elements, even newly created ones, to events:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js"></script>
<input type="button" id="theButton" value="Click" />
<script type="text/javascript">
$(document).ready(function()
{
$('.FOO').live("click", function (){alert("It Works!")});
var $dialog = $('<div></div>').html('<div id="container"><input type ="button" id="CUSTOM" value="click"/>This dialog will show every time!</div>').dialog({
autoOpen: false,
tite: 'Basic Dialog'
});
$('#theButton').click(function()
{
$dialog.dialog('open');
return('false');
});
$('#CUSTOM').click(function(){
//$('#container').append('<input type="button" value="clickmee" class="FOO" /></br>');
var button = document.createElement("input");
button.setAttribute('class','FOO');
button.setAttribute('type','button');
button.setAttribute('value','CLICKMEE');
$('#container').append(button);
});
/* $('#FOO').click(function(){
alert("It Works!");
}); */
});
</script>
</body>
</html>
I had the same issue using an older version of Fancybox. Upgrading to v3 will solve your problem OR you can just add:
html, body {
-webkit-overflow-scrolling : touch !important;
overflow: auto !important;
height: 100% !important;
}
100 % Working Code For Gmail Share
Intent intent = new Intent (Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Any subject if you want");
intent.setPackage("com.google.android.gm");
if (intent.resolveActivity(getPackageManager())!=null)
startActivity(intent);
else
Toast.makeText(this,"Gmail App is not installed",Toast.LENGTH_SHORT).show();
JavaScript will be required, but the amount of code can be kept to a minimum by using an intermediary <output>
element and an oninput
form handler to perform the comparison (patterns and validation could augment this solution, but aren't shown here for sake of simplicity):
<form oninput="result.value=!!p2.value&&(p1.value==p2.value)?'Match!':'Nope!'">
<input type="password" name="p1" value="" required />
<input type="password" name="p2" value="" required />
<output name="result"></output>
</form>
input { float: right; clear: both; }
In Oracle database we can achieve like this.
CREATE TABLE Student(
StudentID Number(38, 0) not null,
DepartmentID Number(38, 0) not null,
PRIMARY KEY (StudentID, DepartmentID)
);
If you want to use the catch()
of the Observable
you need to use Observable.throw()
method before delegating the error response to a method
import { Injectable } from '@angular/core';_x000D_
import { Headers, Http, ResponseOptions} from '@angular/http';_x000D_
import { AuthHttp } from 'angular2-jwt';_x000D_
_x000D_
import { MEAT_API } from '../app.api';_x000D_
_x000D_
import { Observable } from 'rxjs/Observable';_x000D_
import 'rxjs/add/operator/map';_x000D_
import 'rxjs/add/operator/catch';_x000D_
_x000D_
@Injectable()_x000D_
export class CompareNfeService {_x000D_
_x000D_
_x000D_
constructor(private http: AuthHttp) {}_x000D_
_x000D_
envirArquivos(order): Observable < any > {_x000D_
const headers = new Headers();_x000D_
return this.http.post(`${MEAT_API}compare/arquivo`, order,_x000D_
new ResponseOptions({_x000D_
headers: headers_x000D_
}))_x000D_
.map(response => response.json())_x000D_
.catch((e: any) => Observable.throw(this.errorHandler(e)));_x000D_
}_x000D_
_x000D_
errorHandler(error: any): void {_x000D_
console.log(error)_x000D_
}_x000D_
}
_x000D_
Using Observable.throw()
worked for me
You are mixing razor and aspx syntax,if your view engine is razor just do this:
<button class="btn btn-info" type="button" id="addressSearch"
onclick="location.href='@Url.Action("List", "Search")'">
Let it be simple. It's as simple as
promise
in your service(no need to use then
in service)then
in your controllerDemo. http://plnkr.co/edit/cbdG5p?p=preview
var app = angular.module('plunker', []);
app.factory('myService', function($http) {
return {
async: function() {
return $http.get('test.json'); //1. this returns promise
}
};
});
app.controller('MainCtrl', function( myService,$scope) {
myService.async().then(function(d) { //2. so you can use .then()
$scope.data = d;
});
});
def working_ascii():
"""
G r e e t i n g s !
71, 114, 101, 101, 116, 105, 110, 103, 115, 33
"""
hello = [71, 114, 101, 101, 116, 105, 110, 103, 115, 33]
pmsg = ''.join(chr(i) for i in hello)
print(pmsg)
for i in range(33, 256):
print(" ascii: {0} char: {1}".format(i, chr(i)))
working_ascii()
Android, Python !
When I saw these two keywords together in your question, Kivy is the one which came to my mind first.
Before coming to native Android development in Java using Android Studio, I had tried Kivy. It just awesome. Here are a few advantage I could find out.
Simple to use
With a python basics, you won't have trouble learning it.
Good community
It's well documented and has a great, active community.
Cross platform.
You can develop thing for Android, iOS, Windows, Linux and even Raspberry Pi with this single framework. Open source.
It is a free software
At least few of it's (Cross platform) competitors want you to pay a fee if you want a commercial license.
Accelerated graphics support
Kivy's graphics engine build over OpenGL ES 2 makes it suitable for softwares which require fast graphics rendering such as games.
Now coming into the next part of question, you can't use Android Studio IDE for Kivy. Here is a detailed guide for setting up the development environment.
Create a SQLCLR assembly with external access permission that returns the list of files as a result set. There are many examples how to do this, eg. Yet another TVF: returning files from a directory or Trading in xp_cmdshell for SQLCLR (Part 1) - List Directory Contents.
@Jonathan Sampson i think your solution is wrong if you use multiple @media.
You should use (min-width first):
@media screen and (min-width:400px) and (max-width:900px){
...
}
Had issues using the code in the answer provided by @haynar above (wouldn't play on Chrome), and it seems that one of the more modern ways to ensure it plays is to use the video tag
Example:
<video controls="controls" width="800" height="600"
name="Video Name" src="http://www.myserver.com/myvideo.mov"></video>
This worked like a champ for my .mov file (generated from Keynote) in both Safari and Chrome, and is listed as supported in most modern browsers (The video tag is supported in Internet Explorer 9+, Firefox, Opera, Chrome, and Safari.)
Note: Will work in IE / etc.. if you use MP4 (Mov is not officially supported by those guys)
In SQL*Plus putting SET DEFINE ?
at the top of the script will normally solve this. Might work for Oracle SQL Developer as well.
Try to change #include <gl/glut.h>
to #include "gl/glut.h"
in Visual Studio 2013.
Run this query and you'll probably get what you're looking for:
SELECT table_schema "DB Name",
ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB"
FROM information_schema.tables
GROUP BY table_schema;
This query comes from the mysql forums, where there are more comprehensive instructions available.
Try recreate()
it will cause this Activity to be recreated.
I have the same question as the original poster, Michael.
However I have tried to apply the answers submitted for the original code without success
After some trial and error, here is my version of the code that works (or at least works for me!). And if you look closely, you will note that it is different to the earlier solutions posted.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct arg_struct
{
int arg1;
int arg2;
} *args;
void *print_the_arguments(void *arguments)
{
struct arg_struct *args = arguments;
printf("Thread\n");
printf("%d\n", args->arg1);
printf("%d\n", args->arg2);
pthread_exit(NULL);
return NULL;
}
int main()
{
pthread_t some_thread;
args = malloc(sizeof(struct arg_struct) * 1);
args->arg1 = 5;
args->arg2 = 7;
printf("Before\n");
printf("%d\n", args->arg1);
printf("%d\n", args->arg2);
printf("\n");
if (pthread_create(&some_thread, NULL, &print_the_arguments, args) != 0)
{
printf("Uh-oh!\n");
return -1;
}
return pthread_join(some_thread, NULL); /* Wait until thread is finished */
}
So you can just revert the file that you deleted but remember, If you are working on any type of project with a set project file (like iOS), reverting the file will add it to your system folder structure but not your project file structure. additional steps may be required if you are in this case
Its because you have no BEGIN
and END
statements. You shouldn't be seeing the prints, or errors running this statement, only Statement Completed
(or something like that).
If you are sure you want to remove all commit history, simply delete the .git
directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:
git init
git remote add origin [email protected]:user/repo
now commit your current version of code
git add *
git commit -am 'message'
and finally force the update to GitHub:
git push -f origin master
However, I suggest backing up the history (the .git
folder in the repository) before taking these steps!
I wanted to be able to access my application with the HTML5 mode and a fixed token and then switch to the hashbang method (to keep the token so the user can refresh his page).
URL for accessing my app:
http://myapp.com/amazing_url?token=super_token
Then when the user loads the page:
http://myapp.com/amazing_url?token=super_token#/amazing_url
Then when the user navigates:
http://myapp.com/amazing_url?token=super_token#/another_url
With this I keep the token in the URL and keep the state when the user is browsing. I lost a bit of visibility of the URL, but there is no perfect way of doing it.
So don't enable the HTML5 mode and then add this controller:
.config ($stateProvider)->
$stateProvider.state('home-loading', {
url: '/',
controller: 'homeController'
})
.controller 'homeController', ($state, $location)->
if window.location.pathname != '/'
$location.url(window.location.pathname+window.location.search).replace()
else
$state.go('home', {}, { location: 'replace' })
Assuming you're using jQuery..
var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
var parts = line.split(' ');
output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');
Maybe I don't completely understand the accepted answer so it didn't work for me.
What i did was simply to check if the variable is null, assign it to a known value from my database. Which seems to be similar to the accepted answer whereby you first declare an known value and set it to selected
<select name="department">
<c:forEach var="item" items="${dept}">
<option value="${item.key}">${item.value}</option>
</c:forEach>
</select>
because none of the options are selected, thus item = null
<%
if(item == null){
item = "selectedDept"; //known value from your database
}
%>
This way if the user then selects another option, my IF clause will not catch it and assign to the fixed value that was declared at the start. My concept could be wrong here but it works for me
If you split the filename on underscore and dot, you get an array of 3 strings. Join the first and third string, i.e. with index 0 and 2
$x = '237801_201011221155.xml'
( $x.split('_.')[0] , $x.split('_.')[2] ) -join '.'
Another way to do the same thing:
'237801_201011221155.xml'.split('_.')[0,2] -join '.'
Another solution to handle this case is creating a customized Seekbar, to get ride of converting the real value and SeekBar progress every time:
import android.content.Context
import android.util.AttributeSet
import android.widget.SeekBar
//
// Require SeekBar with range [Min, Max] and INCREMENT value,
// However, Android Seekbar starts from 0 and increment is 1 by default, Android supports min attr on API 26,
// To make a increment & range Seekbar, we can do the following conversion:
//
// seekbar.setMax((Max - Min) / Increment)
// seekbar.setProgress((actualValue - Min) / Increment)
// seekbar.getProgress = Min + (progress * Increment)
//
// The RangeSeekBar is responsible for handling all these logic inside the class.
data class Range(val min: Int, val max: Int, private val defaultIncrement: Int) {
val increment = if ((max - min) < defaultIncrement) 1 else defaultIncrement
}
internal fun Range.toSeekbarMaximum(): Int = (max - min) / increment
class RangeSeekBar: SeekBar, SeekBar.OnSeekBarChangeListener {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
var range: Range = Range(0, 100, 1)
set(value) {
field = value
max = value.toSeekbarMaximum()
}
var value: Int = 0
get() = range.min + progress * range.increment
set(value) {
progress = (value - range.min) / range.increment
field = value
}
var onSeekBarChangeListenerDelegate: OnSeekBarChangeListener? = this
override fun setOnSeekBarChangeListener(l: OnSeekBarChangeListener?) {
onSeekBarChangeListenerDelegate = l
super.setOnSeekBarChangeListener(this)
}
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
onSeekBarChangeListenerDelegate?.onProgressChanged(seekBar, value, fromUser)
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
onSeekBarChangeListenerDelegate?.onStartTrackingTouch(seekBar)
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
onSeekBarChangeListenerDelegate?.onStopTrackingTouch(seekBar)
}
}
Then in your fragment,
// init
range_seekbar.range = Range(10, 110, 10)
range_seekbar.value = 20
// observe value changes
range_seekbar.userChanges().skipInitialValue().subscribe {
println("current value=$it")
}
Keywords: Kotlin, range SeekBar, Rx
Would you accept minor changes to the html?
Something like putting a div tag containing the select tag.
Range("$A$1").Value = "'01/01/13 00:00"
will do it.
Note the single quote; this will defeat automatic conversion to a number type. But is that what you really want? An alternative would be to format the cell to take a date-time value. Then drop the single quote from the string.
Aircoded (but tested on this fiddle)
(function($) {
function startTrigger(e) {
var $elem = $(this);
$elem.data('mouseheld_timeout', setTimeout(function() {
$elem.trigger('mouseheld');
}, e.data));
}
function stopTrigger() {
var $elem = $(this);
clearTimeout($elem.data('mouseheld_timeout'));
}
var mouseheld = $.event.special.mouseheld = {
setup: function(data) {
// the first binding of a mouseheld event on an element will trigger this
// lets bind our event handlers
var $this = $(this);
$this.bind('mousedown', +data || mouseheld.time, startTrigger);
$this.bind('mouseleave mouseup', stopTrigger);
},
teardown: function() {
var $this = $(this);
$this.unbind('mousedown', startTrigger);
$this.unbind('mouseleave mouseup', stopTrigger);
},
time: 750 // default to 750ms
};
})(jQuery);
// usage
$("div").bind('mouseheld', function(e) {
console.log('Held', e);
})
Assuming those methods are in one of the libs it looks like an ordering problem.
When linking libraries into an executable they are done in the order they are declared.
Also the linker will only take the methods/functions required to resolve currently outstanding dependencies. If a subsequent library then uses methods/functions that were not originally required by the objects you will have missing dependencies.
How it works:
Example:
Objects requires:
Lib 1 provides:
Lib 2 provides
If linked like this:
gcc -o plop plop.o -l1 -l2
Then the linker will fail to resolve the read and write symbols.
But if I link the application like this:
gcc -o plop plop.o -l2 -l1
Then it will link correctly. As l2 resolves the BatchRead and BatchWrite dependencies but also adds two new ones (read and write). When we link with l1 next all four dependencies are resolved.
Or use box-shadow if table have collapse
Try this:
^[0-9]{4,6}$
{4,6}
= between 4 and 6 characters, inclusive.
Your code is just fine. The reason you're getting a black screen is because there's nothing on your second view controller.
Try something like:
secondViewController.view.backgroundColor = UIColor.redColor();
Now the view controller it shows should be red.
To actually do something with secondViewController
, create a subclass of UIViewController
and instead of
let secondViewController:UIViewController = UIViewController()
create an instance of your second view controller:
//If using code
let secondViewController = MyCustomViewController.alloc()
//If using storyboard, assuming you have a view controller with storyboard ID "MyCustomViewController"
let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("MyCustomViewController") as UIViewController
You should override by increasing Specificity of your styling. There are different ways of increasing the Specificity. Usage of !important
which effects specificity, is a bad practice because it breaks natural cascading in your style sheet.
Following diagram taken from css-tricks.com will help you produce right specificity for your element based on a points structure. Whichever specificity has higher points, will win. Sounds like a game - doesn't it?
Checkout sample calculations here on css-tricks.com. This will help you understand the concept very well and it will only take 2 minutes.
If you then like to produce and/or compare different specificities by yourself, try this Specificity Calculator: https://specificity.keegan.st/ or you can just use traditional paper/pencil.
For further reading try MDN Web Docs.
All the best for not using !important
.
Use a FULL OUTER JOIN:
select
a.col_a,
a.col_b,
b.col_c
from
(select col_a,col_bfrom tab1) a
join
(select col_a,col_cfrom tab2) b
on a.col_a= b.col_a
Change SMTP=localhost to SMTP=smtp.gmail.com
This is a basic example of how to get the creation date of a file in Java
, using BasicFileAttributes
class:
Path path = Paths.get("C:\\Users\\jorgesys\\workspaceJava\\myfile.txt");
BasicFileAttributes attr;
try {
attr = Files.readAttributes(path, BasicFileAttributes.class);
System.out.println("Creation date: " + attr.creationTime());
//System.out.println("Last access date: " + attr.lastAccessTime());
//System.out.println("Last modified date: " + attr.lastModifiedTime());
} catch (IOException e) {
System.out.println("oops error! " + e.getMessage());
}
While cloning you might be using SSH in the dropdown list. Change it to Https and then clone.
Indeed this is a bug, although intentional for 2 years now.
The problem lies with some unclear specs and the complexity when document.title
and back/forward are involved.
See bug reference on Webkit and Mozilla. Also Opera on the introduction of History API said it wasn't using the title parameter and probably still doesn't.
Currently the 2nd argument of pushState and replaceState — the title of the history entry — isn't used in Opera's implementation, but may be one day.
Potential solution
The only way I see is to alter the title element and use pushState instead:
document.getElementsByTagName('title')[0].innerHTML = 'bar';
window.history.pushState( {} , 'bar', '/bar' );
Here's the mysql reference for cursors. So I'm guessing it's something like this:
DECLARE done INT DEFAULT 0;
DECLARE products_id INT;
DECLARE result varchar(4000);
DECLARE cur1 CURSOR FOR SELECT products_id FROM sets_products WHERE set_id = 1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
REPEAT
FETCH cur1 INTO products_id;
IF NOT done THEN
CALL generate_parameter_list(@product_id, @result);
SET param = param + "," + result; -- not sure on this syntax
END IF;
UNTIL done END REPEAT;
CLOSE cur1;
-- now trim off the trailing , if desired
This is a perfect example of where you should use the macro recorder. Turn on the recorder and set the color of the cells through the UI. Stop the recorder and review the macro. It will generate a bunch of extraneous code, but it will also show you syntax that works for what you are trying to accomplish. Strip out what you don't need and modify (if you need to) what's left.
For horizontal and vertical alignment of text in graphics,
you might want to use the following CSS styles.
In particular, note that dominant-baseline:middle
is probably wrong,
since this is (usually) half way between the top and the baseline,
rather than half way between the top and the bottom.
Also, some some sources (e.g. Mozilla) use dominant-baseline:hanging
instead of
dominant-baseline:text-before-edge
. This is also probably wrong, since
hanging
is designed for Indic scripts.
Of course, if you're using a mixture of Latin, Indic, ideographs
or whatever, you'll probably need to read the documentation.
/* Horizontal alignment */
text.goesleft{text-anchor:end}
text.equalleftright{text-anchor:middle}
text.goesright{text-anchor:start}
/* Vertical alignment */
text.goesup{dominant-baseline:text-after-edge}
text.equalupdown{dominant-baseline:central}
text.goesdown{dominant-baseline:text-before-edge}
text.ruledpaper{dominant-baseline:alphabetic}
Edit: I've just noticed that Mozilla also uses dominant-baseline:baseline
which is definitely wrong: it's not even a recognized value! I assume it's defaulting to the font default, which is alphabetic
, so they got lucky.
More edit: Safari (11.1.2) understands text-before-edge
but not text-after-edge
. It also fails on ideographic
. Great stuff, Apple. So you might be forced to use alphabetic
and allow for descenders after all. Sorry.
Just store the property name in a variable, and use the variable to access the property. Like this:
$name = 'Name';
$obj->$name = 'something';
$get = $obj->$name;
Actually if you are waiting for response from a server it should be done programatically. You may create a progress dialog and dismiss it, but then again that is not "the android way".
Currently the recommended method is to use a DialogFragment :
public class MySpinnerDialog extends DialogFragment {
public MySpinnerDialog() {
// use empty constructors. If something is needed use onCreate's
}
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
_dialog = new ProgressDialog(getActivity());
this.setStyle(STYLE_NO_TITLE, getTheme()); // You can use styles or inflate a view
_dialog.setMessage("Spinning.."); // set your messages if not inflated from XML
_dialog.setCancelable(false);
return _dialog;
}
}
Then in your activity you set your Fragment manager and show the dialog once the wait for the server started:
FragmentManager fm = getSupportFragmentManager();
MySpinnerDialog myInstance = new MySpinnerDialog();
}
myInstance.show(fm, "some_tag");
Once your server has responded complete you will dismiss it:
myInstance.dismiss()
Remember that the progressdialog is a spinner or a progressbar depending on the attributes, read more on the api guide
You just need to a add the path of your PHP
file. In case you are using wamp
or have not installed it on the C drive.
1 - @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
<input type="date" "myDate">
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
var today = new Date();
$('#myDate').val(today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2));
2 - @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
<input type="datatime-local" id="myLocalDataTime" step="1">
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
var today = new Date();
$('#myLocalDataTime').val(today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2)+'T'+today.getHours()+':'+today.getMinutes());
Of course you can, but why do this? You have to include a <script></script>
pair of tags that link to the jQuery web page, i.e.:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
. Then you will load the whole jQuery object just to use one single function, and because jQuery is a JavaScript library which will take time for the computer to upload, it will execute slower than just JavaScript.
You can use ng-change instead of ng-click:
<!doctype html>
<html>
<head>
<script src="http://code.angularjs.org/1.2.3/angular.min.js"></script>
<script>
var app = angular.module('myapp', []);
app.controller('mainController', function($scope) {
$scope.vm = {};
$scope.vm.myClick = function($event) {
alert($event);
}
});
</script>
</head>
<body ng-app="myapp">
<div ng-controller="mainController">
<input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">
</div>
</body>
</html>
If you wanted to load message files for different languages, just use the shared.loader= of catalina.properties... for more info, visit http://theswarmintelligence.blogspot.com/2012/08/use-resource-bundle-messages-files-out.html
Intent i = new Intent(firstactivity.this, secondactivity.class);
startActivity(i);
Minimum crossdomain set I've used for embedding fitted single iframe on a page.
On embedding page (containing iframe):
<iframe frameborder="0" id="sizetracker" src="http://www.hurtta.com/Services/SizeTracker/DE" width="100%"></iframe>
<script type="text/javascript">
// Create browser compatible event handler.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
// Listen for a message from the iframe.
eventer(messageEvent, function(e) {
if (isNaN(e.data)) return;
// replace #sizetracker with what ever what ever iframe id you need
document.getElementById('sizetracker').style.height = e.data + 'px';
}, false);
</script>
On embedded page (iframe):
<script type="text/javascript">
function sendHeight()
{
if(parent.postMessage)
{
// replace #wrapper with element that contains
// actual page content
var height= document.getElementById('wrapper').offsetHeight;
parent.postMessage(height, '*');
}
}
// Create browser compatible event handler.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
// Listen for a message from the iframe.
eventer(messageEvent, function(e) {
if (isNaN(e.data)) return;
sendHeight();
},
false);
</script>
If anyone else is having a nullptr on the searchview variable, I found out that the item setup is a tiny bit different:
old:
android:showAsAction="ifRoom"
android:actionViewClass="android.widget.SearchView"
new:
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"
pre-android x:
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
For more information, it's updated documentation is located here.
Easy method is try os.system
:
import os
text = 'this is text'
os.system("echo %s | grep 't*'" % text)
To verify only first letter is number or character -- For number Character.isDigit(str.charAt(0)) --return true
For character Character.isLetter(str.charAt(0)) --return true
Additionnally to hotkey
's good answer, here is how I choose among the two in practice:
lateinit
is for external initialisation: when you need external stuff to initialise your value by calling a method.
e.g. by calling:
private lateinit var value: MyClass
fun init(externalProperties: Any) {
value = somethingThatDependsOn(externalProperties)
}
While lazy
is when it only uses dependencies internal to your object.
You can use simple jQuery jPut plugin
http://plugins.jquery.com/jput/
<script>
$(document).ready(function(){
var json = [{"name": "name1","score":"30"},{"name": "name2","score":"50"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
jsonData:json,
//ajax_url:"youfile.json", if you want to call from a json file
name:"tbody_template",
});
});
</script>
<div jput="tbody_template">
<tr>
<td>{{name}}</td>
<td>{{score}}</td>
</tr>
</div>
<table>
<tbody id="tbody">
</tbody>
</table>
An alternate to the above solutions is using Aliases for Tables:
UPDATE T1 SET T1.extrasPrice = (SELECT SUM(T2.Price) FROM BookingPitchExtras T2 WHERE T2.pitchID = T1.ID)
FROM BookingPitches T1;