var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);
Try insmod
instead of modprobe. Modprobe
looks in the module directory /lib/modules/uname -r
for all the modules and other
files
For me it's a user privilege issue. I logged-in with sa user and its working fine.
Yes it's possible. Follow these steps:
urllib
has been split up in Python 3
.
The urllib.urlencode()
function is now urllib.parse.urlencode()
,
the urllib.urlopen()
function is now urllib.request.urlopen()
.
Be careful, in some cases clicking on a Form Control or Active X Control will give two different results for the same macro - which should not be the case. I find Active X more reliable.
It may be a little late for this question to be answered, but here is what I found.
I don't want to debate on the fact that nodes does that better than php or not, this is not the point.
The solution is : I haven't found any implementation of socket.io for PHP.
But there are some ways to implement WebSockets. There is this jQuery plugin allowing you to use Websockets while gracefully degrading for non-supporting browsers. On the PHP side, there is this class which seems to be the most widely used for PHP WS servers.
You can do this using generic SQL with group by
:
SELECT C.Content_ID, C.Content_Title, MAX(M.Media_Id)
FROM tbl_Contents C LEFT JOIN
tbl_Media M
ON M.Content_Id = C.Content_Id
GROUP BY C.Content_ID, C.Content_Title
ORDER BY MAX(C.Content_DatePublished) ASC;
Or with a correlated subquery:
SELECT C.Content_ID, C.Contt_Title,
(SELECT M.Media_Id
FROM tbl_Media M
WHERE M.Content_Id = C.Content_Id
ORDER BY M.MEDIA_ID DESC
LIMIT 1
) as Media_Id
FROM tbl_Contents C
ORDER BY C.Content_DatePublished ASC;
Of course, the syntax for limit 1
varies between databases. Could be top
. Or rownum = 1
. Or fetch first 1 rows
. Or something like that.
if (!$('#singlechatpanel-1').css('display') == 'none') {
alert('visible');
}else{
alert('hidden');
}
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
must be
$q = $dbh->prepare("DESCRIBE database.table");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
Simply because this is the inheritance philosophy. And according to the Java language specification, this is how the constructor's body is defined:
ConstructorBody: { ExplicitConstructorInvocationopt BlockStatementsopt }
The first statement of a constructor body may be either
If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments. And so on.. there will be a whole chain of constructors called all the way back to the constructor of Object; "All Classes in the Java platform are Descendants of Object". This thing is called "Constructor Chaining".
Now why is this?
And the reason why Java defined the ConstructorBody in this way, is that they needed to maintain the hierarchy of the object. Remember the definition of the inheritance; It's extending a class. With that being said, you cannot extend something that doesn't exist. The base (the superclass) needs to be created first, then you can derive it (the subclass). That's why they called them Parent and Child classes; you can't have a child without a parent.
On a technical level, a subclass inherits all the members (fields, methods, nested classes) from its parent. And since Constructors are NOT members (They don't belong to objects. They are responsible of creating objects) so they are NOT inherited by subclasses, but they can be invoked. And since at the time of object creation only ONE constructor is executed. So how do we guarantee the creation of the superclass when you create the subclass object? Thus the concept of "constructor chaining"; so we have the ability to invoke other constructors (i.e. super) from within the current constructor. And Java required this invocation to be the FIRST line in the subclass constructor to maintain the hierarchy and guarantee it. They assume that if you don't explicitly create the parent object FIRST (like if you forgot about it), they will do it implicitly for you.
This check is done during compilation. But I'm not sure what would happen on runtime, what kind of runtime error we would get, IF Java doesn't throw a compile-error when we explicitly try to execute a base constructor from within a subclass's constructor in the middle of its body and not from the very first line ...
Take a look at http://commons.apache.org/email/ they have an HtmlEmail class that probably does exactly what you need.
SQL 2003 standard defines the format as follows:
<unquoted timestamp string> ::= <unquoted date string> <space> <unquoted time string>
<date value> ::= <years value> <minus sign> <months value> <minus sign> <days value>
<time value> ::= <hours value> <colon> <minutes value> <colon> <seconds value>
There are some definitions in between that just link back to these, but in short YYYY-MM-DD HH:MM:SS
with optional .mmm
milliseconds is required to work on all SQL databases.
Bootstrap datepicker (the first result from bootstrap datepickcer search) has a method to get the selected date.
https://bootstrap-datepicker.readthedocs.io/en/latest/methods.html#getdate
getDate: Returns a localized date object representing the internal date object of the first datepicker in the selection. For multidate pickers, returns the latest date selected.
$('.datepicker').datepicker("getDate")
or
$('.datepicker').datepicker("getDate").valueOf()
I usually store phone numbers as a BIGINT in E164 format.
E164 never start with a 0, with the first few digits being the country code.
+441234567890
+44 (0)1234 567890
01234 567890
etc. would be stored as 441234567890
.
I'm currently experimenting with canvas and pixels... I'm finding this logic works out for me better.
add to offset the 'tint' value
var grey = (r + g + b) / 3;
var grey2 = (new_r + new_g + new_b) / 3;
var dr = grey - grey2 * 1;
var dg = grey - grey2 * 1
var db = grey - grey2 * 1;
tint_r = new_r + dr;
tint_g = new_g + dg;
tint_b = new_b _ db;
or something like that...
I had the same message with a totally different cause: the wsock32.dll
was not found. The ::socket(PF_INET, SOCK_STREAM, 0);
call kept returning an INVALID_SOCKET
but the reason was that the winsock dll was not loaded.
In the end I launched Sysinternals' process monitor and noticed that it searched for the dll 'everywhere' but didn't find it.
Silent failures are great!
Download python 3.6.0 from https://www.python.org/downloads/release/python-360/
Install it as a normal package.
Run cd /Library/Frameworks/Python.framework/Version
Run ls
command and all installed Python versions will be visible here.
Run sudo rm -rf 3.7
Check the version now by python3 -V
and it will be 3.6 now.
You can also use df.columns[df.columns.str.contains(pat = 'spike')]
data = {'spike-2': [1,2,3], 'hey spke': [4,5,6], 'spiked-in': [7,8,9], 'no': [10,11,12]}
df = pd.DataFrame(data)
colNames = df.columns[df.columns.str.contains(pat = 'spike')]
print(colNames)
This will output the column names: 'spike-2', 'spiked-in'
More about pandas.Series.str.contains.
Check that your index is really datetime
, not str
Can be helpful:
data.index = pd.to_datetime(data['Index']).values
The first thing i would suggest is to use the correct configuration for predefined descriptors.
<project>
[...]
<build>
[...]
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.3</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
[...]
</project>
To configure the main class you need to know the package and name of the class you would like to use which should be given into <mainClass>...</mainClass>
parameter.
Furthermore i recommend to stop using Maven 2 and move to Maven 3 instead.
If you're using org.codehaus.jackson, this has been possible since 1.6. You can convert a JsonNode to a POJO with ObjectMapper#readValue
: http://jackson.codehaus.org/1.9.4/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(org.codehaus.jackson.JsonNode, java.lang.Class)
ObjectMapper mapper = new ObjectMapper();
JsonParser jsonParser = mapper.getJsonFactory().createJsonParser("{\"foo\":\"bar\"}");
JsonNode tree = jsonParser.readValueAsTree();
// Do stuff to the tree
mapper.readValue(tree, Foo.class);
I did it many times. To bypass the JavaScript warning, I add two parens:
if ((result = get_something())) { }
You should avoid it, if you really want to use it, write a comment above it saying what you are doing.
Make sure Match Case is selected with Use Regular Expression so this matches. [A-Z]* If match case is not selected, this matches all letters.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(response.GetResponseStream());
string rootNode = XmlDoc.ChildNodes[0].Name;
This solution will first resize the columns based on column data, if the resized width is smaller than header size, it will resize columns to at least fit the header. This is a pretty ugly solution, but it works.
lstContacts.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
colFirstName.Width = (colFirstName.Width < 60 ? 60 : colFirstName.Width);
colLastName.Width = (colLastName.Width < 61 ? 61 : colLastName.Width);
colPhoneNumber.Width = (colPhoneNumber.Width < 81 ? 81 : colPhoneNumber.Width);
colEmail.Width = (colEmail.Width < 40 ? 40 : colEmail.Width);
lstContacts is the ListView. colFirstName is a column, where 60 is the width required to fit the title. Etc.
For anyone trying to solve this on a managed MySQL instance (in my case on AWS RDS), the easiest way was to modify the parameter group and set the server character set and collation to be utf8mb4
and utf8mb4_bin
, respectively. After rebooting the server, a quick query verifies the settings for system databases and any newly created ones:
SELECT * FROM information_schema.SCHEMATA S;
I think you don't have the python-opencv
package.
I had the exact same problem and
sudo apt-get install python-opencv
solved the issue for me.
you can install opencv from the following link https://www.learnopencv.com/install-opencv3-on-ubuntu/ It works for me . apt-get install doesnt contain many packages of opencv
Simply add additional characters like "=" or any other and make it a multiple of 4 before you try decoding the target string value. Something like;
if len(value) % 4 != 0: #check if multiple of 4
while len(value) % 4 != 0:
value = value + "="
req_str = base64.b64decode(value)
else:
req_str = base64.b64decode(value)
ALTER TABLE mytable ALTER COLUMN mycolumn newtype
Beware of the limitations of the ALTER COLUMN clause listed in the article
This error can happen if you are instantiating a fragment that somehow can't be instantiated:
Fragment myFragment = MyFragment.NewInstance();
public classs MyFragment extends Fragment {
public void onCreate() {
// Some error here, or anywhere inside the class is preventing it from being instantiated
}
}
In my case, i have met this when i tried to use:
private String loading = getString(R.string.loading);
In Ubuntu with php7.3:
sudo apt install php7.3-soap
sudo service apache2 restart
Children inherit opacity. It'd be weird and inconvenient if they didn't.
You can use a translucent PNG file for your background image, or use an RGBa (a for alpha) color for your background color.
Example, 50% faded black background:
<div style="background-color:rgba(0, 0, 0, 0.5);">_x000D_
<div>_x000D_
Text added._x000D_
</div>_x000D_
</div>
_x000D_
I use laravel 7.x and I used this as a workaround:->get()->pluck('id')->toArray();
it gives back an array of ids [50,2,3]
and this is the whole query I used:
$article_tags = DB::table('tags')
->join('taggables', function ($join) use ($id) {
$join->on('tags.id', '=', 'taggables.tag_id');
$join->where([
['taggable_id', '=', $id],
['taggable_type','=','article']
]);
})->select('tags.id')->get()->pluck('id')->toArray();
Java 8: Base64 available:
MessageDigest md = MessageDigest.getInstance( "SHA-512" );
md.update( inbytes );
byte[] aMessageDigest = md.digest();
String outEncoded = Base64.getEncoder().encodeToString( aMessageDigest );
return( outEncoded );
That's strange, it definitely works for me:
from matplotlib import pyplot as plt
plt.figure(figsize = (20,2))
plt.imshow(random.rand(8, 90), interpolation='nearest')
I am using the "MacOSX" backend, btw.
Call sys.exit
.
Easiest way is probably using command status; In the output you'll find database, user, host and port:
mysql> status;
--------------
mysql Ver 8.0.13 for Win64 on x86_64 (MySQL Community Server - GPL)
Connection id: 43
Current database: mysql
Current user: user@localhost
SSL: Cipher in use is DHE-RSA-AES128-GCM-SHA256
Using delimiter: ;
Server version: 8.0.13 MySQL Community Server - GPL
Protocol version: 10
Connection: localhost via TCP/IP
Server characterset: utf8mb4
Db characterset: utf8mb4
Client characterset: cp852
Conn. characterset: cp852
TCP port: 3306
Uptime: 3 hours 32 min 40 sec
Threads: 3 Questions: 197 Slow queries: 0 Opens: 214 Flush tables: 2 Open tables: 190 Queries per second avg: 0.015
--------------
Here is a simple explanation. A static method is associated with a class while an instance method is associated with a particular object. Overrides allow calling the different implementation of the overridden methods associated with the particular object. So it is counter-intuitive to override static method which is not even associated with objects but the class itself in the first place. So static methods cannot be overridden based on what object is calling it, it will always be associated with the class where it was created.
For footer change from position: relative;
to position:fixed;
footer {
background-color: #333;
width: 100%;
bottom: 0;
position: fixed;
}
Example: http://jsfiddle.net/a6RBm/
For Java 8 you can use the following command line to get the heap space utilization in kB:
jstat -gc <PID> | tail -n 1 | awk '{split($0,a," "); sum=a[3]+a[4]+a[6]+a[8]; print sum}'
The command basically sums up:
You may also want to include the metaspace and the compressed class space utilization. In this case you have to add a[10] and a[12] to the awk sum.
You simply make each item within the array an array.
var x = new Array(10);_x000D_
_x000D_
for (var i = 0; i < x.length; i++) {_x000D_
x[i] = new Array(3);_x000D_
}_x000D_
_x000D_
console.log(x);
_x000D_
Converting to another palette is a far superior way to do this. There's a reason they do that: other palettes are 'perceptual' - that is, they put similar seeming colors close together, and adjusting one variable changes the color in a predictable manner. None of that is true for RGB, where there's no obvious relationship between colors that "go well together".
Using plain javascript
var isEmpty = document.getElementById('cartContent').innerHTML === "";
And if you are using jquery it can be done like
var isEmpty = $("#cartContent").html() === "";
You can do this:
select t2.*
from t1
join t2 on t2.url = 'site.com/path/' + CAST(t1.id AS VARCHAR(10)) + '/more'
where t1.id > 9000
Pay attention to CAST(t1.id AS VARCHAR(10))
.
To put it in another way, can we replicate the appearance of these text views without using the android:textAppearance attribute?
Like biegleux already said:
If you want to use the small, medium or large value on any text in your Android app, you can just create a dimens.xml
file in your values
folder and define the text size there with the following 3 lines:
<dimen name="text_size_small">14sp</dimen>
<dimen name="text_size_medium">18sp</dimen>
<dimen name="text_size_large">22sp</dimen>
Here is an example for a TextView with large text from the dimens.xml
file:
<TextView
android:id="@+id/hello_world"
android:text="hello world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/text_size_large"/>
None of the above solutions address the generic intention of the original request. What if we don't know the id of the anchor? What if it doesn't have an id? What if it doesn't even have an href parameter (e.g. prev/next icon in a carousel)? What if we want to apply the action to multiple anchors with different models in an agnostic fashion? Here's an example that does something instead of a click, then later simulates the click (for any anchor or other tag):
var clicker = null;
$('a').click(function(e){
clicker=$(this); // capture the clicked dom object
/* ... do something ... */
e.preventDefault(); // prevent original click action
});
clicker[0].click(); // this repeats the original click. [0] is necessary.
a = [4,2,3,1,5,6]
index = dict((y,x) for x,y in enumerate(a))
try:
a_index = index[7]
except KeyError:
print "Not found"
else:
print "found"
This will only be a good idea if a doesn't change and thus we can do the dict() part once and then use it repeatedly. If a does change, please provide more detail on what you are doing.
Explicitly Target IE versions without hacks using HTML and CSS
Use this approach if you don't want hacks in your CSS. Add a browser-unique class to the <html>
element so you can select based on browser later.
Example
<!doctype html>
<!--[if IE]><![endif]-->
<!--[if lt IE 7 ]> <html lang="en" class="ie6"> <![endif]-->
<!--[if IE 7 ]> <html lang="en" class="ie7"> <![endif]-->
<!--[if IE 8 ]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9 ]> <html lang="en" class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html lang="en"><!--<![endif]-->
<head></head>
<body></body>
</html>
Then in your CSS you can very strictly access your target browser.
Example
.ie6 body {
border:1px solid red;
}
.ie7 body {
border:1px solid blue;
}
For more information check out http://html5boilerplate.com/
Target IE versions with CSS "Hacks"
More to your point, here are the hacks that let you target IE versions.
Use "\9" to target IE8 and below.
Use "*" to target IE7 and below.
Use "_" to target IE6.
Example:
body {
border:1px solid red; /* standard */
border:1px solid blue\9; /* IE8 and below */
*border:1px solid orange; /* IE7 and below */
_border:1px solid blue; /* IE6 */
}
Update: Target IE10
IE10 does not recognize the conditional statements so you can use this to apply an "ie10" class to the <html>
element
<!doctype html>
<html lang="en">
<!--[if !IE]><!--><script>if (/*@cc_on!@*/false) {document.documentElement.className+=' ie10';}</script><!--<![endif]-->
<head></head>
<body></body>
</html>
For self-containing Maven project I usually installing all external jar dependencies into project's repository. For SQL Server JDBC driver you can do:
local-repo
in your Maven projectsqljdbc42.jar
into local-repo
folderlocal-repo
folder run mvn deploy:deploy-file -Dfile=sqljdbc42.jar -DartifactId=sqljdbc42 -DgroupId=com.microsoft.sqlserver -DgeneratePom=true -Dpackaging=jar -Dversion=6.0.7507.100 -Durl=file://.
to deploy JAR into local repository (stored together with your code in SCM)sqljdbc42.jar
and downloaded files can be deletedpom.xml
and add reference to project's local repository:
xml
<repositories>
<repository>
<id>parent-local-repository</id>
<name>Parent Local repository</name>
<layout>default</layout>
<url>file://${basedir}/local-repo</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
Now you can run your project everywhere without any additional configurations or installations.try a negative margin.
margin-top: -10px; /* as an example */
We don't stop or kill a thread rather we do Thread.currentThread().isInterrupted().
public class Task1 implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
................
................
................
................
}
}
}
in main we will do like this:
Thread t1 = new Thread(new Task1());
t1.start();
t1.interrupt();
Well I agree with Ryan Conrad on how to do it in eclipse, have you ensured you have changed your manifest.xml?
<uses-sdk android:minSdkVersion="3" />
<uses-sdk android:targetSdkVersion="8" />
Be sure that Initial View Controller is set
Try the following on the command prompt:
>adb remount
>adb push framework-res_old.apk /system/framework-res.apk
you can modify the gatekeeper settings by running the following command
To disable to allow apps from anywhere to be installed use the following command in terminal ::
sudo spctl --master-disable
To re-enable use the following command
sudo spctl --master-enable
I looked and found a cross browser way:
function myFunction(){_x000D_
if(window.innerWidth !== undefined && window.innerHeight !== undefined) { _x000D_
var w = window.innerWidth;_x000D_
var h = window.innerHeight;_x000D_
} else { _x000D_
var w = document.documentElement.clientWidth;_x000D_
var h = document.documentElement.clientHeight;_x000D_
}_x000D_
var txt = "Page size: width=" + w + ", height=" + h;_x000D_
document.getElementById("demo").innerHTML = txt;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body onresize="myFunction()" onload="myFunction()">_x000D_
<p>_x000D_
Try to resize the page._x000D_
</p>_x000D_
<p id="demo">_x000D_
_x000D_
</p>_x000D_
</body>_x000D_
</html>
_x000D_
When parsing its configuration file, the expression ${MY_HOME}
will be expanded to the value of the system property named MY_HOME
, not the system environment variable. There's a difference between the two.
To achieve this in a clean way, you'll have to add something like this to the JVM invocation line:
-DMY_HOME=$MY_HOME
That would define the Java system property MY_HOME
to contain the value of the environment variable MY_HOME
.
I had the same problem too, but I found a solution.
from tkinter import *
# must add
root = Tk()
root.title("Calculator")
root.iconbitmap(r"image/icon.ico")
root.mainloop()
In the example, what python needed is an icon file, so when you dowload an icon as .png
it won't work cause it needs an .ico
file. So you need to find converters to convert your icon from png
to ico
.
Sets new value for backgroundPosition
on the carousel
div when a li in the submenu
div is hovered. Removes the backgroundPosition
when hovering ends and resets backgroundPosition
to old value.
$('#submenu li').hover(function() {
if ($('#carousel').data('oldbackgroundPosition')==undefined) {
$('#carousel').data('oldbackgroundPosition', $('#carousel').css('backgroundPosition'));
}
$('#carousel').css('backgroundPosition', [enternewvaluehere]);
},
function() {
var reset = '';
if ($('#carousel').data('oldbackgroundPosition') != undefined) {
reset = $('#carousel').data('oldbackgroundPosition');
$('#carousel').removeData('oldbackgroundPosition');
}
$('#carousel').css('backgroundPosition', reset);
});
In my case:
My protocol definition
@protocol MyProtocol
- (void)Method;
@end
and I forgot implements the delegate methods.
hope it could help someone.
Update: As of July 2013 this project is no longer maintained. The author suggests using pyenv. (pyenv does not have built-in support for virtualenv, but plays nice with it.)
Pythonbrew is a version manager for python and comes with support for virtualenv.
After installing pythonbrew and a python-version using venvs is really easy:
# Initializes the virtualenv
pythonbrew venv init
# Create a virtual/sandboxed environment
pythonbrew venv create mycoolbundle
# Use it
pythonbrew venv use mycoolbundle
Okay ... so these posts are old as compared to now, but insertion order is needed depending on your need or application requirements, so just use the right type of collection. For most part, it is not needed, but in a situation where you need to utilize objects in the order they were stored, I see a definite need. I think order matters when you are creating for instance a wizard or a flow engine or something of that nature where you need to go from state to state or something. In that sense you can read off stuff from the list without having it keep track of what you need next or traverse a list to find what you want. It does help with performance in that sense. It does matter or else these collections would not make much sense.
No, such method does not exist, but is trivial to write:
func contains(s []int, e int) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
You can use a map if that lookup is an important part of your code, but maps have cost too.
Gradle cache is located at
%USERPROFILE%\.gradle\caches
~/.gradle/caches/
You can browse to these directory and manually delete it or run
rm -rf $HOME/.gradle/caches/
on UNIX system. Run this command will also force to download dependencies.
Clear the Android build cache of current project
NOTE: Android Studio's File > Invalidate Caches / Restart
doesn't clear the Android build cache, so you'll have to clean it separately.
On Windows:
gradlew cleanBuildCache
On Mac or UNIX:
./gradlew cleanBuildCache
Run it with -e
or set -e
at the top.
Also look at set -u
.
Expand your one liner into multiple lines. Then it becomes easy:
f.write(re.split("Tech ID:|Name:|Account #:",line)[-1])
parts = re.split("Tech ID:|Name:|Account #:",line)
wanted_part = parts[-1]
wanted_part_stripped = wanted_part.strip()
f.write(wanted_part_stripped)
Most SSL certificates are bound to the hostname of the machine and not the ip address.
You might get a better answer if you ask this question on serverfault.com
Your applets will run.
If they are still not running then you have to add that website name in exception site list of Security tab of Java in Control panel.
Here is a simple function to do this for you:
def precision(num,x):
return "{0:.xf}".format(round(num))
Here, num is the decimal number. x is the decimal up to where you want to round a floating number.
The advantage over other implementation is that it can fill zeros at the right end of the decimal to make a deciaml number up to x decimal places.
Example 1:
precision(10.2, 9)
will return
10.200000000 (up to 9 decimal points)
Example 2:
precision(10.2231, 2)
will return
10.22 (up to two decimal points)
When I went to Google fonts all they gave me were true type font files .ttf
and didn't explain at all how to use the @font-face to include them into my document. I tried the web font generator from font squirrel too, which just kept running the loading gif and not working... I then found this site -
I had great success using the following method:
I selected the Add Fonts button, leaving the default options, added all of my .ttf
that Google gave me for Open Sans
(which was like 10, I chose a lot of options...).
Then I selected the Convert button.
Heres the best part!
They gave me a zip file with all the font format files I selected, .ttf
, .woff
and .eot
. Inside that zip file they had a demo.html
file that I just double clicked on and it opened up a web page in my browser showing me example usages of all the different css font options, how to implement them, and what they looked like etc.
@font-face
I still didn't know at this point how to include the fonts into my stylesheet properly using @font-face
but then I noticed that this demo.html
came with it's own stylesheet in the zip as well. I opened the stylesheet and it showed how to bring in all of the fonts using @font-face
so I was able to quickly, and easily, copy paste this into my project -
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-BoldItalic.eot');
src: url('fonts/Open_Sans/OpenSans-BoldItalic.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-BoldItalic.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-BoldItalic.ttf') format('truetype');
font-weight: bold;
font-style: italic;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-LightItalic.eot');
src: url('fonts/Open_Sans/OpenSans-LightItalic.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-LightItalic.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-LightItalic.ttf') format('truetype');
font-weight: 300;
font-style: italic;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-SemiBold.eot');
src: url('fonts/Open_Sans/OpenSans-SemiBold.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-SemiBold.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-SemiBold.ttf') format('truetype');
font-weight: 600;
font-style: normal;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-Regular.eot');
src: url('fonts/Open_Sans/OpenSans-Regular.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-Regular.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-Regular.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-Light.eot');
src: url('fonts/Open_Sans/OpenSans-Light.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-Light.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-Light.ttf') format('truetype');
font-weight: 300;
font-style: normal;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-Italic.eot');
src: url('fonts/Open_Sans/OpenSans-Italic.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-Italic.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-Italic.ttf') format('truetype');
font-weight: normal;
font-style: italic;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-SemiBoldItalic.eot');
src: url('fonts/Open_Sans/OpenSans-SemiBoldItalic.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-SemiBoldItalic.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-SemiBoldItalic.ttf') format('truetype');
font-weight: 600;
font-style: italic;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-ExtraBold.eot');
src: url('fonts/Open_Sans/OpenSans-ExtraBold.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-ExtraBold.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-ExtraBold.ttf') format('truetype');
font-weight: 800;
font-style: normal;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.eot');
src: url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.ttf') format('truetype');
font-weight: 800;
font-style: italic;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-Bold.eot');
src: url('fonts/Open_Sans/OpenSans-Bold.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-Bold.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-Bold.ttf') format('truetype');
font-weight: bold;
font-style: normal;
}
The demo.html
also had it's own inline stylesheet that was interesting to take a look at, though I am familiar with working with font weights and styles once they are included so I didn't need it much. For an example of how to implement a font style onto an html element for reference purposes you could use the following method in a similar case to mine after @font-face
has been used properly -
html, body{
margin: 0;
font-family: 'Open Sans';
}
.banner h1{
font-size: 43px;
font-weight: 700;
}
.banner p{
font-size: 24px;
font-weight: 300;
font-style: italic;
}
For not very sharp eyes like mine, I had href
instead of routerLink
, took me a few searches to figure that out #facepalm.
to answer the second:
make the column unique and catch the exception if it's set to the same value.
In views with {{}}
and/or ng-model, Angular is setting up $watch()
es for you behind the scenes.
By default $watch
compares by reference. If you set the third parameter to $watch
to true
, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:
$scope.$watch('myModel', function() { ... }, true);
Update: Angular v1.2 added a new method for this, `$watchCollection():
$scope.$watchCollection('myModel', function() { ... });
Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.
While there are suggestions above for "doing it the python way", if one wants to really have a logic based on EOF, then I suppose using exception handling is the way to do it --
try:
line = raw_input()
... whatever needs to be done incase of no EOF ...
except EOFError:
... whatever needs to be done incase of EOF ...
Example:
$ echo test | python -c "while True: print raw_input()"
test
Traceback (most recent call last):
File "<string>", line 1, in <module>
EOFError: EOF when reading a line
Or press Ctrl-Z at a raw_input()
prompt (Windows, Ctrl-Z Linux)
What @BoltClock mentioned are pretty solid. And Here I just want to add several more solutions for this problem. check this w3c_collapsing margin. The green parts are the potential thought how this problem can be solved.
Solution 1
Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children).
that means I can add float:left
to either #outer
or #inner
demo1.
also notice that float
would invalidate the auto
in margin.
Solution 2
Margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.
other than visible
, let's put overflow: hidden
into #outer
. And this way seems pretty simple and decent. I like it.
#outer{
width: 500px;
height: 200px;
background: #FFCCCC;
margin: 50px auto;
overflow: hidden;
}
#inner {
background: #FFCC33;
height: 50px;
margin: 50px;
}
Solution 3
Margins of absolutely positioned boxes do not collapse (not even with their in-flow children).
#outer{
width: 500px;
height: 200px;
background: #FFCCCC;
margin: 50px auto;
position: absolute;
}
#inner{
background: #FFCC33;
height: 50px;
margin: 50px;
}
or
#outer{
width: 500px;
height: 200px;
background: #FFCCCC;
margin: 50px auto;
position: relative;
}
#inner {
background: #FFCC33;
height: 50px;
margin: 50px;
position: absolute;
}
these two methods will break the normal flow of div
Solution 4
Margins of inline-block boxes do not collapse (not even with their in-flow children).
is the same as @enderskill
Solution 5
The bottom margin of an in-flow block-level element always collapses with the top margin of its next in-flow block-level sibling, unless that sibling has clearance.
This has not much work to do with the question since it is the collapsing margin between siblings. it generally means if a top-box has margin-bottom: 30px
and a sibling-box has margin-top: 10px
. The total margin between them is 30px
instead of 40px
.
Solution 6
The top margin of an in-flow block element collapses with its first in-flow block-level child's top margin if the element has no top border, no top padding, and the child has no clearance.
This is very interesting and I can just add one top border line
#outer{
width: 500px;
height: 200px;
background: #FFCCCC;
margin: 50px auto;
border-top: 1px solid red;
}
#inner {
background: #FFCC33;
height: 50px;
margin: 50px;
}
And Also <div>
is block-level in default, so you don't have to declare it on purpose. Sorry for not being able to post more than 2 links and images due to my novice reputation. At least you know where the problem comes from next time you see something similar.
The sequences in postgresql are transaction safe. So you can use the
currval(sequence)
currval
Return the value most recently obtained by nextval for this sequence in the current session. (An error is reported if nextval has never been called for this sequence in this session.) Notice that because this is returning a session-local value, it gives a predictable answer even if other sessions are executing nextval meanwhile.
I am using searchform.php
and search.php
files as already mentioned, but here I provide the actual code.
Creating a Search Page codex
page helps here and #Creating_a_Search_Page_Template
shows the search query.
In my case I pass the $search_query
arguments to the WP_Query Class
(which can determine if is search query!). I then run The Loop to display the post information I want to, which in my case is the the_permalink and the_title
.
Search box form:
<form class="search" method="get" action="<?php echo home_url(); ?>" role="search">
<input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" />
<button type="submit" role="button" class="btn btn-default right"/><span class="glyphicon glyphicon-search white"></span></button>
</form>
search.php
template file:
<?php
global $query_string;
$query_args = explode("&", $query_string);
$search_query = array();
foreach($query_args as $key => $string) {
$query_split = explode("=", $string);
$search_query[$query_split[0]] = urldecode($query_split[1]);
} // foreach
$the_query = new WP_Query($search_query);
if ( $the_query->have_posts() ) :
?>
<!-- the loop -->
<ul>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
</ul>
<!-- end of the loop -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
When you talked about "Hash Table will place a new entry into the 'next available' bucket if the new Key entry collides with another.", you are talking about the Open addressing strategy of Collision resolution of hash table.
There are several strategies for hash table to resolve collision.
First kind of big method require that the keys (or pointers to them) be stored in the table, together with the associated values, which further includes:
Another important method to handle collision is by Dynamic resizing, which further has several ways:
EDIT: the above are borrowed from wiki_hash_table, where you should go to have a look to get more info.
This will match a single non-ASCII character:
[^\x00-\x7F]
This is a valid PCRE (Perl-Compatible Regular Expression).
You can also use the POSIX shorthands:
[[:ascii:]]
- matches a single ASCII char[^[:ascii:]]
- matches a single non-ASCII char[^[:print:]]
will probably suffice for you.**
We don't have any way to add volume in running container, but to achieve this objective you may use the below commands:
Copy files/folders between a container and the local filesystem:
docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH
docker cp [OPTIONS] SRC_PATH CONTAINER:DEST_PATH
For reference see:
/*working only in ipad portrait device*/
@media only screen and (width: 768px) and (height: 1024px) and (orientation:portrait) {
body{
background: red !important;
}
}
/*working only in ipad landscape device*/
@media all and (width: 1024px) and (height: 768px) and (orientation:landscape){
body{
background: green !important;
}
}
In the media query of specific devices, please use '!important' keyword to override the default CSS. Otherwise that does not change your webpage view on that particular devices.
This question is very general and there are a couple of assumptions I'll make to simplify it a bit. We'll assume that you want to update your master
branch.
If you haven't made any changes locally, you can use git pull
to bring down any new commits and add them to your master
.
git pull origin master
If you have made changes, and you want to avoid adding a new merge commit, use git pull --rebase
.
git pull --rebase origin master
git pull --rebase
will work even if you haven't made changes and is probably your best call.
//create activity object to get activity from Activity class for use to content resolver
private final Activity ActivityObj;
//create constructor with ActivityObj to get activity from Activity class
public RecyclerViewAdapterClass(Activity activityObj) {
this.ActivityObj = activityObj;
}
ActivityObj.getContentResolver(),.....,.....,null);
As of PostgreSQL 9.4, you can use the ?
operator:
select info->>'name' from rabbits where (info->'food')::jsonb ? 'carrots';
You can even index the ?
query on the "food"
key if you switch to the jsonb type instead:
alter table rabbits alter info type jsonb using info::jsonb;
create index on rabbits using gin ((info->'food'));
select info->>'name' from rabbits where info->'food' ? 'carrots';
Of course, you probably don't have time for that as a full-time rabbit keeper.
Update: Here's a demonstration of the performance improvements on a table of 1,000,000 rabbits where each rabbit likes two foods and 10% of them like carrots:
d=# -- Postgres 9.3 solution
d=# explain analyze select info->>'name' from rabbits where exists (
d(# select 1 from json_array_elements(info->'food') as food
d(# where food::text = '"carrots"'
d(# );
Execution time: 3084.927 ms
d=# -- Postgres 9.4+ solution
d=# explain analyze select info->'name' from rabbits where (info->'food')::jsonb ? 'carrots';
Execution time: 1255.501 ms
d=# alter table rabbits alter info type jsonb using info::jsonb;
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
Execution time: 465.919 ms
d=# create index on rabbits using gin ((info->'food'));
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
Execution time: 256.478 ms
if you are using pycharm go to settings and in project interpreter sub-tab click on "+" sign next to list and in the search bar in there search name "scipy" and install the package.
In file php.ini you should try this for all errors:
display_errors = On
Location file is:
For multiple plots in a single pdf file you can use PdfPages
In the plotGraph
function you should return the figure and than call savefig
of the figure object.
------ plotting module ------
def plotGraph(X,Y):
fig = plt.figure()
### Plotting arrangements ###
return fig
------ plotting module ------
----- mainModule ----
from matplotlib.backends.backend_pdf import PdfPages
plot1 = plotGraph(tempDLstats, tempDLlabels)
plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
pp = PdfPages('foo.pdf')
pp.savefig(plot1)
pp.savefig(plot2)
pp.savefig(plot3)
pp.close()
You can try the following to retrieve the name of a function you defined (does not work for built-in functions though):
import re
def retrieve_name(func):
return re.match("<function\s+(\w+)\s+at.*", str(func)).group(1)
def foo(x):
return x**2
print(retrieve_name(foo))
# foo
If you look close, you'll see the difference:
/var/run/mysqld/mysqld.sock
/var/run/mysqld/mysql.sock
You'll have to adjust the one or the other.
As @Malvineous said, It's not professional but a work-around to use the Find/Replace method to remove trailing space (below including tab U+0009 and whitespace U+0020).
Just press Ctrl + F (or command + F)
[\t ][\t ]*$
extra:
For removing leading space, find ^[\t ][\t ]*
instead of [\t ][\t ]*$
For removing blank lines, find ^\s*$\r?\n
For connecting to a sql server database via Windows authentication basically needs which server you want to connect , what is your database name , Integrated Security info and provider name.
Basically this works:
<connectionStrings>
<add name="MyConnectionString"
connectionString="data source=ServerName;
Initial Catalog=DatabaseName;Integrated Security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Setting Integrated Security field true means basically you want to reach database via Windows authentication, if you set this field false Windows authentication will not work.
It is also working different according which provider you are using.
SqlClient both Integrated Security=true; or IntegratedSecurity=SSPI; is working.
OleDb it is Integrated Security=SSPI;
Integrated Security=true throws an exception when used with the OleDb provider.
#include"stdio.h"//rmv coding for randam number access
#include"conio.h"
#include"time.h"
void main()
{
time_t t;
int rmvivek;
srand(time(&t));
rmvivek=1;
while(rmvivek<=5)
{
printf("%c\t",rand()%10);
rmvivek++;
}
getch();
}
Use the Figure.savefig()
method, like so:
ax = s.hist() # s is an instance of Series
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')
It doesn't have to end in pdf
, there are many options. Check out the documentation.
Alternatively, you can use the pyplot
interface and just call the savefig
as a function to save the most recently created figure:
import matplotlib.pyplot as plt
s.hist()
plt.savefig('path/to/figure.pdf') # saves the current figure
var x = y !== undefined ? y : 1;
Note that var x = y || 1;
would assign 1
for any case where y
is falsy (e.g. false
, 0
, ""
), which may be why it "didn't work" for you. Also, if y
is a global variable, if it's truly not defined you may run into an error unless you access it as window.y
.
As vol7ron suggests in the comments, you can also use typeof
to avoid the need to refer to global vars as window.<name>
:
var x = typeof y != "undefined" ? y : 1;
this is a mysql function example. I hope it helps. (I have not tested it yet, but should work)
DROP FUNCTION IF EXISTS F_TEST //
CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR
BEGIN
/*DECLARE VALUES YOU MAY NEED, EXAMPLE:
DECLARE NOM_VAR1 DATATYPE [DEFAULT] VALUE;
*/
DECLARE NAME_FOUND VARCHAR DEFAULT "";
SELECT EMPLOYEE_NAME INTO NAME_FOUND FROM TABLE_NAME WHERE ID = PID;
RETURN NAME_FOUND;
END;//
I got the same error in this code:
var articulos_en_almacen = xx.IV00102.Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();
this was the exactly error:
System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[conector_gp.Models.almacenes_por_sucursal])' method, and this method cannot be translated into a store expression.'
I solved this way:
var articulos_en_almacen = xx.IV00102.ToList().Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();
I added a .ToList() before my table, this decouple the Entity and linq code, and avoid my next linq expression be translated
NOTE: this solution isn't optimal, because avoid entity filtering, and simply loads all table into memory
When you create more than one instance of MyClass , you will still only have only one instance of publicMethod in memory but in case of privilegedMethod you will end up creating lots of instances and staticMethod has no relationship with an object instance.
That's why prototypes save memory.
Also, if you change the parent object's properties, is the child's corresponding property hasn't been changed, it'll be updated.
When I was implementing an algorithm to calculate the entropy of an image I found these links, see here and here.
This is the pseudo-code I used, you'll need to adapt it to work with text rather than images but the principles should be the same.
//Loop over image array elements and count occurrences of each possible
//pixel to pixel difference value. Store these values in prob_array
for j = 0, ysize-1 do $
for i = 0, xsize-2 do begin
diff = array(i+1,j) - array(i,j)
if diff lt (array_size+1)/2 and diff gt -(array_size+1)/2 then begin
prob_array(diff+(array_size-1)/2) = prob_array(diff+(array_size-1)/2) + 1
endif
endfor
//Convert values in prob_array to probabilities and compute entropy
n = total(prob_array)
entrop = 0
for i = 0, array_size-1 do begin
prob_array(i) = prob_array(i)/n
//Base 2 log of x is Ln(x)/Ln(2). Take Ln of array element
//here and divide final sum by Ln(2)
if prob_array(i) ne 0 then begin
entrop = entrop - prob_array(i)*alog(prob_array(i))
endif
endfor
entrop = entrop/alog(2)
I got this code from somewhere, but I can't dig out the link.
1)
total = 0;
for i=1:size(A,1)
for j=1:size(A,2)
total = total + A(i,j);
end
end
2)
total = sum(A(:));
This is all perfectly normal. Microsoft added sequences
in SQL Server 2012, finally, i might add and changed the way identity keys are generated. Have a look here for some explanation.
If you want to have the old behaviour, you can:
To get cell column name as well as cell value :
List<JObject> dataList = new List<JObject>();
for (int i = 0; i < dataTable.Rows.Count; i++)
{
JObject eachRowObj = new JObject();
for (int j = 0; j < dataTable.Columns.Count; j++)
{
string key = Convert.ToString(dataTable.Columns[j]);
string value = Convert.ToString(dataTable.Rows[i].ItemArray[j]);
eachRowObj.Add(key, value);
}
dataList.Add(eachRowObj);
}
Name2 is a field. WPF binds only to properties. Change it to:
public string Name2 { get; set; }
Be warned that with this minimal implementation, your TextBox won't respond to programmatic changes to Name2. So for your timer update scenario, you'll need to implement INotifyPropertyChanged:
partial class Window1 : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private string _name2;
public string Name2
{
get { return _name2; }
set
{
if (value != _name2)
{
_name2 = value;
OnPropertyChanged("Name2");
}
}
}
}
You should consider moving this to a separate data object rather than on your Window class.
Missing from these answers is how to get a file dialog without a input element on the page.
The function to show the input file dialog.
function openFileDialog (accept, callback) { // this function must be called from a user
// activation event (ie an onclick event)
// Create an input element
var inputElement = document.createElement("input");
// Set its type to file
inputElement.type = "file";
// Set accept to the file types you want the user to select.
// Include both the file extension and the mime type
inputElement.accept = accept;
// set onchange event to call callback when user has selected file
inputElement.addEventListener("change", callback)
// dispatch a click event to open the file dialog
inputElement.dispatchEvent(new MouseEvent("click"));
}
NOTE the function must be part of a user activation such as a click event. Attempting to open the file dialog without user activation will fail.
NOTE
input.accept
is not used in Edge
Calling above function when user clicks an anchor element.
// wait for window to load
window.addEventListener("load", windowLoad);
// open a dialog function
function openFileDialog (accept, multy = false, callback) {
var inputElement = document.createElement("input");
inputElement.type = "file";
inputElement.accept = accept; // Note Edge does not support this attribute
if (multy) {
inputElement.multiple = multy;
}
if (typeof callback === "function") {
inputElement.addEventListener("change", callback);
}
inputElement.dispatchEvent(new MouseEvent("click"));
}
// onload event
function windowLoad () {
// add user click event to userbutton
userButton.addEventListener("click", openDialogClick);
}
// userButton click event
function openDialogClick () {
// open file dialog for text files
openFileDialog(".txt,text/plain", true, fileDialogChanged);
}
// file dialog onchange event handler
function fileDialogChanged (event) {
[...this.files].forEach(file => {
var div = document.createElement("div");
div.className = "fileList common";
div.textContent = file.name;
userSelectedFiles.appendChild(div);
});
}
_x000D_
.common {
font-family: sans-serif;
padding: 2px;
margin : 2px;
border-radius: 4px;
}
.fileList {
background: #229;
color: white;
}
#userButton {
background: #999;
color: #000;
width: 8em;
text-align: center;
cursor: pointer;
}
#userButton:hover {
background : #4A4;
color : white;
}
_x000D_
<a id = "userButton" class = "common" title = "Click to open file selection dialog">Open file dialog</a>
<div id = "userSelectedFiles" class = "common"></div>
_x000D_
Warning the above snippet is written in ES6.
Dont make name with capital letters . Always use lowercase for naming . This will work fine . like companyLogo.png will raise error but company_logo.png will work fine.
After looking at this and trying it out I found it actually didn't allow more than one instance of jquery to run at a time. After searching around I found that this did just the trick and was a whole lot less code.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script>var $j = jQuery.noConflict(true);</script>
<script>
$(document).ready(function(){
console.log($().jquery); // This prints v1.4.2
console.log($j().jquery); // This prints v1.9.1
});
</script>
So then adding the "j" after the "$" was all I needed to do.
$j(function () {
$j('.button-pro').on('click', function () {
var el = $('#cnt' + this.id.replace('btn', ''));
$j('#contentnew > div').not(el).animate({
height: "toggle",
opacity: "toggle"
}, 100).hide();
el.toggle();
});
});
The new method is:
[self dismissViewControllerAnimated:NO completion:nil];
The word modal has been removed; As it has been for the presenting API call:
[self presentViewController:vc animated:NO completion:nil];
The reasons were discussed in the 2012 WWDC Session 236 - The Evolution of View Controllers on iOS Video. Essentially, view controllers presented by this API are no longer always modal, and since they were adding a completion handler it was a good time to rename it.
In response to comment from Marc:
What's the best way to support all devices 4.3 and above? The new method doesn't work in iOS4, yet the old method is deprecated in iOS6.
I realize that this is almost a separate question, but I think it's worth a mention since not everyone has the money to upgrade all their devices every 3 years so many of us have some older (pre 5.0) devices. Still, as much as it pains me to say it, you need to consider if it is worth targeting below 5.0. There are many new and cool APIs not available below 5.0. And Apple is continually making it harder to target them; armv6 support is dropped from Xcode 4.5, for example.
To target below 5.0 (as long as the completion block is nil) just use the handy respondsToSelector
: method.
if ([self respondsToSelector:@selector(presentViewController:animated:completion:)]){
[self presentViewController:test animated:YES completion:nil];
} else {
[self presentModalViewController:test animated:YES];
}
In response to another comment from Marc:
That could be quite a lot of If statements in my application!...I was thinking of creating a category that encapsulated this code, would creating a category on UIViewControler get me rejected?
and one from Full Decent:
...is there a way to manually cause that to not present a compiler warning?
Firstly, no, creating a category on UIViewController
in and of itself will not get your app rejected; unless that category method called private APIs or something similar.
A category method is an exceedingly good place for such code. Also, since there would be only one call to the deprecated API, there would be only one compiler warning.
To address Full Decent's comment(question), yes you can suppress compiler warnings manually. Here is a link to an answer on SO on that very subject. A category method is also a great place to suppress a compiler warning, since you're only suppressing the warning in one place. You certainly don't want to go around silencing the compiler willy-nilly.
If I was to write a simple category method for this it might be something like this:
@implementation UIViewController (NJ_ModalPresentation)
-(void)nj_presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion{
NSAssert(completion == nil, @"You called %@ with a non-nil completion. Don't do that!",NSStringFromSelector(_cmd));
if ([self respondsToSelector:@selector(presentViewController:animated:completion:)]){
[self presentViewController:viewControllerToPresent animated:flag completion:completion];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[self presentModalViewController:viewControllerToPresent animated:flag];
#pragma clang diagnostic pop
}
}
@end
you should remove last comma and as nrodic said your command is not correct.
you should change it like this :
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact " + ") VALUES (" + " textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, comboBox1.Text,comboBox2.Text,textBox7.Text" + ")", cn);
My problem was that I added the directory with the __init__.py
file to PYTHONPATH, when actually I needed to add its parent directory.
Beginning of line or beginning of string?
/^CTR.*$/
/
= delimiter
^
= start of string
CTR
= literal CTR
$
= end of string
.*
= zero or more of any character except newline
/^CTR.*$/m
/
= delimiter
^
= start of line
CTR
= literal CTR
$
= end of line
.*
= zero or more of any character except newline
m
= enables multi-line mode, this sets regex to treat every line as a string, so ^
and $
will match start and end of line
While in multi-line mode you can still match the start and end of the string with \A\Z
permanent anchors
/\ACTR.*\Z/m
\A
= means start of string
CTR
= literal CTR
.*
= zero or more of any character except newline
\Z
= end of string
m
= enables multi-line mode
As such, another way to match the start of the line would be like this:
/(\A|\r|\n|\r\n)CTR.*/
or
/(^|\r|\n|\r\n)CTR.*/
\r
= carriage return / old Mac OS newline
\n
= line-feed / Unix/Mac OS X newline
\r\n
= windows newline
Note, if you are going to use the backslash \
in some program string that supports escaping, like the php double quotation marks ""
then you need to escape them first
so to run \r\nCTR.*
you would use it as "\\r\\nCTR.*"
How about using fn:replace(string,pattern,replace) instead?
XPATH is very often used in XSLTs and if you are in that situation and does not have XPATH 2.0 you could use:
<xsl:choose>
<xsl:when test="condition1">
condition1-statements
</xsl:when>
<xsl:when test="condition2">
condition2-statements
</xsl:when>
<xsl:otherwise>
otherwise-statements
</xsl:otherwise>
</xsl:choose>
<TextView
android:id="@+id/some_textview"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="@id/textview_above"
app:layout_constraintRight_toLeftOf="@id/button_to_right"/>
android:maxLines="2"
to prevent vertical expansion (2 is just an e.g.)android:ellipsize="end"
0dp width allows left/right constraints to determine how wide your widget is.
Setting left/right constraints sets the actual width of your widget, within which your text will wrap.
Try setting the HOME environment variable in Windows to your home folder (c:\users\username
).
( you can confirm that this is the problem by doing echo $HOME
in git bash and echo %HOME%
in cmd - latter might not be available )
When it comes to memory usage, x86 is limited to circa 3 / 3,5 Gb, while x64 works fine with 4 Gb and more.
Moreover, when it comes to Windows, x86 will run on both X86 and x64 processors, while x64 requires x64 processor only.
I would add, and also to answer the question find mean bin values using histogram2d python that the scipy also have a function specially designed to compute a bidimensional binned statistic for one or more sets of data
import numpy as np
from scipy.stats import binned_statistic_2d
x = np.random.rand(100)
y = np.random.rand(100)
values = np.random.rand(100)
bin_means = binned_statistic_2d(x, y, values, bins=10).statistic
the function scipy.stats.binned_statistic_dd is a generalization of this funcion for higher dimensions datasets
Do you want iteration? itertools.combinations. Common usage:
>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']
If you just need to compute the formula, use math.factorial:
import math
def nCr(n,r):
f = math.factorial
return f(n) / f(r) / f(n-r)
if __name__ == '__main__':
print nCr(4,2)
In Python 3, use the integer division //
instead of /
to avoid overflows:
return f(n) // f(r) // f(n-r)
6
The common approach is to call "cat /proc/net/netstat" as described here:
This code computes the occurrences of all columns, and prints a sorted report for each of them:
# columnvalues.pl
while (<>) {
@Fields = split /\s+/;
for $i ( 0 .. $#Fields ) {
$result[$i]{$Fields[$i]}++
};
}
for $j ( 0 .. $#result ) {
print "column $j:\n";
@values = keys %{$result[$j]};
@sorted = sort { $result[$j]{$b} <=> $result[$j]{$a} || $a cmp $b } @values;
for $k ( @sorted ) {
print " $k $result[$j]{$k}\n"
}
}
Save the text as columnvalues.pl
Run it as: perl columnvalues.pl files*
In the top-level while loop:
* Loop over each line of the combined input files
* Split the line into the @Fields array
* For every column, increment the result array-of-hashes data structure
In the top-level for loop:
* Loop over the result array
* Print the column number
* Get the values used in that column
* Sort the values by the number of occurrences
* Secondary sort based on the value (for example b vs g vs m vs z)
* Iterate through the result hash, using the sorted list
* Print the value and number of each occurrence
column 0:
a 3
z 3
t 1
v 1
w 1
column 1:
d 3
r 2
b 1
g 1
m 1
z 1
column 2:
c 4
a 3
e 2
If your input files are .csv, change /\s+/
to /,/
In an ugly contest, Perl is particularly well equipped.
This one-liner does the same:
perl -lane 'for $i (0..$#F){$g[$i]{$F[$i]}++};END{for $j (0..$#g){print "$j:";for $k (sort{$g[$j]{$b}<=>$g[$j]{$a}||$a cmp $b} keys %{$g[$j]}){print " $k $g[$j]{$k}"}}}' files*
A shorter solution using data.table
:
setDT(group)[, .SD[which.max(pt)], by=Subject]
# Subject pt Event
# 1: 1 5 2
# 2: 2 17 2
# 3: 3 5 2
Add a new pandas.Series using pandas.DataFrame.append().
If you wish to specify the name (AKA the "index") of the new row, use:
df.append(pandas.Series(name='NameOfNewRow'))
If you don't wish to name the new row, use:
df.append(pandas.Series(), ignore_index=True)
where df
is your pandas.DataFrame.
import pandas as pd
df = pd.DataFrame([{'Product': 'Coke', 'Prices': [100,123,101,105,99,94,98]},{'Product': 'Pepsi', 'Prices': [101,104,104,101,99,99,99]}])
print(df)
df = df.assign(Prices=df.Prices.str.split(',')).explode('Prices')
print(df)
Try this in pandas >=0.25 version
You should use the setString()
method to set the userID
. This both ensures that the statement is formatted properly, and prevents SQL injection
:
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
There is a nice tutorial on how to use PreparedStatement
s properly in the Java Tutorials.
Since this thread is a popular result in google search, here is the way to do it for sublime text 3 build 3059+: in user preferences, add the line:
"show_encoding": true
As a novice programmer it can be confusing when people produce more skilled and unnecessary responses...You do not have to do any of the complicated stuff shown above!...
Here is the simplest option...In the case your keyboard appears in response to the textfield - Inside your touch screen function just add the resignFirstResponder function. As shown below - the keyboard will close because the First Responder is released (exiting the Responder chain)...
override func touchesBegan(_: Set<UITouch>, with: UIEvent?){
MyTextField.resignFirstResponder()
}
Firstly, I would try a non-secure websocket connection. So remove one of the s
's from the connection address:
conn = new WebSocket('ws://localhost:8080');
If that doesn't work, then the next thing I would check is your server's firewall settings. You need to open port 8080
both in TCP_IN
and TCP_OUT
.
This worked for me :
select option {
color: black;
}
select:not(:checked) {
color: gray;
}
Instead of importing the logout_view
function, you should provide a string in your urls.py
file:
So not (r'^login/', login_view),
but (r'^login/', 'login.views.login_view'),
That is the standard way of doing things. Then you can access the URL in your templates using:
{% url login.views.login_view %}
IndexError: invalid index to scalar variable
happens when you try to index a numpy
scalar such as numpy.int64
or numpy.float64
. It is very similar to TypeError: 'int' object has no attribute '__getitem__'
when you try to index an int
.
>>> a = np.int64(5)
>>> type(a)
<type 'numpy.int64'>
>>> a[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: invalid index to scalar variable.
>>> a = 5
>>> type(a)
<type 'int'>
>>> a[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'
The problem as I understand it is as follows. You have several libraries, some static, some dynamic and some both static and dynamic. gcc's default behavior is to link "mostly dynamic". That is, gcc links to dynamic libraries when possible but otherwise falls back to static libraries. When you use the -static option to gcc the behavior is to only link static libraries and exit with an error if no static library can be found, even if there is an appropriate dynamic library.
Another option, which I have on several occasions wished gcc had, is what I call -mostly-static and is essentially the opposite of -dynamic (the default). -mostly-static would, if it existed, prefer to link against static libraries but would fall back to dynamic libraries.
This option does not exist but it can be emulated with the following algorithm:
Constructing the link command line with out including -static.
Iterate over the dynamic link options.
Accumulate library paths, i.e. those options of the form -L<lib_dir> in a variable <lib_path>
For each dynamic link option, i.e. those of the form -l<lib_name>, run the command gcc <lib_path> -print-file-name=lib<lib_name>.a and capture the output.
If the command prints something other than what you passed, it will be the full path to the static library. Replace the dynamic library option with the full path to the static library.
Rinse and repeat until you've processed the entire link command line. Optionally the script can also take a list of library names to exclude from static linking.
The following bash script seems to do the trick:
#!/bin/bash
if [ $# -eq 0 ]; then
echo "Usage: $0 [--exclude <lib_name>]. . . <link_command>"
fi
exclude=()
lib_path=()
while [ $# -ne 0 ]; do
case "$1" in
-L*)
if [ "$1" == -L ]; then
shift
LPATH="-L$1"
else
LPATH="$1"
fi
lib_path+=("$LPATH")
echo -n "\"$LPATH\" "
;;
-l*)
NAME="$(echo $1 | sed 's/-l\(.*\)/\1/')"
if echo "${exclude[@]}" | grep " $NAME " >/dev/null; then
echo -n "$1 "
else
LIB="$(gcc $lib_path -print-file-name=lib"$NAME".a)"
if [ "$LIB" == lib"$NAME".a ]; then
echo -n "$1 "
else
echo -n "\"$LIB\" "
fi
fi
;;
--exclude)
shift
exclude+=(" $1 ")
;;
*) echo -n "$1 "
esac
shift
done
echo
For example:
mostlyStatic gcc -o test test.c -ldl -lpthread
on my system returns:
gcc -o test test.c "/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/libdl.a" "/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/libpthread.a"
or with an exclusion:
mostlyStatic --exclude dl gcc -o test test.c -ldl -lpthread
I then get:
gcc -o test test.c -ldl "/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/libpthread.a"
You have to open database connection, not workbench file with schema. It looks a bit wierd, but it makes sense when you realize what you are editing.
So, go to home tab, double click database connection (create it if you don't have it yet) and have fun.
If you got Destination path XXX already exists
means the name of the project repository which you are trying to clone is already there in that current directory. So please cross-check and delete any existing one and try to clone it again
If you want to get it aligned to the right after the text looses focus you can try to use the direction modifier. This will show the right part of the text after loosing focus. e.g. useful if you want to show the file name in a large path.
input.rightAligned {_x000D_
direction:ltr;_x000D_
overflow:hidden;_x000D_
}_x000D_
input.rightAligned:not(:focus) {_x000D_
direction:rtl;_x000D_
text-align: left;_x000D_
unicode-bidi: plaintext;_x000D_
text-overflow: ellipsis;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" class="rightAligned" name="name" value="">_x000D_
</form>
_x000D_
The not selector is currently well supported : Browser support
sys.modules
pip
), you may look at pip.get_installed_distributions()
For the second purpose, example code:
import pip
for package in pip.get_installed_distributions():
name = package.project_name # SQLAlchemy, Django, Flask-OAuthlib
key = package.key # sqlalchemy, django, flask-oauthlib
module_name = package._get_metadata("top_level.txt") # sqlalchemy, django, flask_oauthlib
location = package.location # virtualenv lib directory etc.
version = package.version # version number
Solution for me was to use:
from flask_sqlalchemy import SQLAlchemy
instead of
from flask.ext.sqlalchemy import SQLAlchemy
lsof -i:3000;
kill -9 $(lsof -t -i:3000);
// 3000 is a your port
// This "lsof -i:3000;" command will show PID
kill PID
ex: kill 129393
On the "How to do it" part:
I think the introduction to ScalaTest does good job of illustrating different styles of unit tests.
On the "When to do it" part:
Unit testing is not only for testing. By doing unit testing you also force the design of the software into something that is unit testable. Many people are of the opinion that this design is for the most part Good Design(TM) regardless of other benefits from testing.
So one reason to do unit test is to force your design into something that hopefully will be easier to maintain that what it would be had you not designed it for unit testing.
In Mac OS X the command file -I
(capital i) will give you the proper character set so long as the file you are testing contains characters outside of the basic ASCII range.
For instance if you go into Terminal and use vi to create a file eg. vi test.txt
then insert some characters and include an accented character (try ALT-e followed by e)
then save the file.
They type file -I text.txt
and you should get a result like this:
test.txt: text/plain; charset=utf-8
The getParent
method returns a ViewParent
, not a View
. You need to cast the first call to getParent()
also:
RelativeLayout r = (RelativeLayout) ((ViewGroup) this.getParent()).getParent();
As stated in the comments by the OP, this is causing a NPE
. To debug, split this up into multiple parts:
ViewParent parent = this.getParent();
RelativeLayout r;
if (parent == null) {
Log.d("TEST", "this.getParent() is null");
}
else {
if (parent instanceof ViewGroup) {
ViewParent grandparent = ((ViewGroup) parent).getParent();
if (grandparent == null) {
Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is null");
}
else {
if (parent instanceof RelativeLayout) {
r = (RelativeLayout) grandparent;
}
else {
Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is not a RelativeLayout");
}
}
}
else {
Log.d("TEST", "this.getParent() is not a ViewGroup");
}
}
//now r is set to the desired RelativeLayout.
Here in this article is clearly explained: The $state
service provides a number of useful methods for manipulating the state as well as pertinent data on the current state. The current state parameters are accessible on the $state
service at the params key. The $stateParams
service returns this very same object. Hence, the $stateParams
service is strictly a convenience service to quickly access the params object on the $state
service.
As such, no controller should ever inject both the $state
service and its convenience service, $stateParams
. If the $state
is being injected just to access the current parameters, the controller should be rewritten to inject $stateParams
instead.
I recommend you to look at the adbroker package of the oVirt project. It uses Spring-Ldap and the Krb5 JAAS Login module (with GSSAPI) in order to authenticate using Kerberos against Ldap servers (Active-Directory, ipa, rhds, Tivoli-DS). Look for the code at engine\backend\manager\modules\bll\src\main\java\org\ovirt\engine\core\bll\adbroker
You can use git to clone the repository or browse using the gerrit link
if you want to do a simple, it will be like this
// Fig. 6.3: MaximumFinder.java
// Programmer-declared method maximum with three double parameters.
import java.util.Scanner;
public class MaximumFinder
{
// obtain three floating-point values and locate the maximum value
public static void main(String[] args)
{
// create Scanner for input from command window
Scanner input = new Scanner(System.in);
// prompt for and input three floating-point values
System.out.print(
"Enter three floating-point values separated by spaces: ");
double number1 = input.nextDouble(); // read first double
double number2 = input.nextDouble(); // read second double
double number3 = input.nextDouble(); // read third double
// determine the maximum value
double result = maximum(number1, number2, number3);
// display maximum value
System.out.println("Maximum is: " + result);
}
// returns the maximum of its three double parameters
public static double maximum(double x, double y, double z)
{
double maximumValue = x; // assume x is the largest to start
// determine whether y is greater than maximumValue
if (y > maximumValue)
maximumValue = y;
// determine whether z is greater than maximumValue
if (z > maximumValue)
maximumValue = z;
return maximumValue;
}
} // end class MaximumFinder
and the output will be something like this
Enter three floating-point values separated by spaces: 9.35 2.74 5.1
Maximum is: 9.35
References Java™ How To Program (Early Objects), Tenth Edition
One liner error raising can be done with assert statements if that's what you want to do. This will help you write statically fixable code and check errors early.
assert type(A) is type(""), "requires a string"
Did you try using double-quotes? Regardless, no one in 2011 should be limited by the native VB6 shell command. Here's a function that uses ShellExecuteEx, much more versatile.
Option Explicit
Private Const SEE_MASK_DEFAULT = &H0
Public Enum EShellShowConstants
essSW_HIDE = 0
essSW_SHOWNORMAL = 1
essSW_SHOWMINIMIZED = 2
essSW_MAXIMIZE = 3
essSW_SHOWMAXIMIZED = 3
essSW_SHOWNOACTIVATE = 4
essSW_SHOW = 5
essSW_MINIMIZE = 6
essSW_SHOWMINNOACTIVE = 7
essSW_SHOWNA = 8
essSW_RESTORE = 9
essSW_SHOWDEFAULT = 10
End Enum
Private Type SHELLEXECUTEINFO
cbSize As Long
fMask As Long
hwnd As Long
lpVerb As String
lpFile As String
lpParameters As String
lpDirectory As String
nShow As Long
hInstApp As Long
lpIDList As Long 'Optional
lpClass As String 'Optional
hkeyClass As Long 'Optional
dwHotKey As Long 'Optional
hIcon As Long 'Optional
hProcess As Long 'Optional
End Type
Private Declare Function ShellExecuteEx Lib "shell32.dll" Alias "ShellExecuteExA" (lpSEI As SHELLEXECUTEINFO) As Long
Public Function ExecuteProcess(ByVal FilePath As String, ByVal hWndOwner As Long, ShellShowType As EShellShowConstants, Optional EXEParameters As String = "", Optional LaunchElevated As Boolean = False) As Boolean
Dim SEI As SHELLEXECUTEINFO
On Error GoTo Err
'Fill the SEI structure
With SEI
.cbSize = Len(SEI) ' Bytes of the structure
.fMask = SEE_MASK_DEFAULT ' Check MSDN for more info on Mask
.lpFile = FilePath ' Program Path
.nShow = ShellShowType ' How the program will be displayed
.lpDirectory = PathGetFolder(FilePath)
.lpParameters = EXEParameters ' Each parameter must be separated by space. If the lpFile member specifies a document file, lpParameters should be NULL.
.hwnd = hWndOwner ' Owner window handle
' Determine launch type (would recommend checking for Vista or greater here also)
If LaunchElevated = True Then ' And m_OpSys.IsVistaOrGreater = True
.lpVerb = "runas"
Else
.lpVerb = "Open"
End If
End With
ExecuteProcess = ShellExecuteEx(SEI) ' Execute the program, return success or failure
Exit Function
Err:
' TODO: Log Error
ExecuteProcess = False
End Function
Private Function PathGetFolder(psPath As String) As String
On Error Resume Next
Dim lPos As Long
lPos = InStrRev(psPath, "\")
PathGetFolder = Left$(psPath, lPos - 1)
End Function
You don't create subfolders of the drawable folder but rather 'sibling' folders next to it under the /res
folder for the different screen densities or screen sizes.
The /drawable
folder (without any dimension) is mostly used for drawables that don't relate to any screen sizes like selector
s.
See this screenshot (use the name drawable-hdpi
instead of mipmap-hdpi
):
How about .toDateString()
?
Alternatively, use .getDate()
, .getMonth()
, and .getYear()
?
In my mind, if you want to group things by date, you simply want to access the date, not set it. Through having some set way of accessing the date field, you can compare them and group them together, no?
Check out all the fun Date methods here: MDN Docs
Edit: If you want to keep it as a date object, just do this:
var newDate = new Date(oldDate.toDateString());
Date's constructor is pretty smart about parsing Strings (though not without a ton of caveats, but this should work pretty consistently), so taking the old Date and printing it to just the date without any time will result in the same effect you had in the original post.
What kind of data?
data: $('#myForm').serialize() + "&moredata=" + morevalue
The "data" parameter is just a URL encoded string. You can append to it however you like. See the API here.
Close the current interpreter using exit() command and reopen typing python to start your work. And do not name a list as list literally. Then you will be fine.
The application/x-www-form-urlencoded
Content-type header is not needed. Unless the request handler expects the parameters coming from request body. Try it out:
curl -X DELETE "http://localhost:5000/locations?id=3"
or
curl -X GET "http://localhost:5000/locations?id=3"
See question: How to find an item in a std::vector?
You'll also need to ensure you've implemented a suitable operator==()
for your object, if the default one isn't sufficient for a "deep" equality test.
While you can't yet get Firefox to remove the dropdown arrow (see MatTheCat's post), you can hide your "stylized" background image from showing in Firefox.
-moz-background-position: -9999px -9999px!important;
This will position it out of frame, leaving you with the default select box arrow – while keeping the stylized version in Webkit.
There is some news based on Mozilla Foundation, and sitepoint
Do not use this value (
http-equiv=content-type
) as it is obsolete. Prefer thecharset
attribute on the <meta
> element.
For me, the problem was twofold: First, the version of IIS I was dealing with didn't know about the .woff2
MIME type, only about .woff
. I fixed that using IIS Manager at the server level, not at the web app level, so the setting wouldn't get overridden with each new app deployment. (Under IIS Manager, I went to MIME types, and added the missing .woff2
, then updated .woff
.)
Second, and more importantly, I was bundling bootstrap.css
along with some other files as "~/bundles/css/site"
. Meanwhile, my font files were in "~/fonts"
. bootstrap.css
looks for the glyphicon fonts in "../fonts"
, which translated to "~/bundles/fonts"
-- wrong path.
In other words, my bundle path was one directory too deep. I renamed it to "~/bundles/siteCss"
, and updated all the references to it that I found in my project. Now bootstrap looked in "~/fonts"
for the glyphicon files, which worked. Problem solved.
Before I fixed the second problem above, none of the glyphicon
font files were loading. The symptom was that all instances of glyphicon
glyphs in the project just showed an empty box. However, this symptom only occurred in the deployed versions of the web app, not on my dev machine. I'm still not sure why that was the case.
Create a listview item
ListViewItem item1 = new ListViewItem("sdasdasdasd", 0)
item1.SubItems.Add("asdasdasd")
If you need to sort by only one field, then usort
is a good choice. However, the solution quickly becomes messy if you need to sort by multiple fields. In this case, YaLinqo library* can be used, which implements SQL-like query syntax for arrays and objects. It has a pretty syntax for all cases:
$sortedByName = from($objects)->orderBy('$v->name');
$sortedByCount = from($objects)->orderBy('$v->count');
$sortedByCountAndName = from($objects)->orderBy('$v->count')->thenBy('$v->name');
Here, '$v->count'
is a shorthand for function ($v) { return $v->count; }
(either can be used). These method chains return iterators, but you can get arrays by adding ->toArray()
in the end if you need it.
* developed by me
This will eventually get to your question, but I first want to address a number of issues you raise in your various comments to the various answers already given at the time of this writing. I have no intention of changing your mind -- rather, these are here for others who come to read this post in the future.
The point is that I cannot allow for Android to determine when my app is going to be terminated. that must be the choice of the user.
Millions of people are perfectly happy with the model where the environment closes up the application as needed. Those users simply don't think about "terminating" the Android app, any more than they think about "terminating" a Web page or "terminating" a thermostat.
iPhone users are much the same way, in that pressing the iPhone button does not necessarily "feel" like the app was terminated since many iPhone apps pick up where the user left off, even if the app really was shut down (since iPhone only allows one third-party app at a time, at present).
As I said above, there is a lot of things going on in my app (data being PUSHed to the device, lists with tasks that always should be there, etc.).
I don't know what "lists with tasks that always should be there" means, but the "data being PUSHed to the device" is a pleasant fiction and should not be done by activity in any case. Use a scheduled task (via AlarmManager
) to update your data for maximum reliability.
Our users log in and can't be doing that every time they get a phone call and Android decides to kill the app.
There are many iPhone and Android applications that deal with this. Usually, it is because they hold onto login credentials, rather than forcing users to log in every time manually.
For example, we want to check updates when exiting the application
That is a mistake on any operating system. For all you know, the reason your application is being "exited" is because the OS is shutting down, and then your update process will fail mid-stream. Generally, that's not a good thing. Either check updates on start or check updates totally asynchronously (e.g., via a scheduled task), never on exit.
Some comments suggest that hitting the back button does not kill the app at all (see link in my question above).
Pressing the BACK button does not "kill the app". It finishes the activity that was on-screen when the user pressed the BACK button.
It should only terminate when the users want to terminate it - never ever any other way. If you can't write apps that behave like that in Android, then I think that Android can't be used for writing real apps =(
Then neither can Web applications. Or WebOS, if I understand their model correctly (haven't had a chance to play with one yet). In all of those, users don't "terminate" anything -- they just leave. iPhone is a bit different, in that it only presently allows one thing to run at a time (with a few exceptions), and so the act of leaving implies a fairly immediate termination of the app.
Is there a way for me to really quit the application?
As everybody else told you, users (via BACK) or your code (via finish()
) can close up your currently-running activity. Users generally don't need anything else, for properly-written applications, any more than they need a "quit" option for using Web applications.
No two application environments are the same, by definition. This means that you can see trends in environments as new ones arise and others get buried.
For example, there is a growing movement to try to eliminate the notion of the "file". Most Web applications don't force users to think of files. iPhone apps typically don't force users to think of files. Android apps generally don't force users to think of files. And so on.
Similarly, there is a growing movement to try to eliminate the notion of "terminating" an app. Most Web applications don't force the user to log out, but rather implicitly log the user out after a period of inactivity. Same thing with Android, and to a lesser extent, iPhone (and possibly WebOS).
This requires more emphasis on application design, focusing on business goals, and not sticking with an implementation model tied to a previous application environment. Developers who lack the time or inclination to do this will get frustrated with newer environments that break their existing mental model. This is not the fault of either environment, any more than it is the fault of a mountain for storms flowing around it rather than through it.
For example, some development environments, like Hypercard and Smalltalk, had the application and the development tools co-mingled in one setup. This concept did not catch on much, outside of language extensions to apps (e.g., VBA in Excel, Lisp in AutoCAD). Developers who came up with mental models that presumed the existence of development tools in the app itself, therefore, either had to change their model or limit themselves to environments where their model would hold true.
So, when you write:
Along with other messy things I discovered, I think that developing our app for Android is not going to happen.
That would appear to be for the best, for you, for right now. Similarly, I would counsel you against attempting to port your application to the Web, since some of the same problems you have reported with Android you will find in Web applications as well (e.g., no "termination"). Or, conversely, someday if you do port your app to the Web, you may find that the Web application's flow may be a better match for Android, and you can revisit an Android port at that time.
Here's a fairly unconventional (but fast) approach: use fwrite
from data.table
to "paste" the columns together, and fread
to read it back in. For convenience, I've written the steps as a function called fpaste
:
fpaste <- function(dt, sep = ",") {
x <- tempfile()
fwrite(dt, file = x, sep = sep, col.names = FALSE)
fread(x, sep = "\n", header = FALSE)
}
Here's an example:
d <- data.frame(a = 1:3, b = c('a','b','c'), c = c('d','e','f'), d = c('g','h','i'))
cols = c("b", "c", "d")
fpaste(d[cols], "-")
# V1
# 1: a-d-g
# 2: b-e-h
# 3: c-f-i
How does it perform?
d2 <- d[sample(1:3,1e6,TRUE),]
library(microbenchmark)
microbenchmark(
docp = do.call(paste, c(d2[cols], sep="-")),
tidr = tidyr::unite_(d2, "x", cols, sep="-")$x,
docs = do.call(sprintf, c(d2[cols], '%s-%s-%s')),
appl = apply( d2[, cols ] , 1 , paste , collapse = "-" ),
fpaste = fpaste(d2[cols], "-")$V1,
dt2 = as.data.table(d2)[, x := Reduce(function(...) paste(..., sep = "-"), .SD), .SDcols = cols][],
times=10)
# Unit: milliseconds
# expr min lq mean median uq max neval
# docp 215.34536 217.22102 220.3603 221.44104 223.27224 225.0906 10
# tidr 215.19907 215.81210 220.7131 220.09636 225.32717 229.6822 10
# docs 281.16679 285.49786 289.4514 286.68738 290.17249 312.5484 10
# appl 2816.61899 3106.19944 3259.3924 3266.45186 3401.80291 3804.7263 10
# fpaste 88.57108 89.67795 101.1524 90.59217 91.76415 197.1555 10
# dt2 301.95508 310.79082 384.8247 316.29807 383.94993 874.4472 10
Parse() methods provide the number styles which cannot be used for Convert(). For example:
int i;
bool b = int.TryParse( "123-",
System.Globalization.NumberStyles.AllowTrailingSign,
System.Globalization.CultureInfo.InvariantCulture,
out i);
would parse the numbers with trailing sign so that i == -123
The trailing sign is popular in ERP systems.
Show everything including dir itself but not its long boring contents:
find . -print -name dir -prune
It could be used as a wrapper function for returning a reference to a private constant data type. For example in a linked list you have the constants tail and head, and if you want to determine if a node is a tail or head node, then you can compare it with the value returned by that function.
Though any optimizer would most likely optimize it out anyway...
Another one, using git log:
git log -1 --format="%H"
It's very similar to the of @outofculture though a bit shorter.
From Effective Go:
To delete a map entry, use the delete built-in function, whose arguments are the map and the key to be deleted. It's safe to do this even if the key is already absent from the map.
delete(timeZone, "PDT") // Now on Standard Time
The 'classic' way of measuring this is to break the image up into some canonical number of sections (say a 10x10 grid) and then computing a histogram of RGB values inside of each cell and compare corresponding histograms. This type of algorithm is preferred because of both its simplicity and it's invariance to scaling and (small!) translation.
The following should suffice:
[^ ]
If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):
[^\s]
or
\S # Note this is a CAPITAL 'S'!
Source control is best way to handle this problem, if you don't want to pay then try bitbucket
It's free, allows private repo for upto 5 members team.
Define will make the constant available everywhere in your class without needing to use global, while the variable requires global in the class, I would use DEFINE. but again, if the db params should change during program execution you might want to stick with variable.
$('input[type="text"]').keyup(function(evt){
var txt = $(this).val();
// Regex taken from php.js (http://phpjs.org/functions/ucwords:569)
$(this).val(txt.replace(/^(.)|\s(.)/g, function($1){ return $1.toUpperCase( ); }));
});
Had a similar problem on Centos 7. When I tried to apply the solution prescribed by Sorin, I started moving in cycles. First I had a permission {write} denied. Then when I solved that I had a permission { connectto } denied. Then back again to permission {write } denied.
Following @Sid answer above of checking the flags using getsebool -a | grep httpd
and toggling them I found that in addition to the httpd_can_network_connect being off. http_anon_write was also off resulting in permission denied write and permission denied {connectto}
type=AVC msg=audit(1501830505.174:799183): avc:
denied { write } for pid=12144 comm="nginx" name="myroject.sock"
dev="dm-2" ino=134718735 scontext=system_u:system_r:httpd_t:s0
tcontext=system_u:object_r:default_t:s0 tclass=sock_file
Obtained using sudo cat /var/log/audit/audit.log | grep nginx | grep denied as explained above.
So I solved them one at a time, toggling the flags on one at a time.
setsebool httpd_can_network_connect on -P
Then running the commands specified by @sorin and @Joseph above
sudo cat /var/log/audit/audit.log | grep nginx | grep denied |
audit2allow -M mynginx
sudo semodule -i mynginx.pp
Basically you can check the permissions set on setsebool and correlate that with the error obtained from grepp'ing' audit.log nginx, denied
See the Express docs as well as the Node docs for https.createServer (which is what express recommends to use):
var privateKey = fs.readFileSync( 'privatekey.pem' );
var certificate = fs.readFileSync( 'certificate.pem' );
https.createServer({
key: privateKey,
cert: certificate
}, app).listen(port);
Other options for createServer are at: http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener
Check that C:\Program Files (x86)\Git\cmd
is in you Path environment variable:
echo $env:Path
The S parameter does not do anything on its own.
/S Modifies the treatment of string after /C or /K (see below)
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
Try something like this instead
Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)
You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.
Shell("perl a.pl c:\temp")
-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn
Type the command mvn -version
directly in your maven directory, you probably haven't added it to your PATH. Here are explained details of how to add maven to your PATH variable (I guess you use Windows because you are talking about CMD).
For removing the data and preserving the table-structures in pgAdmin you can do:
I'd prefer to use the .Find
method directly on a range object containing the range of cells to be searched. For original poster's code it might look like:
Set cell = ActiveSheet.Columns("B:B").Find( _
What:=celda, _
After:=ActiveCell _
LookIn:=xlFormulas, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False _
)
If cell Is Nothing Then
'do something
Else
'do something else
End If
I'd prefer to use more variables (and be sure to declare them) and let a lot of optional arguments use their default values:
Dim rng as Range
Dim cell as Range
Dim search as String
Set rng = ActiveSheet.Columns("B:B")
search = "String to Find"
Set cell = rng.Find(What:=search, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=False)
If cell Is Nothing Then
'do something
Else
'do something else
End If
I kept LookIn:=
, LookAt::=
, and MatchCase:=
to be explicit about what is being matched. The other optional parameters control the order matches are returned in - I'd only specify those if the order is important to my application.
The "@import" rule could calls in multiple styles files. These files are called by the browser or User Agent when needed e.g. HTML tags call the CSS.
<!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" lang="EN" dir="ltr">
<head>
<title>Using @import</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style type="text/css">
@import url("main.css");
</style>
</head>
<body>
</body>
</html>
CSS File "main.css" Contains The Following Syntax:
@import url("fineprint.css") print;
@import url("bluish.css") projection, tv;
@import 'custom.css';
@import url("chrome://communicator/skin/");
@import "common.css" screen, projection;
@import url('landscape.css') screen and (orientation:landscape);
To insert in style element use createTexNode don't use innerHTML but:
<script>
var style = document.createElement('style');
style.setAttribute("type", "text/css");
var textNode = document.createTextNode("
@import 'fineprint.css' print;
@import 'bluish.css' projection, tv;
@import 'custom.css';
@import 'chrome://communicator/skin/';
@import 'common.css' screen, projection;
@import 'landscape.css' screen and (orientation:landscape);
");
style.appendChild(textNode);
</script>
First add the file to your project resource directory
then
public YourPage uploadFileBtnSendKeys() {
final ClassLoader classLoader = getClass().getClassLoader();
final File file = new File(classLoader.getResource("yourFile.whatever").getPath());
uploadFileBtn.sendKeys(file.getPath());
return this;
}
Walla, you will see your choosen selected file, and have skipped the file explorer window
Edit!: Please be sure that you should have both Python installed on your computer.
Maybe my answer is late for you but I can help someone who has the same problem!
You don't have to download both Anaconda
.
If you are using Spyder
and Jupyter
in Anaconda environmen and,
If you have already Anaconda 2 type in Terminal:
python3 -m pip install ipykernel
python3 -m ipykernel install --user
If you have already Anaconda 3 then type in terminal:
python2 -m pip install ipykernel
python2 -m ipykernel install --user
Then before use Spyder
you can choose Python environment like below!
Sometimes only you can see root and your new Python environment, so root is your first anaconda environment!
Also this is Jupyter. You can choose python version like this!
I hope it will help.
There's no need to require a big library like jQuery to accomplish this, if you don't want to. To achieve this with built-in DOM manipulation, get a collection of the li
siblings in an array, and on click, check the indexOf
the clicked element in that array.
const lis = [...document.querySelectorAll('#wizard > li')];_x000D_
lis.forEach((li) => {_x000D_
li.addEventListener('click', () => {_x000D_
const index = lis.indexOf(li);_x000D_
console.log(index);_x000D_
});_x000D_
});
_x000D_
<ul id="wizard">_x000D_
<li>Step 1</li>_x000D_
<li>Step 2</li>_x000D_
</ul>
_x000D_
Or, with event delegation:
const lis = [...document.querySelectorAll('#wizard li')];_x000D_
document.querySelector('#wizard').addEventListener('click', ({ target }) => {_x000D_
// Make sure the clicked element is a <li> which is a child of wizard:_x000D_
if (!target.matches('#wizard > li')) return;_x000D_
_x000D_
const index = lis.indexOf(target);_x000D_
console.log(index);_x000D_
});
_x000D_
<ul id="wizard">_x000D_
<li>Step 1</li>_x000D_
<li>Step 2</li>_x000D_
</ul>
_x000D_
Or, if the child elements may change dynamically (like with a todo list), then you'll have to construct the array of li
s on every click, rather than beforehand:
const wizard = document.querySelector('#wizard');_x000D_
wizard.addEventListener('click', ({ target }) => {_x000D_
// Make sure the clicked element is a <li>_x000D_
if (!target.matches('li')) return;_x000D_
_x000D_
const lis = [...wizard.children];_x000D_
const index = lis.indexOf(target);_x000D_
console.log(index);_x000D_
});
_x000D_
<ul id="wizard">_x000D_
<li>Step 1</li>_x000D_
<li>Step 2</li>_x000D_
</ul>
_x000D_
Here's my code:
public static class ShortcutHelper
{
#region Constants
/// <summary>
/// Default shortcut extension
/// </summary>
public const string DEFAULT_SHORTCUT_EXTENSION = ".lnk";
private const string WSCRIPT_SHELL_NAME = "WScript.Shell";
#endregion
/// <summary>
/// Create shortcut in current path.
/// </summary>
/// <param name="linkFileName">shortcut name(include .lnk extension.)</param>
/// <param name="targetPath">target path</param>
/// <param name="workingDirectory">working path</param>
/// <param name="arguments">arguments</param>
/// <param name="hotkey">hot key(ex: Ctrl+Shift+Alt+A)</param>
/// <param name="shortcutWindowStyle">window style</param>
/// <param name="description">shortcut description</param>
/// <param name="iconNumber">icon index(start of 0)</param>
/// <returns>shortcut file path.</returns>
/// <exception cref="System.IO.FileNotFoundException"></exception>
public static string CreateShortcut(
string linkFileName,
string targetPath,
string workingDirectory = "",
string arguments = "",
string hotkey = "",
ShortcutWindowStyles shortcutWindowStyle = ShortcutWindowStyles.WshNormalFocus,
string description = "",
int iconNumber = 0)
{
if (linkFileName.Contains(DEFAULT_SHORTCUT_EXTENSION) == false)
{
linkFileName = string.Format("{0}{1}", linkFileName, DEFAULT_SHORTCUT_EXTENSION);
}
if (File.Exists(targetPath) == false)
{
throw new FileNotFoundException(targetPath);
}
if (workingDirectory == string.Empty)
{
workingDirectory = Path.GetDirectoryName(targetPath);
}
string iconLocation = string.Format("{0},{1}", targetPath, iconNumber);
if (Environment.Version.Major >= 4)
{
Type shellType = Type.GetTypeFromProgID(WSCRIPT_SHELL_NAME);
dynamic shell = Activator.CreateInstance(shellType);
dynamic shortcut = shell.CreateShortcut(linkFileName);
shortcut.TargetPath = targetPath;
shortcut.WorkingDirectory = workingDirectory;
shortcut.Arguments = arguments;
shortcut.Hotkey = hotkey;
shortcut.WindowStyle = shortcutWindowStyle;
shortcut.Description = description;
shortcut.IconLocation = iconLocation;
shortcut.Save();
}
else
{
Type shellType = Type.GetTypeFromProgID(WSCRIPT_SHELL_NAME);
object shell = Activator.CreateInstance(shellType);
object shortcut = shellType.InvokeMethod("CreateShortcut", shell, linkFileName);
Type shortcutType = shortcut.GetType();
shortcutType.InvokeSetMember("TargetPath", shortcut, targetPath);
shortcutType.InvokeSetMember("WorkingDirectory", shortcut, workingDirectory);
shortcutType.InvokeSetMember("Arguments", shortcut, arguments);
shortcutType.InvokeSetMember("Hotkey", shortcut, hotkey);
shortcutType.InvokeSetMember("WindowStyle", shortcut, shortcutWindowStyle);
shortcutType.InvokeSetMember("Description", shortcut, description);
shortcutType.InvokeSetMember("IconLocation", shortcut, iconLocation);
shortcutType.InvokeMethod("Save", shortcut);
}
return Path.Combine(System.Windows.Forms.Application.StartupPath, linkFileName);
}
private static object InvokeSetMember(this Type type, string methodName, object targetInstance, params object[] arguments)
{
return type.InvokeMember(
methodName,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty,
null,
targetInstance,
arguments);
}
private static object InvokeMethod(this Type type, string methodName, object targetInstance, params object[] arguments)
{
return type.InvokeMember(
methodName,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod,
null,
targetInstance,
arguments);
}
/// <summary>
/// windows styles
/// </summary>
public enum ShortcutWindowStyles
{
/// <summary>
/// Hide
/// </summary>
WshHide = 0,
/// <summary>
/// NormalFocus
/// </summary>
WshNormalFocus = 1,
/// <summary>
/// MinimizedFocus
/// </summary>
WshMinimizedFocus = 2,
/// <summary>
/// MaximizedFocus
/// </summary>
WshMaximizedFocus = 3,
/// <summary>
/// NormalNoFocus
/// </summary>
WshNormalNoFocus = 4,
/// <summary>
/// MinimizedNoFocus
/// </summary>
WshMinimizedNoFocus = 6,
}
}
I've done this before. You can just create a new exception and grab the stack trace on it without throwing it, then examine the stack trace. As the other answer says though, it's extremely costly--don't do it in a tight loop.
I've done it before for a logging utility on an app where performance didn't matter much (Performance rarely matters much at all, actually--as long as you display the result to an action such as a button click quickly).
It was before you could get the stack trace, exceptions just had .printStackTrace() so I had to redirect System.out to a stream of my own creation, then (new Exception()).printStackTrace(); Redirect System.out back and parse the stream. Fun stuff.
TextField( minLines: 1, maxLines: 5, maxLengthEnforced: true)
For those looking for a general strategy for reading and writing a string to file:
First, get a file object
You'll need the storage path. For the internal storage, use:
File path = context.getFilesDir();
For the external storage (SD card), use:
File path = context.getExternalFilesDir(null);
Then create your file object:
File file = new File(path, "my-file-name.txt");
Write a string to the file
FileOutputStream stream = new FileOutputStream(file);
try {
stream.write("text-to-write".getBytes());
} finally {
stream.close();
}
Or with Google Guava
String contents = Files.toString(file, StandardCharsets.UTF_8);
Read the file to a string
int length = (int) file.length();
byte[] bytes = new byte[length];
FileInputStream in = new FileInputStream(file);
try {
in.read(bytes);
} finally {
in.close();
}
String contents = new String(bytes);
Or if you are using Google Guava
String contents = Files.toString(file,"UTF-8");
For completeness I'll mention
String contents = new Scanner(file).useDelimiter("\\A").next();
which requires no libraries, but benchmarks 50% - 400% slower than the other options (in various tests on my Nexus 5).
Notes
For each of these strategies, you'll be asked to catch an IOException.
The default character encoding on Android is UTF-8.
If you are using external storage, you'll need to add to your manifest either:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
or
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Write permission implies read permission, so you don't need both.
To answer the title of your question directly because this comes up in Google first:
YES, TypeScript can export a function!
Here is a direct quote from the TS Documentation:
"Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword."
In Swift 3.0
let rowNumber: Int = 2
let sectionNumber: Int = 0
let indexPath = IndexPath(item: rowNumber, section: sectionNumber)
self.tableView.reloadRows(at: [indexPath], with: .automatic)
byDefault, if you have only one section in TableView, then you can put section value 0.
Here's what I did in case someone finds it useful (I used a lot of things according to the rest of the answers in this thread):
First I adjusted the layout settings as needed. This changes the window size immediately so it was easier to set the exact size that I wanted. By the way I didn't know that I can also have visible width smaller than width buffer. This was nice since I usually hate a long line to be wrapped.
Then after clicking ok, I opened regedit.exe and went to "HKEY_CURRENT_USER\Console". There is a new child entry there "%SystemRoot%_system32_cmd.exe". I right clicked on that and selected Export:
I saved this as "cmd_settings.reg". Then I created a batch script that imports those settings, invokes my original batch script (name batch_script.bat) and then deletes what I imported in order for the command line window to return to default settings:
regedit /s cmd_settings.reg
start /wait batch_script.bat
reg delete "HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_cmd.exe" /f
This is a sample batch that could be invoked ("batch_script.bat"):
@echo off
echo test!
pause
exit
Don't forget the exit command at the end of your script if you want the reg delete line to run after the script execution.
If column dbo.patient_address.id_no
allows NULL
s then you could use this solution:
SET XACT_ABORT ON;
BEGIN TRANSACTION;
-- I assmume that [id] is the primary key of patient_address table (single column key)
-- replace the name of [id] column with the name of PK column from patient_address table
-- replace INT data type with the proper type
DECLARE @RowsForUpdate TABLE([id] INT PRIMARY KEY);
UPDATE patient_address
SET id_no = NULL
OUTPUT deleted.[id] INTO @RowsForUpdate ([id])
WHERE id_no='8008255601088'
UPDATE patient
SET id_no='7008255601088'
WHERE id_no='8008255601088'
UPDATE patient_address
SET id_no='7008255601088'
WHERE [id] IN (SELECT u.[id] FROM @RowsForUpdate u)
COMMIT;
Simplest is use list[i:i]
a = [1,2, 3, 4]
a[2:2] = [10]
Print a to check insertion
print a
[1, 2, 10, 3, 4]
You've already done it correctly by using a DateTime
parameter with the value from the DateTime
, so it should already work. Forget about ToString()
- since that isn't used here.
If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).
I have a table and the date-times in it are in the format:
2011-07-01 15:17:33.357
Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281
. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.
With TortoiseGit:
right click on the file and use
Context Menu ? Restore after commit
. This will create a copy of the file as it is. Then you can edit the file, e.g. in TortoiseGitMerge and undo all the changes you don't want to commit. After saving those changes you can commit the file.
Dynamic programming is when you use past knowledge to make solving a future problem easier.
A good example is solving the Fibonacci sequence for n=1,000,002.
This will be a very long process, but what if I give you the results for n=1,000,000 and n=1,000,001? Suddenly the problem just became more manageable.
Dynamic programming is used a lot in string problems, such as the string edit problem. You solve a subset(s) of the problem and then use that information to solve the more difficult original problem.
With dynamic programming, you store your results in some sort of table generally. When you need the answer to a problem, you reference the table and see if you already know what it is. If not, you use the data in your table to give yourself a stepping stone towards the answer.
The Cormen Algorithms book has a great chapter about dynamic programming. AND it's free on Google Books! Check it out here.
function strEndsWith(str,suffix) {
var reguex= new RegExp(suffix+'$');
if (str.match(reguex)!=null)
return true;
return false;
}
Using PuTTY's pscp.exe (which I have in an $env:path
directory):
pscp -sftp -pw passwd c:\filedump\* user@host:/Outbox/
mv c:\filedump\* c:\backup\*
Use .length
to count number of characters, and $.trim()
function to remove spaces, and replace(/ /g,'')
to replace multiple spaces with just one. Here is an example:
var str = " Hel lo ";
console.log(str.length);
console.log($.trim(str).length);
console.log(str.replace(/ /g,'').length);
Output:
20
7
5
Source: How to count number of characters in a string with JQuery
its possible using syntax:
RUNAS [/profile] [/env] [/netonly] /user:user Program
Key :
/profile Option to load the user's profile (registry)
/env Use current environment instead of user's.
/netonly Use the credentials specified only for remote connections.
/user Username in form USER@DOMAIN or DOMAIN\USER
(USER@DOMAIN is not compatible with /netonly)
Program The command to execute
example :
runas /env /user:domain\Administrator <program.exe/command you want to execute>
Not only HTML5 but a bit of JavaScript
Click [here]https://codepen.io/diegoleme/pen/surIK
HTML
<form class="pure-form">
<fieldset>
<legend>Confirm password with HTML5</legend>
<input type="password" placeholder="Password" id="password" required>
<input type="password" placeholder="Confirm Password" id="confirm_password" required>
<button type="submit" class="pure-button pure-button-primary">Confirm</button>
</fieldset>
</form>
JAVASCRIPT
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
In my case, I had to create a new app, reinstall my node packages, and copy my src document over. That worked.
I think my method is the simplest.
Form2 form2 = null;
private void SwitchFormShowClose_Click(object sender, EventArgs e)
{
if(form2 == null){
form2 = new Form2();
form2.Show();
}
else{
form2.Close();
form2 = null;
}
}
Well, URL API object avoids splitting and constructing the url's manually.
let url = new URL('https://stackoverflow.com/questions/1420881');
alert(url.origin);
Points to note, on the Watch out for common mistakes:
If your start index is 0 (or some index from begin), then, the correct code is:
var tableHeaderRowCount = 1;
var table = document.getElementById('WRITE_YOUR_HTML_TABLE_NAME_HERE');
var rowCount = table.rows.length;
for (var i = tableHeaderRowCount; i < rowCount; i++) {
table.deleteRow(tableHeaderRowCount);
}
NOTES
1. the argument for deleteRow is fixed
this is required since as we delete a row, the number of rows decrease.
i.e; by the time i reaches (rows.length - 1), or even before that row is already deleted, so you will have some error/exception (or a silent one).
2. the rowCount is taken before the for loop starts
since as we delete the "table.rows.length" will keep on changing, so again you have some issue, that only odd or even rows only gets deleted.
Hope that helps.
If you want to pass the form to the controller for validation purposes you can simply pass it as an argument to the method handling the submission. Use the form name, so for the original question it would be something like:
<button ng-click="submit(customerForm)">Save</button>
The key point was "HARD TAB" 1. Check whether you used TAB instead of whitespace 2. Check your .vimrc for "set tabstop=X"
See type assertions here:
http://golang.org/ref/spec#Type_assertions
I'd assert a sensible type (string, uint64) etc only and keep it as loose as possible, performing a conversion to the native type last.