Below is code snippet you can use to delete the bucket,
import boto3, botocore
from botocore.exceptions import ClientError
s3 = boto3.resource("s3",aws_access_key_id='Your-Access-Key',aws_secret_access_key='Your-Secret-Key')
s3.Object('Bucket-Name', 'file-name as key').delete()
If you really need it, consider redirections.
For example, on request to assets.my-domain.example.com/path/to/file
you could perform a 301 or 302 redirection to my-bucket-name.s3.amazonaws.com/path/to/file
or s3.amazonaws.com/my-bucket-name/path/to/file
(please remember that in the first case my-bucket-name
cannot contain any dots, otherwise it won't match *.s3.amazonaws.com, s3.amazonaws.com
stated in S3 certificate).
Not tested, but I believe it would work. I see few gotchas, however.
The first one is pretty obvious, an additional request to get this redirection. And I doubt you could use redirection server provided by your domain name registrar — you'd have to upload proper certificate there somehow — so you have to use your own server for this.
The second one is that you can have urls with your domain name in page source code, but when for example user opens the pic in separate tab, then address bar will display the target url.
$var += 0
probably what you want. Be warned however, if $var is string could not be converted to numeric, you'll get the error, and $var will be reset to 0:
my $var = 'abc123';
print "var = $var\n";
$var += 0;
print "var = $var\n";
logs
var = abc123
Argument "abc123" isn't numeric in addition (+) at test.pl line 7.
var = 0
New, detailed answer and explanation to an old, frequently asked question...
Short answer: If you don't add elementFormDefault="qualified"
to xsd:schema
, then the default unqualified
value means that locally declared elements are in no namespace.
There's a lot of confusion regarding what elementFormDefault
does, but this can be quickly clarified with a short example...
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:target="http://www.levijackson.net/web340/ns"
targetNamespace="http://www.levijackson.net/web340/ns">
<element name="assignments">
<complexType>
<sequence>
<element name="assignment" type="target:assignmentInfo"
minOccurs="1" maxOccurs="unbounded"/>
</sequence>
</complexType>
</element>
<complexType name="assignmentInfo">
<sequence>
<element name="name" type="string"/>
</sequence>
<attribute name="id" type="string" use="required"/>
</complexType>
</schema>
Key points:
assignment
element is locally defined.elementFormDefault
is unqualified
.elementFormDefault="qualified"
so that assignment
is in the target namespace as one would
expect.form
attribute on xs:element
declarations for which elementFormDefault
establishes default values.This XML looks like it should be valid according to the above XSD:
<assignments xmlns="http://www.levijackson.net/web340/ns"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.levijackson.net/web340/ns try.xsd">
<assignment id="a1">
<name>John</name>
</assignment>
</assignments>
Notice:
assignments
places assignments
and all of its descendents in the default namespace (http://www.levijackson.net/web340/ns
).Despite looking valid, the above XML yields the following confusing validation error:
[Error] try.xml:4:23: cvc-complex-type.2.4.a: Invalid content was found starting with element 'assignment'. One of '{assignment}' is expected.
Notes:
assignment
element but it actually found an assignment
element. (WTF){
and }
around assignment
means that validation was expecting assignment
in no namespace here. Unfortunately, when it says that it found an assignment
element, it doesn't mention that it found it in a default namespace which differs from no namespace.elementFormDefault="qualified"
to the xsd:schema
element of the XSD. This means valid XML must place elements in the target namespace when locally declared in the XSD; otherwise, valid XML must place locally declared elements in no namespace.assignment
be in no namespace. This can be achieved,
for example, by adding xmlns=""
to the assignment
element.Credits: Thanks to Michael Kay for helpful feedback on this answer.
If javascript is accepted as an answer, I made a jQuery plugin to address this issue (for more information about the issue see CSS: Truncate table cells, but fit as much as possible).
To use the plugin just type
$('selector').tableoverflow();
Plugin: https://github.com/marcogrcr/jquery-tableoverflow
Full example: http://jsfiddle.net/Cw7TD/3/embedded/result/
ListView listView = getListView();
listView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
view.setOnTouchListener(new OnTouchListener() {
private float mInitialX;
private float mInitialY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mInitialX = event.getX();
mInitialY = event.getY();
return true;
case MotionEvent.ACTION_MOVE:
final float x = event.getX();
final float y = event.getY();
final float yDiff = y - mInitialY;
if (yDiff > 0.0) {
Log.d(tag, "SCROLL DOWN");
scrollDown = true;
break;
} else if (yDiff < 0.0) {
Log.d(tag, "SCROLL up");
scrollDown = true;
break;
}
break;
}
return false;
}
});
not need to run queries to sidable FKs on sql. If you have a FK from table A to B, you should:
You can also tell the destination not to check constraints
r
opens for reading, whereas r+
opens for reading and writing. The b
is for binary.
This is spelled out in the documentation:
The most commonly-used values of mode are
'r'
for reading,'w'
for writing (truncating the file if it already exists), and'a'
for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to'r'
. The default is to use text mode, which may convert'\n'
characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append'b'
to the mode value to open the file in binary mode, which will improve portability. (Appending'b'
is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below for more possible values of mode.Modes
'r+'
,'w+'
and'a+'
open the file for updating (note that'w+'
truncates the file). Append'b'
to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the'b'
has no effect.
Maybe this could help you:
=IF(N6<10,"0-10",IF(N6<20,"10-20",IF(N6<30,"20-30",IF(N6<40,"30-40",IF(N6<50,"40-50")))))
Just replace the values and the text to small, medium and large.
Windows.Forms.Form
, so just a new window Page is, according to online documentation:
Encapsulates a page of content that can be navigated to and hosted by Windows Internet Explorer, NavigationWindow, and Frame.
So you basically use this if going you visualize some HTML content
UserControl is for cases when you want to create some reusable component (but not standalone one) to use it in multiple different Windows
Although Visual Studio does not support this (you can do some tricks and get MSBuild to compile both, but not from within Visual Studio), SharpDevelop does. You can have both in the same solution (as long as you are running Visual Studio Professional and above), so the easiest solution if you want to keep using Visual Studio is to seperate your VB code into a different project and access it that way.
I believe what you are looking for is assign_attributes
.
It's basically the same as update_attributes but it doesn't save the record:
class User < ActiveRecord::Base
attr_accessible :name
attr_accessible :name, :is_admin, :as => :admin
end
user = User.new
user.assign_attributes({ :name => 'Josh', :is_admin => true }) # Raises an ActiveModel::MassAssignmentSecurity::Error
user.assign_attributes({ :name => 'Bob'})
user.name # => "Bob"
user.is_admin? # => false
user.new_record? # => true
For completeness:
https://developer.chrome.com/multidevice/android/installtohomescreen
Does Add to homescreen work on Chrome for iOS?
No.
(along CUDA Toolkit 11.0 RC)
To solve the same issue as OP, I just had to find cudart64_101.dll on my disk (in my case C:\Program Files\NVIDIA Corporation\NvStreamSrv) and add it as variable environment (that is add value C:\Program Files\NVIDIA\Corporation\NvStreamSrv)cudart64_101.dll to user's environment variable Path).
public class BinaryConverter {
public static String binaryConverter(int number) {
String binary = "";
if (number == 1){
binary = "1";
System.out.print(binary);
return binary;
}
if (number == 0){
binary = "0";
System.out.print(binary);
return binary;
}
if (number > 1) {
String i = Integer.toString(number % 2);
binary = binary + i;
binaryConverter(number/2);
}
System.out.print(binary);
return binary;
}
}
as simple as that: echo '<a href="'.$link_address.'">Link</a>';
This will do it for you:
var yourSelect = document.getElementById( "your-select-id" );
alert( yourSelect.options[ yourSelect.selectedIndex ].value )
Listen , Make Following changes in your code if you want to show empty datetimepicker and get null when no date is selected by user, else save date.
if user will interact with datetimepicker its VALUECHANGED event will be called and there set its TAG property to 1.
Now when saving, check if its TAG is zero, then save NULL date else if TAG is 1 then pick and save Datetime picker value.
It Works like a charm.
Now if you want its value be changed back to empty by user interaction, then add checkbox and show text "Clear" with this checkbox. if user wants to clear date, simply again set its CUSTOM FORMAT property to empty string " ", and set its TAG back to 0. Thats it..
Try the following:
echo a#b#c | awk -F"#" '{$1 = ""; $NF = ""; print}' OFS=""
I was getting the same error Requires: container-selinux >= 2.9 on amazon ec2 instance(Rhel7)
I tried to add extra package rmp repo by executing
sudo yum-config-manager --enable rhui-REGION-rhel-server-extras
but it works.
followed steps from https://installdocker.blogspot.com/ and I was able to install docker.
You can use the following script in view:
<script type="text/javascript">
var BASE_URL = '<%= ResolveUrl("~/") %>';
</script>
A workaround of mine is to manipulate a model variable just for the ng-class toggling:
For example, I want to toggle class according to the state of my list:
1) Whenever my list is empty, I update my model:
$scope.extract = function(removeItemId) {
$scope.list= jQuery.grep($scope.list, function(item){return item.id != removeItemId});
if (!$scope.list.length) {
$scope.liststate = "empty";
}
}
2) Whenever my list is not empty, I set another state
$scope.extract = function(item) {
$scope.list.push(item);
$scope.liststate = "notempty";
}
3) When my list is not ever touched, I want to give another class (this is where the page is initiated):
$scope.liststate = "init";
3) I use this additional model on my ng-class:
ng-class="{'bg-empty': liststate == 'empty', 'bg-notempty': liststate == 'notempty', 'bg-init': liststate = 'init'}"
One notable difference in Python 2 is that if you're using ensure_ascii=False
, dump
will properly write UTF-8 encoded data into the file (unless you used 8-bit strings with extended characters that are not UTF-8):
dumps
on the other hand, with ensure_ascii=False
can produce a str
or unicode
just depending on what types you used for strings:
Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a
unicode
instance.
(emphasis mine). Note that it may still be a str
instance as well.
Thus you cannot use its return value to save the structure into file without checking which
format was returned and possibly playing with unicode.encode
.
This of course is not valid concern in Python 3 any more, since there is no more this 8-bit/Unicode confusion.
As for load
vs loads
, load
considers the whole file to be one JSON document, so you cannot use it to read multiple newline limited JSON documents from a single file.
Normal Class
: A Java class
Java Beans
:
Pojo
:
Plain Old Java Object is a Java object not bound by any restriction other than those forced by the Java Language Specification. I.e., a POJO should not have to
((\n.*){0,3})(.*)\W*\.txt
This will select all the content before the particular word ".txt" including any context in different lines up to 3 lines
-XX:PermSize -XX:MaxPermSize
are used to set size for Permanent Generation.
Permanent Generation: The Permanent Generation is where class files are kept. These are the result of compiled classes and JSP pages. If this space is full, it triggers a Full Garbage Collection. If the Full Garbage Collection cannot clean out old unreferenced classes and there is no room left to expand the Permanent Space, an Out-of- Memory error (OOME) is thrown and the JVM will crash.
After reading around alot, only this worked: In class to set Shared preferences:
SharedPreferences userDetails = getApplicationContext().getSharedPreferences("test", MODE_PRIVATE);
SharedPreferences.Editor edit = userDetails.edit();
edit.clear();
edit.putString("test1", "1");
edit.putString("test2", "2");
edit.commit();
In AlarmReciever:
SharedPreferences userDetails = context.getSharedPreferences("test", Context.MODE_PRIVATE);
String test1 = userDetails.getString("test1", "");
String test2 = userDetails.getString("test2", "");
In my case,
word-break: break-all;
worked perfecly, hope it helps any other newcomer like me.
It is a reference to the current file name. In the file foo.rb
, __FILE__
would be interpreted as "foo.rb"
.
Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:
# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__
Running ruby test.rb
will output
test.rb
/full/path/to/dir2/test.rb
It really doesn't matter. Just make sure you name your variables and functions descriptively. Also be consistent.
Nowt worse than seeing code like this:
int anInt; // Great name for a variable there ...
int myVar = Func( anInt ); // And on this line a great name for a function and myVar
// lacks the consistency already, poorly, laid out!
Edit: As pointed out by my commenter that consistency needs to be maintained across an entire team. As such it doesn't matter WHAT method you chose, as long as that consistency is maintained. There is no right or wrong method, however. Every team I've worked in has had different ideas and I've adapted to those.
I needed to do the same and had to query a query to get the result
I set my first query up to bring in all IDs from the table and all other information needed to filter:
SELECT tMAIN.tLOTS.NoContract, tMAIN.ID
FROM tMAIN INNER JOIN tLOTS ON tMAIN.ID = tLOTS.id
WHERE (((tLOTS.NoContract)=False));
Save this as Q04_1 -0 this returned 1229 results (there are 63 unique records to query - soime with multiple LOTs)
SELECT DISTINCT ID
FROM q04_1;
Saved that as q04_2
I then wrote another query which brought in the required information linked to the ID
SELECT q04_2.ID, tMAIN.Customer, tMAIN.Category
FROM q04_2 INNER JOIN tMAIN ON q04_2.ID = tMAIN.ID;
Worked a treat and got me exactly what I needed - 63 unique records returned with customer and category details.
This is how I worked around it as I couldn't get the Group By working at all - although I am rather "wet behind the ears" weith SQL (so please be gentle and constructive with feedback)
Even this question is already answered I'd add the solution in Regex.
>>> import re
>>> file_suffix = ".*(\..*)"
>>> result = re.search(file_suffix, "somefile.ext")
>>> result.group(1)
'.ext'
I don't think the jar tool supports this natively, but you can just unzip a JAR file with "unzip" and specify the output directory with that with the "-d" option, so something like:
$ unzip -d /home/foo/bar/baz /home/foo/bar/Portal.ear Binaries.war
Wow! Mean this that you must learn a different programming language just to send two keys to the keyboard? There are simpler ways for you to achieve the same thing. :-)
The Batch file below is an example that start another program (cmd.exe in this case), send a command to it and then send an Up Arrow key, that cause to recover the last executed command. The Batch file is simple enough to be understand with no problems, so you may modify it to fit your needs.
@if (@CodeSection == @Batch) @then
@echo off
rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"
rem Start the other program in the same Window
start "" /B cmd
%SendKeys% "echo off{ENTER}"
set /P "=Wait and send a command: " < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "echo Hello, world!{ENTER}"
set /P "=Wait and send an Up Arrow key: [" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{UP}"
set /P "=] Wait and send an Enter key:" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{ENTER}"
%SendKeys% "exit{ENTER}"
goto :EOF
@end
// JScript section
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));
For a list of key names for SendKeys, see: http://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx
For example:
LEFT ARROW {LEFT}
RIGHT ARROW {RIGHT}
For a further explanation of this solution, see: GnuWin32 openssl s_client conn to WebSphere MQ server not closing at EOF, hangs
OO Abstraction occurs during class level design, with the objective of hiding the implementation complexity of how the the features offered by an API / design / system were implemented, in a sense simplifying the 'interface' to access the underlying implementation.
The process of abstraction can be repeated at increasingly 'higher' levels (layers) of classes, which enables large systems to be built without increasing the complexity of code and understanding at each layer.
For example, a Java developer can make use of the high level features of FileInputStream without concern for how it works (i.e. file handles, file system security checks, memory allocation and buffering will be managed internally, and are hidden from consumers). This allows the implementation of FileInputStream
to be changed, and as long as the API (interface) to FileInputStream
remains consistent, code built against previous versions will still work.
Similarly, when designing your own classes, you will want to hide internal implementation details from others as far as possible.
In the Booch definition1, OO Encapsulation is achieved through Information Hiding, and specifically around hiding internal data (fields / members representing the state) owned by a class instance, by enforcing access to the internal data in a controlled manner, and preventing direct, external change to these fields, as well as hiding any internal implementation methods of the class (e.g. by making them private).
For example, the fields of a class can be made private
by default, and only if external access to these was required, would a get()
and/or set()
(or Property
) be exposed from the class. (In modern day OO languages, fields can be marked as readonly
/ final
/ immutable
which further restricts change, even within the class).
Example where NO information hiding has been applied (Bad Practice):
class Foo {
// BAD - NOT Encapsulated - code external to the class can change this field directly
// Class Foo has no control over the range of values which could be set.
public int notEncapsulated;
}
Example where field encapsulation has been applied:
class Bar {
// Improvement - access restricted only to this class
private int encapsulatedPercentageField;
// The state of Bar (and its fields) can now be changed in a controlled manner
public void setEncapsulatedField(int percentageValue) {
if (percentageValue >= 0 && percentageValue <= 100) {
encapsulatedPercentageField = percentageValue;
}
// else throw ... out of range
}
}
Example of immutable / constructor-only initialization of a field:
class Baz {
private final int immutableField;
public void Baz(int onlyValue) {
// ... As above, can also check that onlyValue is valid
immutableField = onlyValue;
}
// Further change of `immutableField` outside of the constructor is NOT permitted, even within the same class
}
Re : Abstraction vs Abstract Class
Abstract classes are classes which promote reuse of commonality between classes, but which themselves cannot directly be instantiated with new()
- abstract classes must be subclassed, and only concrete
(non abstract) subclasses may be instantiated. Possibly one source of confusion between Abstraction
and an abstract class
was that in the early days of OO, inheritance was more heavily used to achieve code reuse (e.g. with associated abstract base classes). Nowadays, composition is generally favoured over inheritance, and there are more tools available to achieve abstraction, such as through Interfaces, events / delegates / functions, traits / mixins etc.
Re : Encapsulation vs Information Hiding
The meaning of encapsulation appears to have evolved over time, and in recent times, encapsulation
can commonly also used in a more general sense when determining which methods, fields, properties, events etc to bundle into a class.
Quoting Wikipedia:
In the more concrete setting of an object-oriented programming language, the notion is used to mean either an information hiding mechanism, a bundling mechanism, or the combination of the two.
For example, in the statement
I've encapsulated the data access code into its own class
.. the interpretation of encapsulation is roughly equivalent to the Separation of Concerns or the Single Responsibility Principal (the "S" in SOLID), and could arguably be used as a synonym for refactoring.
[1] Once you've seen Booch's encapsulation cat picture you'll never be able to forget encapsulation - p46 of Object Oriented Analysis and Design with Applications, 2nd Ed
You can implement this using Java 8 lambdas.
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
public class LevelLogger {
private static final Logger LOGGER = LoggerFactory.getLogger(LevelLogger.class);
private static final Map<Level, LoggingFunction> map;
static {
map = new HashMap<>();
map.put(Level.TRACE, (o) -> LOGGER.trace(o));
map.put(Level.DEBUG, (o) -> LOGGER.debug(o));
map.put(Level.INFO, (o) -> LOGGER.info(o));
map.put(Level.WARN, (o) -> LOGGER.warn(o));
map.put(Level.ERROR, (o) -> LOGGER.error(o));
}
public static void log(Level level, String s) {
map.get(level).log(s);
}
@FunctionalInterface
private interface LoggingFunction {
public void log(String arg);
}
}
Friend. Use this way, There will be no "Undefined variable message" and it will work fine.
<?php
if(isset($_POST['SubmitButton'])){
$price = $_POST["price"];
$qty = $_POST["qty"];
$message = $price*$qty;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" method="post">
<input type="number" name="price"> <br>
<input type="number" name="qty"><br>
<input type="submit" name="SubmitButton">
</form>
<?php echo "The Answer is" .$message; ?>
</body>
</html>
After making the id
unique across the document
,You have to use event delegation
$("#container").on("click", "buttonid", function () {
alert("Hi");
});
I combined Phil and jqno's answer and made untoggle comments with spaces:
autocmd FileType c,cpp,java,scala let b:comment_leader = '//'
autocmd FileType sh,ruby,python let b:comment_leader = '#'
autocmd FileType conf,fstab let b:comment_leader = '#'
autocmd FileType tex let b:comment_leader = '%'
autocmd FileType mail let b:comment_leader = '>'
autocmd FileType vim let b:comment_leader = '"'
function! CommentToggle()
execute ':silent! s/\([^ ]\)/' . escape(b:comment_leader,'\/') . ' \1/'
execute ':silent! s/^\( *\)' . escape(b:comment_leader,'\/') . ' \?' . escape(b:comment_leader,'\/') . ' \?/\1/'
endfunction
map <F7> :call CommentToggle()<CR>
how it works:
Lets assume we work with #-comments.
The first command s/\([^ ]\)/# \1/
searches for the first non-space character [^ ]
and replaces that with #
+itself
. The itself-replacement is done by the \(..\)
in the search-pattern and \1
in the replacement-pattern.
The second command s/^\( *\)# \?# \?/\1/
searches for lines starting with a double comment ^\( *\)# \?# \?
(accepting 0 or 1 spaces in between comments) and replaces those simply with the non-comment part \( *\)
(meaning the same number of preceeding spaces).
For more details about vim patterns check this out.
I think it is going to be possible soon in AMD FirePro GPU's, see press release here but support is coming 2016 Q1 for the developing tools:
An early access program for the "Boltzmann Initiative" tools is planned for Q1 2016.
Simply, @Id: This annotation specifies the primary key of the entity.
@GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used.
GenerationType enum defines four strategies:
1. Generation Type . TABLE,
2. Generation Type. SEQUENCE,
3. Generation Type. IDENTITY
4. Generation Type. AUTO
GenerationType.SEQUENCE
With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities.
GenerationType.TABLE
With this strategy, underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities.
GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.
GenerationType.AUTO
This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used.
Reference:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html
You can't compare object data like this:s1.getParent() == s2
- this will compare the object references. You should override equals function
for Foo class and then compare them like this s1.getParent().equals(s2)
Your Fundamentals are wrong, the program won't work, so go through the basics and rewrite the program.
Some of the corrections you must make are:
1) You must make a variable of semaphore type
sem_t semvar;
2) The functions sem_wait()
, sem_post()
require the semaphore variable but you are passing the semaphore id, which makes no sense.
sem_wait(&semvar);
//your critical section code
sem_post(&semvar);
3) You are passing the semaphore to sem_wait()
and sem_post()
without initializing it. You must initialize it to 1 (in your case) before using it, or you will have a deadlock.
ret = semctl( semid, 1, SETVAL, sem);
if (ret == 1)
perror("Semaphore failed to initialize");
Study the semaphore API's from the man page and go through this example.
NSCharacterSet *charSet = NSCharacterSet.newlineCharacterSet;
NSString *formatted = [[unformatted componentsSeparatedByCharactersInSet:charSet] componentsJoinedByString:@"\n"];
This is old but here's another way.
#include <stdio.h>
#define atoa(x) #x
int main(int argc, char *argv[])
{
char *string = atoa(1234567890);
printf("%s\n", string);
return 0;
}
variable=$(ps -ef | awk '/[p]ort 10/ {print $12}')
The [p]
is a neat trick to remove the search from showing from ps
@Jeremy
If you post the output of ps -ef | grep "port 10"
, and what you need from the line, it would be more easy to help you getting correct syntax
Code snippet below. I'm providing a small scenario.
import tkinter as tk
from tkinter import *
root = Tk()
def exit():
if askokcancel("Quit", "Do you really want to quit?"):
root.destroy()
menubar = Menu(root, background='#000099', foreground='white',
activebackground='#004c99', activeforeground='white')
fileMenu = Menu(menubar, tearoff=0, background="grey", foreground='black',
activebackground='#004c99', activeforeground='white')
menubar.add_cascade(label='File', menu=fileMenu)
fileMenu.add_command(label='Exit', command=exit)
root.config(bg='#2A2C2B',menu=menubar)
if __name__ == '__main__':
root.mainloop()
I have created a blank window here & add file menu option on the same window(root window), where I only add one option exit.
Then simply run mainloop for root.
Try to do it once
One thing you might want to look at is the Commons DBCP project. It provides a BasicDataSource that is configured fairly similarly to your example. To use that you need the database vendor's JDBC JAR in your classpath and you have to specify the vendor's driver class name and the database URL in the proper format.
Edit:
If you want to configure a BasicDataSource
for MySQL, you would do something like this:
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUsername("username");
dataSource.setPassword("password");
dataSource.setUrl("jdbc:mysql://<host>:<port>/<database>");
dataSource.setMaxActive(10);
dataSource.setMaxIdle(5);
dataSource.setInitialSize(5);
dataSource.setValidationQuery("SELECT 1");
Code that needs a DataSource
can then use that.
const cars = ['Volvo', 'Saab', 'Mervedes', 'Audi'];_x000D_
_x000D_
let domSelect = document.createElement('select');_x000D_
domSelect.multiple = true;_x000D_
document.getElementsByTagName('body')[0].appendChild(domSelect);_x000D_
_x000D_
_x000D_
for (const i in cars) {_x000D_
let optionSelect = document.createElement('option');_x000D_
_x000D_
let optText = document.createTextNode(cars[i]);_x000D_
optionSelect.appendChild(optText);_x000D_
_x000D_
document.getElementsByTagName('select')[0].appendChild(optionSelect);_x000D_
}
_x000D_
You don't have to uninstall the Google Play version if App Signing by Google Play is enabled for your app, follow the steps:
1. Make a signed version of your app with your release key
2. Go to Google Play Developer console
3. Create a closed track release (alpha or beta release) with the new signed version of your app
4. You can now download the apk signed by App Signing by Google Play, choose derived APK
The reason is App Signing by Google Play signs release apps with different keys, if you have an app installed from Play Store, and you want to test the new release version app (generated from Android Studio) in your phone, "App not installed" happens since the old version and the new version were signed by two different keys: one with App Signing by Google Play and one with your key.
If someone wants to transfer file from windows host to vagrant, then this solution worked for me.
1. Make sure to install **winscp** on your windows system
2. run **vagrant up** command
3. run **vagrant ssh-config** command and note down below details
4. Enter Hostname, Port, Username: vagrant, Password: vagrant in winscp and select **SCP**, file protocol
5. In most cases, hostname: 127.0.0.1, port: 2222, username: vagrant, password: vagrant.
You should be able to see directories in your vagrant machine.
For a web application, to get the current web application root directory, generally call by web page for the current incoming request:
HttpContext.Current.Server.MapPath();
System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
string result = Path.GetTempPath();
https://docs.microsoft.com/en-us/dotnet/api/system.io.path.gettemppath
I came across this issue myself. I had the need to conditionally validate parts of a form while the form was being constructed based on steps (i.e. certain inputs were dynamically appended during runtime). As a result, sometimes a select dropdown would need validation, and sometimes it would not. However, by the end of the ordeal, it needed to be validated. As a result, I needed a robust method which was not a workaround. I consulted the source code for jquery.validate
.
Here is what I came up with:
Here is what it looks like in code:
function clearValidation(formElement){
//Internal $.validator is exposed through $(form).validate()
var validator = $(formElement).validate();
//Iterate through named elements inside of the form, and mark them as error free
$('[name]',formElement).each(function(){
validator.successList.push(this);//mark as error free
validator.showErrors();//remove error messages if present
});
validator.resetForm();//remove error class on name elements and clear history
validator.reset();//remove all error and success data
}
//used
var myForm = document.getElementById("myFormId");
clearValidation(myForm);
minified as a jQuery extension:
$.fn.clearValidation = function(){var v = $(this).validate();$('[name]',this).each(function(){v.successList.push(this);v.showErrors();});v.resetForm();v.reset();};
//used:
$("#formId").clearValidation();
:datetime (8 bytes)
:timestamp (4 bytes)
This is valid YAML:
jobs:
- name: A
schedule: "0 0/5 * 1/1 * ? *"
type: mongodb.cluster
config:
host: mongodb://localhost:27017/admin?replicaSet=rs
minSecondaries: 2
minOplogHours: 100
maxSecondaryDelay: 120
- name: B
schedule: "0 0/5 * 1/1 * ? *"
type: mongodb.cluster
config:
host: mongodb://localhost:27017/admin?replicaSet=rs
minSecondaries: 2
minOplogHours: 100
maxSecondaryDelay: 120
Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.
I had a similar problem on a raspberry pi.
The problem was that http requires SSL and so I needed to force it to use https to get around this requirement.
sudo pip install --upgrade pip --index-url=https://pypi.python.org/simple
or
sudo pip-3.2 --upgrade pip --index-url=https://pypi.python.org/simple/
(UPDATED with examples for Bootstrap v4, v3 and v3)
Examples of forms with validation classes for the past few major versions of Bootstrap.
Bootstrap v4
See the live version on codepen
<div class="container">
<form>
<div class="form-group row">
<label for="inputEmail" class="col-sm-2 col-form-label text-success">Email</label>
<div class="col-sm-7">
<input type="email" class="form-control is-valid" id="inputEmail" placeholder="Email">
</div>
</div>
<div class="form-group row">
<label for="inputPassword" class="col-sm-2 col-form-label text-danger">Password</label>
<div class="col-sm-7">
<input type="password" class="form-control is-invalid" id="inputPassword" placeholder="Password">
</div>
<div class="col-sm-3">
<small id="passwordHelp" class="text-danger">
Must be 8-20 characters long.
</small>
</div>
</div>
</form>
</div>
Bootstrap v3
See the live version on codepen
<form role="form">
<div class="form-group has-warning">
<label class="control-label" for="inputWarning">Input with warning</label>
<input type="text" class="form-control" id="inputWarning">
<span class="help-block">Something may have gone wrong</span>
</div>
<div class="form-group has-error">
<label class="control-label" for="inputError">Input with error</label>
<input type="text" class="form-control" id="inputError">
<span class="help-block">Please correct the error</span>
</div>
<div class="form-group has-info">
<label class="control-label" for="inputError">Input with info</label>
<input type="text" class="form-control" id="inputError">
<span class="help-block">Username is taken</span>
</div>
<div class="form-group has-success">
<label class="control-label" for="inputSuccess">Input with success</label>
<input type="text" class="form-control" id="inputSuccess" />
<span class="help-block">Woohoo!</span>
</div>
</form>
Bootstrap v2
See the live version on jsfiddle
The .error
, .success
, .warning
and .info
classes are appended to the .control-group
. This is standard Bootstrap markup and styling in v2. Just follow that and you're in good shape. Of course you can go beyond with your own styles to add a popup or "inline flash" if you prefer, but if you follow Bootstrap convention and hang those validation classes on the .control-group
it will stay consistent and easy to manage (at least since you'll continue to have the benefit of Bootstrap docs and examples)
<form class="form-horizontal">
<div class="control-group warning">
<label class="control-label" for="inputWarning">Input with warning</label>
<div class="controls">
<input type="text" id="inputWarning">
<span class="help-inline">Something may have gone wrong</span>
</div>
</div>
<div class="control-group error">
<label class="control-label" for="inputError">Input with error</label>
<div class="controls">
<input type="text" id="inputError">
<span class="help-inline">Please correct the error</span>
</div>
</div>
<div class="control-group info">
<label class="control-label" for="inputInfo">Input with info</label>
<div class="controls">
<input type="text" id="inputInfo">
<span class="help-inline">Username is taken</span>
</div>
</div>
<div class="control-group success">
<label class="control-label" for="inputSuccess">Input with success</label>
<div class="controls">
<input type="text" id="inputSuccess">
<span class="help-inline">Woohoo!</span>
</div>
</div>
</form>
From http://www.postgresql.org/docs/current/interactive/datatype.html
Note: Prior to PostgreSQL 7.3, serial implied UNIQUE. This is no longer automatic. If you wish a serial column to be in a unique constraint or a primary key, it must now be specified, same as with any other data type.
var str = "you can enter maximum 500 choices";
str.replace(/[^0-9]/g, "");
console.log(str); // "500"
On our site we have pages where the content is static, and pages where it is loaded in with AJAX. On one page (a search page), there were cases when the AJAX results would more than fill the page, and cases where it would return no results. In order for the background image to fill the page in all cases we had to apply the following CSS:
html {
margin: 0px;
height: 100%;
width: 100%;
}
body {
margin: 0px;
min-height: 100%;
width: 100%;
}
height
for the html
and min-height
for the body
.
PowerShell 2.0 replacement for [string]::IsNullOrWhiteSpace()
is string -notmatch "\S"
("\S" = any non-whitespace character)
> $null -notmatch "\S"
True
> " " -notmatch "\S"
True
> " x " -notmatch "\S"
False
Performance is very close:
> Measure-Command {1..1000000 |% {[string]::IsNullOrWhiteSpace(" ")}}
TotalMilliseconds : 3641.2089
> Measure-Command {1..1000000 |% {" " -notmatch "\S"}}
TotalMilliseconds : 4040.8453
The main use of anchor tags - <a></a>
- is as hyperlinks. That basically means that they take you somewhere. Hyperlinks require the href
property, because it specifies a location.
A hash - #
within a hyperlink specifies an html element id to which the window should be scrolled.
href="#some-id"
would scroll to an element on the current page such as <div id="some-id">
.
href="//site.com/#some-id"
would go to site.com
and scroll to the id on that page.
href="#"
doesn't specify an id name, but does have a corresponding location - the top of the page. Clicking an anchor with href="#"
will move the scroll position to the top.
This is the expected behavior according to the w3 documentation.
An example where a hyperlink placeholder makes sense is within template previews. On single page demos for templates, I have often seen <a href="#">
so that the anchor tag is a hyperlink, but doesn't go anywhere. Why not leave the href
property blank? A blank href
property is actually a hyperlink to the current page. In other words, it will cause a page refresh. As I discussed, href="#"
is also a hyperlink, and causes scrolling. Therefore, the best solution for hyperlink placeholders is actually href="#!"
The idea here is that there hopefully isn't an element on the page with id="!"
(who does that!?) and the hyperlink therefore refers to nothing - so nothing happens.
Another question that you may be wondering is, "Why not just leave the href property off?". A common response I've heard is that the href
property is required, so it "should" be present on anchors. This is FALSE! The href
property is required only for an anchor to actually be a hyperlink! Read this from w3. So, why not just leave it off for placeholders? Browsers render default styles for elements and will change the default style of an anchor tag that doesn't have the href property. Instead, it will be considered like regular text. It even changes the browser's behavior regarding the element. The status bar (bottom of the screen) will not be displayed when hovering on an anchor without the href property. It is best to use a placeholder href value on an anchor to ensure it is treated as a hyperlink.
See this demo demonstrating style and behavior differences.
Python 3 result for the OP's tests: (best of 3 for each)
with lambda: 18.978000981995137
without lambda: 8.110567473006085
for loop: 10.795806062000338
with lambda (no 0): 26.612515013999655
without lambda (no 0): 14.704098362999503
for loop (no 0): 14.93075215499266
class Timer
{
private $startTime = null;
public function __construct($showSeconds = true)
{
$this->startTime = microtime(true);
echo 'Working - please wait...' . PHP_EOL;
}
public function __destruct()
{
$endTime = microtime(true);
$time = $endTime - $this->startTime;
$hours = (int)($time / 60 / 60);
$minutes = (int)($time / 60) - $hours * 60;
$seconds = (int)$time - $hours * 60 * 60 - $minutes * 60;
$timeShow = ($hours == 0 ? "00" : $hours) . ":" . ($minutes == 0 ? "00" : ($minutes < 10 ? "0" . $minutes : $minutes)) . ":" . ($seconds == 0 ? "00" : ($seconds < 10 ? "0" . $seconds : $seconds));
echo 'Job finished in ' . $timeShow . PHP_EOL;
}
}
$t = new Timer(); // echoes "Working, please wait.."
[some operations]
unset($t); // echoes "Job finished in h:m:s"
Adding a reference to System.Net.Http.Formatting.dll may cause DLL mismatch issues. Right now, System.Net.Http.Formatting.dll appears to reference version 4.5.0.0 of Newtonsoft.Json.DLL, whereas the latest version is 6.0.0.0. That means you'll need to also add a binding redirect to avoid a .NET Assembly exception if you reference the latest Newtonsoft NuGet package or DLL:
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
So an alternative solution to adding a reference to System.Net.Http.Formatting.dll is to read the response as a string and then desearalize yourself with JsonConvert.DeserializeObject(responseAsString). The full method would be:
public async Task<T> GetHttpResponseContentAsType(string baseUrl, string subUrl)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(subUrl);
response.EnsureSuccessStatusCode();
var responseAsString = await response.Content.ReadAsStringAsync();
var responseAsConcreteType = JsonConvert.DeserializeObject<T>(responseAsString);
return responseAsConcreteType;
}
}
If your expected output is a single line, you can simply remove all newline characters from the output. It would not be uncommon to pipe to the tr
utility, or to Perl if preferred:
wc -l < log.txt | tr -d '\n'
wc -l < log.txt | perl -pe 'chomp'
You can also use command substitution to remove the trailing newline:
echo -n "$(wc -l < log.txt)"
printf "%s" "$(wc -l < log.txt)"
If your expected output may contain multiple lines, you have another decision to make:
If you want to remove MULTIPLE newline characters from the end of the file, again use cmd substitution:
printf "%s" "$(< log.txt)"
If you want to strictly remove THE LAST newline character from a file, use Perl:
perl -pe 'chomp if eof' log.txt
Note that if you are certain you have a trailing newline character you want to remove, you can use head
from GNU coreutils to select everything except the last byte. This should be quite quick:
head -c -1 log.txt
Also, for completeness, you can quickly check where your newline (or other special) characters are in your file using cat
and the 'show-all' flag -A
. The dollar sign character will indicate the end of each line:
cat -A log.txt
Quick work around
Simply enclose the list within a new list, as done for col2 in the data frame below. The reason it works is that python takes the outer list (of lists) and converts it into a column as if it were containing normal scalar items, which is lists in our case and not normal scalars.
mydict={'col1':[1,2,3],'col2':[[1, 4], [2, 5], [3, 6]]}
data=pd.DataFrame(mydict)
data
col1 col2
0 1 [1, 4]
1 2 [2, 5]
2 3 [3, 6]
a WebMethod which requires a ContextKey,
[WebMethod]
public string[] GetValues(string prefixText, int count, string contextKey)
when this key is not set, got the exception.
Fixing it by assigning AutoCompleteExtender's key.
ac.ContextKey = "myKey";
It's just PHP, not HTML.
It parses all HTML fields with [] into an array.
So you can have
<input type="checkbox" name="food[]" value="apple" />
<input type="checkbox" name="food[]" value="pear" />
and when submitted, PHP will make $_POST['food'] an array, and you can access its elements like so:
echo $_POST['food'][0]; // would output first checkbox selected
or to see all values selected:
foreach( $_POST['food'] as $value ) {
print $value;
}
Anyhow, don't think there is a specific name for it
I had faced he similar problem however it got resolved once i renamed the file , so i would suggest that you should
"Just rename the file"
"N/A"
is not an integer. It must throw NumberFormatException
if you try to parse it to an integer.
Check before parsing or handle Exception
properly.
Exception Handling
try{
int i = Integer.parseInt(input);
} catch(NumberFormatException ex){ // handle your exception
...
}
or - Integer pattern matching -
String input=...;
String pattern ="-?\\d+";
if(input.matches("-?\\d+")){ // any positive or negetive integer or not!
...
}
An example (axios_example.js) using Axios in Node.js:
const axios = require('axios');
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
app.get('/search', function(req, res) {
let query = req.query.queryStr;
let url = `https://your.service.org?query=${query}`;
axios({
method:'get',
url,
auth: {
username: 'xxxxxxxxxxxxx',
password: 'xxxxxxxxxxxxx'
}
})
.then(function (response) {
res.send(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
});
var server = app.listen(port);
Be sure in your project directory you do:
npm init
npm install express
npm install axios
node axios_example.js
You can then test the Node.js REST API using your browser at: http://localhost:5000/search?queryStr=xxxxxxxxx
A lazy way to do this is with the UTF-8 entity code for a half circle \25E0
(aka ◠
), which looks like ? and then keyframe animate it. It's a simple as:
.busy
{
animation: spin 1s infinite linear;
display:inline-block;
font-weight: bold;
font-family: sans-serif;
font-size: 35px;
font-style:normal;
color:#555;
}
.busy::before
{
content:"\25E0";
}
@keyframes spin
{
0% {transform: rotate(0deg);}
100% {transform: rotate(359deg);}
}
_x000D_
<i class="busy"></i>
_x000D_
Have you Googled for "weblogic ExpressionMap"? Do you know what it is and what it does?
Looks like you definitely need to be compiling alongside Weblogic and with Weblogic's jars included in your Eclipse classpath, if you're not already.
If you're not already working with Weblogic, then you need to find out what in the world is referencing it. You might need to do some heavy-duty grepping on your jars, classfiles, and/or source files looking for which ones include the string "weblogic".
If I had to include something that was relying on this Weblogic class, but couldn't use Weblogic, I'd be tempted to try to reverse-engineer a compatible class. Create your own weblogic.utils.expressions.ExpressionMap class; see if everything compiles; use any resultant errors or warnings at compile-time or runtime to give you clues as to what methods and other members need to be in this class. Make stub methods that do nothing or return null if possible.
see this bin: http://jsbin.com/yacom/2/edit
should set parent element to
display:table-cell;
vertical-align:middle;
text-align:center;
the main reason for avoiding throwing an exception is that there is a lot of overhead involved with throwing an exception.
One thing the article below states is that an exception is for an exceptional conditions and errors.
A wrong user name is not necessarily a program error but a user error...
Here is a decent starting point for exceptions within .NET: http://msdn.microsoft.com/en-us/library/ms229030(VS.80).aspx
To plot an equation that is not solved for a specific variable (like circle or hyperbola):
import numpy as np
import matplotlib.pyplot as plt
plt.figure() # Create a new figure window
xlist = np.linspace(-2.0, 2.0, 100) # Create 1-D arrays for x,y dimensions
ylist = np.linspace(-2.0, 2.0, 100)
X,Y = np.meshgrid(xlist, ylist) # Create 2-D grid xlist,ylist values
F = X**2 + Y**2 - 1 # 'Circle Equation
plt.contour(X, Y, F, [0], colors = 'k', linestyles = 'solid')
plt.show()
More about it: http://courses.csail.mit.edu/6.867/wiki/images/3/3f/Plot-python.pdf
You can concatenate strings a number of ways:
let a = "Hello"
let b = "World"
let first = a + ", " + b
let second = "\(a), \(b)"
You could also do:
var c = "Hello"
c += ", World"
I'm sure there are more ways too.
Bit of description
let
creates a constant. (sort of like an NSString
). You can't change its value once you have set it. You can still add it to other things and create new variables though.
var
creates a variable. (sort of like NSMutableString
) so you can change the value of it. But this has been answered several times on Stack Overflow, (see difference between let and var).
Note
In reality let
and var
are very different from NSString
and NSMutableString
but it helps the analogy.
If you treat the content as text, not HTML, then DOM operations should cause the data to be properly encoded. Here's how you'd do it in jQuery:
$('#container').text(xmlString);
Here's how you'd do it with standard DOM methods:
document.getElementById('container')
.appendChild(document.createTextNode(xmlString));
If you're placing the XML inside of HTML through server-side scripting, there are bound to be encoding functions to allow you to do that (if you add what your server-side technology is, we can give you specific examples of how you'd do it).
To get the absolute position of an UI element within the window you can use:
Point position = desiredElement.PointToScreen(new Point(0d, 0d));
If you are within an User Control, and simply want relative position of the UI element within that control, simply use:
Point position = desiredElement.PointToScreen(new Point(0d, 0d)),
controlPosition = this.PointToScreen(new Point(0d, 0d));
position.X -= controlPosition.X;
position.Y -= controlPosition.Y;
(Google search brought me to this question even though I did not ask for perl)
I had a problem with running scripts (albeit bash not perl). Apache had a config of ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
however Apache error log showed File does not exist: /var/www/cgi-bin/test.html
.
Tried putting the script in both /usr/lib/cgi-bin/
and /var/www/cgi-bin/
but neither were working.
After a prolonged googling session what cracked it for me was
sudo a2enmod cgi
and everything fell into place using /usr/lib/cgi-bin/
.
Decompile it with ILDASM, and look at the version of mscorlib that is being referenced (should be pretty much right at the top).
select Max(Salary) as SecondHighestSalary from Employee where Salary not in (select max(Salary) from Employee)
better to use touchstart
event with .on()
jQuery method:
$(window).load(function() { // better to use $(document).ready(function(){
$('.List li').on('click touchstart', function() {
$('.Div').slideDown('500');
});
});
And i don't understand why you are using $(window).load()
method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready()
method which does not wait for each element on the page to be loaded first.
This is an answer based on jluckyiv's, but I think it is better and simpler to change Javascript as follows.
browser.loadUrl("javascript:HTMLOUT.processHTML(document.documentElement.outerHTML);");
I would say that the specification does not prevent someone from creating an engine that runs javascript on multiple threads, requiring the code to perform synchronization for accessing shared object state.
I think the single-threaded non-blocking paradigm came out of the need to run javascript in browsers where ui should never block.
Nodejs has followed the browsers' approach.
Rhino engine however, supports running js code in different threads. The executions cannot share context, but they can share scope. For this specific case the documentation states:
..."Rhino guarantees that accesses to properties of JavaScript objects are atomic across threads, but doesn't make any more guarantees for scripts executing in the same scope at the same time.If two scripts use the same scope simultaneously, the scripts are responsible for coordinating any accesses to shared variables."
From reading Rhino documentation I conclude that that it can be possible for someone to write a javascript api that also spawns new javascript threads, but the api would be rhino-specific (e.g. node can only spawn a new process).
I imagine that even for an engine that supports multiple threads in javascript there should be compatibility with scripts that do not consider multi-threading or blocking.
Concearning browsers and nodejs the way I see it is:
So, in case of browsers and nodejs (and probably a lot of other engines) javascript is not multithreaded but the engines themselves are.
The presence of web-workers justifies further that javascript can be multi-threaded, in the sense that someone can create code in javascript that will run on a separate thread.
However: web-workers do not curry the problems of traditional threads who can share execution context. Rules 2 and 3 above still apply, but this time the threaded code is created by the user (js code writer) in javascript.
The only thing to consider is the number of spawned threads, from an efficiency (and not concurrency) point of view. See below:
The Worker interface spawns real OS-level threads, and mindful programmers may be concerned that concurrency can cause “interesting” effects in your code if you aren't careful.
However, since web workers have carefully controlled communication points with other threads, it's actually very hard to cause concurrency problems. There's no access to non-threadsafe components or the DOM. And you have to pass specific data in and out of a thread through serialized objects. So you have to work really hard to cause problems in your code.
Besides theory, always be prepared about possible corner cases and bugs described on the accepted answer
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size: 16px;_x000D_
text-align:center;_x000D_
line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size: 16px;_x000D_
text-align:center;_x000D_
line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size: 16px;_x000D_
text-align:center;_x000D_
line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
Thread.Sleep(50);
The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.
This method does not perform standard COM and SendMessage pumping. If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.
Thread.Join
Suppose you want to write that in the same file, you can do as follows:
Set-Content -Path "C:\temp\Newtext.txt" -Value (get-content -Path "c:\Temp\Newtext.txt" | Select-String -Pattern 'H\|159' -NotMatch)
I've used below command to copy from local linux Centos 7 to AWS EC2.
scp -i user_key.pem file.txt [email protected]:/home/ec2-user
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class Program
{
public static void Main()
{
var key = Encoding.UTF8.GetBytes("SUkbqO2ycDo7QwpR25kfgmC7f8CoyrZy");
var data = Encoding.UTF8.GetBytes("testData");
//Encrypt data
var encrypted = CryptoHelper.EncryptData(data,key);
//Decrypt data
var decrypted = CryptoHelper.DecryptData(encrypted,key);
//Display result
Console.WriteLine(Encoding.UTF8.GetString(decrypted));
}
}
public static class CryptoHelper
{
public static byte[] EncryptData(byte[] data, byte[] key)
{
using (var aesAlg = Aes.Create())
{
aesAlg.Mode = CipherMode.CBC;
using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
{
using (var msEncrypt = new MemoryStream())
{
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
csEncrypt.Write(data, 0, data.Length);
return msEncrypt.ToArray();
}
}
}
}
public static byte[] DecryptData(byte[] encrypted, byte[] key)
{
var iv = new byte[16];
Buffer.BlockCopy(encrypted, 0, iv, 0, iv.Length);
using (var aesAlg = Aes.Create())
{
aesAlg.Mode = CipherMode.CBC;
using (var decryptor = aesAlg.CreateDecryptor(key, iv))
{
using (var msDecrypt = new MemoryStream(encrypted, iv.Length, encrypted.Length - iv.Length))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var resultStream = new MemoryStream())
{
csDecrypt.CopyTo(resultStream);
return resultStream.ToArray();
}
}
}
}
}
}
}
Starting from API 21, the GridLayout now supports the weight like LinearLayout. For details please see the link below:
Just don't anchor your pattern:
/Test/
The above regex will check for the literal string "Test" being found somewhere within it.
I think you cant remove column names, only reset them by range
with shape
:
print df.shape[1]
2
print range(df.shape[1])
[0, 1]
df.columns = range(df.shape[1])
print df
0 1
0 23 12
1 21 44
2 98 21
This is same as using to_csv
and read_csv
:
print df.to_csv(header=None,index=False)
23,12
21,44
98,21
print pd.read_csv(io.StringIO(u""+df.to_csv(header=None,index=False)), header=None)
0 1
0 23 12
1 21 44
2 98 21
Next solution with skiprows
:
print df.to_csv(index=False)
A,B
23,12
21,44
98,21
print pd.read_csv(io.StringIO(u""+df.to_csv(index=False)), header=None, skiprows=1)
0 1
0 23 12
1 21 44
2 98 21
You can use android:background="#DC143C"
, or any other RGB values for your color. I have no problem using it this way, as stated here
I was testing my application with the Android emulator and I solved this by turning off and turning on the Wi-Fi on the Android emulator device! It worked perfectly.
The following code creates a table with 2 column as a primary key in SQLite.
SOLUTION:
CREATE TABLE IF NOT EXISTS users (
id TEXT NOT NULL,
name TEXT NOT NULL,
pet_name TEXT,
PRIMARY KEY (id, name)
)
When I was doing the same query, I had hard time adjusting the solutions to my case, though all the previous answers have good insights.
Here is a solution when one has to acquire a list of unique objects, NOT strings.
Let's say, one has a list of Record object. Record
class has only properties of type String
, NO property of type int
.
Here implementing hashCode()
becomes difficult as hashCode()
needs to return an int
.
The following is a sample Record
Class.
public class Record{
String employeeName;
String employeeGroup;
Record(String name, String group){
employeeName= name;
employeeGroup = group;
}
public String getEmployeeName(){
return employeeName;
}
public String getEmployeeGroup(){
return employeeGroup;
}
@Override
public boolean equals(Object o){
if(o instanceof Record){
if (((Record) o).employeeGroup.equals(employeeGroup) &&
((Record) o).employeeName.equals(employeeName)){
return true;
}
}
return false;
}
@Override
public int hashCode() { //this should return a unique code
int hash = 3; //this could be anything, but I would chose a prime(e.g. 5, 7, 11 )
//again, the multiplier could be anything like 59,79,89, any prime
hash = 89 * hash + Objects.hashCode(this.employeeGroup);
return hash;
}
As suggested earlier by others, the class needs to override both the equals()
and the hashCode()
method to be able to use HashSet
.
Now, let's say, the list of Records is allRecord
(List<Record> allRecord
).
Set<Record> distinctRecords = new HashSet<>();
for(Record rc: allRecord){
distinctRecords.add(rc);
}
This will only add the distinct Records to the Hashset, distinctRecords.
Hope this helps.
Remove display: block;
in the div #tfl
style property
<div id="tfl" style="display: block; width: 187px; height: 260px;
Inline style take priority then css file
Sometimes, when you add a new library, in introduces a clashing version of System.Windows.Interactivity.dll
.
For example, the NuGet package MVVM light
might require v4.2 of System.Windows.Interactivity.dll
, but the NuGet package Rx-XAML
might require v4.5 of System.Windows.Interactivity.dll
. This will prevent the the project from working, because no matter which version of System.Windows.Interactivity.dll
you include, one of the libraries will refuse to compile.
To fix, add an Assembly Binding Redirect by editing your app.config
to look something like this:
<?xml version="1.0"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Windows.Interactivity"
publicKeyToken="31bf3856ad364e35"
culture="neutral"/>
<bindingRedirect oldVersion="4.0.0.0"
newVersion="4.5.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup>
<appSettings>
<add key="TestKey" value="true"/>
</appSettings>
Don't worry about changing the PublicKeyToken
, that's constant across all versions, as it depends on the name of the .dll, not the version.
Ensure that you match the newVersion
in your appConfig
to the actual version that you end up pointing at:
We use object-scan for a lot of data processing. It has some nice properties, especially traversing in delete safe order. Here is how one could implement find, delete and replace for your question.
// const objectScan = require('object-scan');
const tool = (() => {
const scanner = objectScan(['[*]'], {
abort: true,
rtn: 'bool',
filterFn: ({
value, parent, property, context
}) => {
if (value.id === context.id) {
context.fn({ value, parent, property });
return true;
}
return false;
}
});
return {
add: (data, id, obj) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property + 1, 0, obj) }),
del: (data, id) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property, 1) }),
mod: (data, id, prop, v = undefined) => scanner(data, {
id,
fn: ({ value }) => {
if (value !== undefined) {
value[prop] = v;
} else {
delete value[prop];
}
}
})
};
})();
// -------------------------------
const data = [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ];
const toAdd = { id: 'two', pId: 'foo2', cId: 'bar2' };
const exec = (fn) => {
console.log('---------------');
console.log(fn.toString());
console.log(fn());
console.log(data);
};
exec(() => tool.add(data, 'one', toAdd));
exec(() => tool.mod(data, 'one', 'pId', 'zzz'));
exec(() => tool.mod(data, 'one', 'other', 'test'));
exec(() => tool.mod(data, 'one', 'gone', 'delete me'));
exec(() => tool.mod(data, 'one', 'gone'));
exec(() => tool.del(data, 'three'));
// => ---------------
// => () => tool.add(data, 'one', toAdd)
// => true
// => [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'pId', 'zzz')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'other', 'test')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'gone', 'delete me')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: 'delete me' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'gone')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.del(data, 'three')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' } ]
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
It must be overridden. You could use:
<!-- Add a class name to override -->
<select name="funTimes" class="funTimes" size="5">
#elementId select.funTimes {
/* Override styles here */
}
Make sure you use !important
flag in css style e.g. margin-top: 0px !important
What does !important mean in CSS?
You could use an attribute selector, but since that isn't supported by legacy browsers (read IE6 etc), it's better to add a class name
For picking just one element of a generator use break
in a for
statement, or list(itertools.islice(gen, 1))
According to your example (literally) you can do something like:
while True:
...
if something:
for my_element in myfunct():
dostuff(my_element)
break
else:
do_generator_empty()
If you want "get just one element from the [once generated] generator whenever I like" (I suppose 50% thats the original intention, and the most common intention) then:
gen = myfunct()
while True:
...
if something:
for my_element in gen:
dostuff(my_element)
break
else:
do_generator_empty()
This way explicit use of generator.next()
can be avoided, and end-of-input handling doesn't require (cryptic) StopIteration
exception handling or extra default value comparisons.
The else:
of for
statement section is only needed if you want do something special in case of end-of-generator.
next()
/ .next()
:In Python3 the .next()
method was renamed to .__next__()
for good reason: its considered low-level (PEP 3114). Before Python 2.6 the builtin function next()
did not exist. And it was even discussed to move next()
to the operator
module (which would have been wise), because of its rare need and questionable inflation of builtin names.
Using next()
without default is still very low-level practice - throwing the cryptic StopIteration
like a bolt out of the blue in normal application code openly. And using next()
with default sentinel - which best should be the only option for a next()
directly in builtins
- is limited and often gives reason to odd non-pythonic logic/readablity.
Bottom line: Using next() should be very rare - like using functions of operator
module. Using for x in iterator
, islice
, list(iterator)
and other functions accepting an iterator seamlessly is the natural way of using iterators on application level - and quite always possible. next()
is low-level, an extra concept, unobvious - as the question of this thread shows. While e.g. using break
in for
is conventional.
I lost somehow my temporary notepad++ files, they weren't showing in tabs. So I did some search in appdata folder, and I found all my temporary files there. It seems that they are stored there for a long time.
C:\Users\USER\AppData\Roaming\Notepad++\backup
or
%AppData%\Notepad++\backup
You could spare yourself the transformations, you could use CSS3 Transitions to flip <div>
's and <ol>
's and any HTML tag you want. Here are some demos with source code explain to see and learn: http://www.webdesignerwall.com/trends/47-amazing-css3-animation-demos/
Let's use an analogy. For a given musical script every musician which plays it gives her own touch in the interpretation.
Musician can be abstracted with interfaces, genre to which musician belongs can be an abstrac class which defines some global rules of interpretation and every musician who plays can be modeled with a concrete class.
If you are a listener of the musical work, you have a reference to the script e.g. Bach's 'Fuga and Tocata' and every musician who performs it does it polymorphicaly in her own way.
This is just an example of a possible design (in Java):
public interface Musician {
public void play(Work work);
}
public interface Work {
public String getScript();
}
public class FugaAndToccata implements Work {
public String getScript() {
return Bach.getFugaAndToccataScript();
}
}
public class AnnHalloway implements Musician {
public void play(Work work) {
// plays in her own style, strict, disciplined
String script = work.getScript()
}
}
public class VictorBorga implements Musician {
public void play(Work work) {
// goofing while playing with superb style
String script = work.getScript()
}
}
public class Listener {
public void main(String[] args) {
Musician musician;
if (args!=null && args.length > 0 && args[0].equals("C")) {
musician = new AnnHalloway();
} else {
musician = new TerryGilliam();
}
musician.play(new FugaAndToccata());
}
If you have floats you can write a function and then use that e.g.
#!/bin/bash
function float_gt() {
perl -e "{if($1>$2){print 1} else {print 0}}"
}
x=3.14
y=5.20
if [ $(float_gt $x $y) == 1 ] ; then
echo "do stuff with x"
else
echo "do stuff with y"
fi
I dont know if the a best solution, but i describe it here:
First of all, you need certificate with you class Application of your app is in your manifest of this:
<application
android:name=".App"
...
Second, in my class App i did like this:
public class App extends Application {
public static boolean isOrientationChanged = false;
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onConfigurationChanged(@NotNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ||
newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
isOrientationChanged = true;
}
}
}
Third, you need to set a flag to Orientation Change, in my case, I always set it when the previous activity within the app navigation is called, so only calling once when the later activity is created.
isOrientationChanged = false;
So every time I change the orientation of my screen in that context, I set it every time it changes this setting, it checks if there is a change in orientation, if so, it validates it based on the value of that flag.
Basically, I had to use it whenever I made an asynchronous retrofit request, which he called every moment that changed orientation, constantly crashing the application:
if (!isOrientationChanged) {
presenter.retrieveAddress(this, idClient, TYPE_ADDRESS);
}
I don't know if it's the most elegant and beautiful solution, but at least here it's functional :)
Google changed the name to avoid confusion.
Problem with the old name fill parent
was that it implies its affecting the dimensions of the parent, while match parent
better describes the resulting behavior - match the dimension with the parent.
Both constants resolve to -1
in the end, and so result in the identical behavior in the app. Ironically enough, this name change made to clarify things seems to have added confusion rather than eliminating it.
Case sensitive Tables (table names created with double-quotes) can throw this same error as well. See this answer for more information.
Simply wrap the table in double quotes:
INSERT INTO "customer" (c_id,name,surname) VALUES ('1','Micheal','Jackson')
This issue could by happen while using unmanaged oracle reference if you have more than one oracle client , or sometimes if you reference different version
There is two way to solve it :
First and fast solution is to remove unmanaged reference and use the managed one from NuGet see this before to go with this option Differences between the ODP.NET Managed Driver and Unmanaged Driver
Second solution is to fix project unmanaged target version like the below :
Then check oracle GAC version
got to gac from run (Win+R) "%windir%\Microsoft.NET\assembly"
to check you target platform (right click on your project > properties)
Right Click on Oracle.DataAccess > properties > details and check version
if you notice the versions are different this is an the issue and to fix it we need to redirect assembly version (in startup project go to config file and add the below section )
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Oracle.DataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="4.121.2.0" />
</dependentAssembly>
</assemblyBinding>
oldVersion : should be cover your project version
newVersion : GAC version
publicKeyToken : From GAC
This is with reference to the original question
$('select').val(['a','c']);
$('select').trigger('change');
Try adding a button on mdi parent and add this code' to set your mdi child inside the mdi parent. change the yourchildformname to your MDI Child's form name and see if this works.
Dim NewMDIChild As New yourchildformname()
'Set the Parent Form of the Child window.
NewMDIChild.MdiParent = Me
'Display the new form.
NewMDIChild.Show()
@ is used as a prefix denoting stored procedure and function parameter names, and also variable names
If mongodb is installed via Homebrew the default location is:
/usr/local/var/mongodb
See the answer from @simonbogarde for the location of other interesting files that are different when using Homebrew.
Any of the following will work:
print 'Hello\nWorld'
print 'Hello'
print 'World'
Additionally, if you want to print a blank line (not make a new line), print
or print()
will work.
I had to do something like this but wanted to use a getter/setter for mine. In particular I wanted to return a long from a textfield. The other answers all worked well also, I just ended up adapting mine a little as my school project evolved.
long ms = [self.textfield.text longLongValue];
return ms;
Try this:
$keys = array_keys($array, "Completed");
/edit As mentioned by JohnP, this method only works for non-nested arrays.
Correct or Incorrect: Please execute test locally and decide for yourself!
Edit/Remove is faster in LinkedList
than ArrayList
.
ArrayList
, backed by Array
, which needs to be double the size, is worse in large volume application.
Below is the unit test result for each operation.Timing is given in Nanoseconds.
Operation ArrayList LinkedList
AddAll (Insert) 101,16719 2623,29291
Add (Insert-Sequentially) 152,46840 966,62216
Add (insert-randomly) 36527 29193
remove (Delete) 20,56,9095 20,45,4904
contains (Search) 186,15,704 189,64,981
Here's the code:
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
public class ArrayListVsLinkedList {
private static final int MAX = 500000;
String[] strings = maxArray();
////////////// ADD ALL ////////////////////////////////////////
@Test
public void arrayListAddAll() {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
List<String> arrayList = new ArrayList<String>(MAX);
watch.start();
arrayList.addAll(stringList);
watch.totalTime("Array List addAll() = ");//101,16719 Nanoseconds
}
@Test
public void linkedListAddAll() throws Exception {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
watch.start();
List<String> linkedList = new LinkedList<String>();
linkedList.addAll(stringList);
watch.totalTime("Linked List addAll() = "); //2623,29291 Nanoseconds
}
//Note: ArrayList is 26 time faster here than LinkedList for addAll()
///////////////// INSERT /////////////////////////////////////////////
@Test
public void arrayListAdd() {
Watch watch = new Watch();
List<String> arrayList = new ArrayList<String>(MAX);
watch.start();
for (String string : strings)
arrayList.add(string);
watch.totalTime("Array List add() = ");//152,46840 Nanoseconds
}
@Test
public void linkedListAdd() {
Watch watch = new Watch();
List<String> linkedList = new LinkedList<String>();
watch.start();
for (String string : strings)
linkedList.add(string);
watch.totalTime("Linked List add() = "); //966,62216 Nanoseconds
}
//Note: ArrayList is 9 times faster than LinkedList for add sequentially
/////////////////// INSERT IN BETWEEN ///////////////////////////////////////
@Test
public void arrayListInsertOne() {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
List<String> arrayList = new ArrayList<String>(MAX + MAX / 10);
arrayList.addAll(stringList);
String insertString0 = getString(true, MAX / 2 + 10);
String insertString1 = getString(true, MAX / 2 + 20);
String insertString2 = getString(true, MAX / 2 + 30);
String insertString3 = getString(true, MAX / 2 + 40);
watch.start();
arrayList.add(insertString0);
arrayList.add(insertString1);
arrayList.add(insertString2);
arrayList.add(insertString3);
watch.totalTime("Array List add() = ");//36527
}
@Test
public void linkedListInsertOne() {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
List<String> linkedList = new LinkedList<String>();
linkedList.addAll(stringList);
String insertString0 = getString(true, MAX / 2 + 10);
String insertString1 = getString(true, MAX / 2 + 20);
String insertString2 = getString(true, MAX / 2 + 30);
String insertString3 = getString(true, MAX / 2 + 40);
watch.start();
linkedList.add(insertString0);
linkedList.add(insertString1);
linkedList.add(insertString2);
linkedList.add(insertString3);
watch.totalTime("Linked List add = ");//29193
}
//Note: LinkedList is 3000 nanosecond faster than ArrayList for insert randomly.
////////////////// DELETE //////////////////////////////////////////////////////
@Test
public void arrayListRemove() throws Exception {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
List<String> arrayList = new ArrayList<String>(MAX);
arrayList.addAll(stringList);
String searchString0 = getString(true, MAX / 2 + 10);
String searchString1 = getString(true, MAX / 2 + 20);
watch.start();
arrayList.remove(searchString0);
arrayList.remove(searchString1);
watch.totalTime("Array List remove() = ");//20,56,9095 Nanoseconds
}
@Test
public void linkedListRemove() throws Exception {
Watch watch = new Watch();
List<String> linkedList = new LinkedList<String>();
linkedList.addAll(Arrays.asList(strings));
String searchString0 = getString(true, MAX / 2 + 10);
String searchString1 = getString(true, MAX / 2 + 20);
watch.start();
linkedList.remove(searchString0);
linkedList.remove(searchString1);
watch.totalTime("Linked List remove = ");//20,45,4904 Nanoseconds
}
//Note: LinkedList is 10 millisecond faster than ArrayList while removing item.
///////////////////// SEARCH ///////////////////////////////////////////
@Test
public void arrayListSearch() throws Exception {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
List<String> arrayList = new ArrayList<String>(MAX);
arrayList.addAll(stringList);
String searchString0 = getString(true, MAX / 2 + 10);
String searchString1 = getString(true, MAX / 2 + 20);
watch.start();
arrayList.contains(searchString0);
arrayList.contains(searchString1);
watch.totalTime("Array List addAll() time = ");//186,15,704
}
@Test
public void linkedListSearch() throws Exception {
Watch watch = new Watch();
List<String> linkedList = new LinkedList<String>();
linkedList.addAll(Arrays.asList(strings));
String searchString0 = getString(true, MAX / 2 + 10);
String searchString1 = getString(true, MAX / 2 + 20);
watch.start();
linkedList.contains(searchString0);
linkedList.contains(searchString1);
watch.totalTime("Linked List addAll() time = ");//189,64,981
}
//Note: Linked List is 500 Milliseconds faster than ArrayList
class Watch {
private long startTime;
private long endTime;
public void start() {
startTime = System.nanoTime();
}
private void stop() {
endTime = System.nanoTime();
}
public void totalTime(String s) {
stop();
System.out.println(s + (endTime - startTime));
}
}
private String[] maxArray() {
String[] strings = new String[MAX];
Boolean result = Boolean.TRUE;
for (int i = 0; i < MAX; i++) {
strings[i] = getString(result, i);
result = !result;
}
return strings;
}
private String getString(Boolean result, int i) {
return String.valueOf(result) + i + String.valueOf(!result);
}
}
import moment from 'moment';
.....
render() {
return (
<div>
{
this.props.data.map((post,key) =>
<div key={key} className="post-detail">
<h1>{post.title}</h1>
<p>{moment(post.date).calendar()}</p>
<p dangerouslySetInnerHTML={{__html: post.content}}></p>
<hr />
</div>
)}
</div>
);
}
To compile source.cpp
, run
g++ source.cpp
This command will compile source.cpp
to file a.out
in the same directory.
To run the compiled file, run
./a.out
If you compile another source file, with g++ source2.cpp
, the new compiled file a.out
will overwrite the a.out
generated with source.cpp
If you want to compile source.cpp
to a specific file, say compiledfile
,
run
g++ source.cpp -o compiledfile
or
g++ -o compiledfile source.cpp
This will create the compiledfile
which is the compiled binary file. to run the compiledfile
, run
./compiledfile
If g++
is not in your $PATH
, replace g++ with /usr/bin/g++
.
The only time I factor in extra time for testing is if I'm unfamiliar with the testing technology I'll be using (e.g. using Selenium tests for the first time). Then I factor in maybe 10-20% for getting up to speed on the tools and getting the test infrastructure in place.
Otherwise testing is just an innate part of development and doesn't warrant an extra estimate. In fact, I'd probably increase the estimate for code done without tests.
EDIT: Note that I'm usually writing code test-first. If I have to come in after the fact and write tests for existing code that's going to slow things down. I don't find that test-first development slows me down at all except for very exploratory (read: throw-away) coding.
Another option, especially if you're already using UnderscoreJS, would be:
_.last([1, 2, 3, 4]); // Will return 4
You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)
$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property
Or just this, xpath is case sensitive. Both have the same output:
$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml
Name Type #text
---- ---- -----
DisplayName System.String SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName System.String SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped
A few more things in addition to the existing answers. Have a look at this:
var seatsValid = true;
// cache the selector
var seatsVal = $("#seats").val();
if(seatsVal!=''){
seatsValid = false;
alert("Not a valid character")
// convert seatsVal to an integer for comparison
}else if(parseInt(seatsVal) < 99999){
seatsValid = false;
alert("Not a valid Number");
}
The variable name setFlag is very generic, if your only using it in conjunction with the number of seats you should rename it (I called it seatsValid). I also initialized it to true which gets rid of the need for the final else in your original code. Next, I put the selector and call to .val() in a variable. It's good practice to cache your selectors so jquery doesn't need to traverse the DOM more than it needs to. Lastly when comparing two values you should try to make sure they are the same type, in this case seatsVal is a string so in order to properly compare it to 99999 you should use parseInt() on it.
More generally, to exclude files that don't comply with some shell regexp, you could use module fnmatch
:
import fnmatch
file_list = glob('somepath')
for ind, ii in enumerate(file_list):
if not fnmatch.fnmatch(ii, 'bash_regexp_with_exclude'):
file_list.pop(ind)
The above will first generate a list from a given path and next pop out the files that won't satisfy the regular expression with the desired constraint.
con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Yna Maningding-Dula\Documents\Visual Studio 2010\Projects\LuxuryHotel\LuxuryHotel\ClientsRecords.mdf;Integrated Security=True;User Instance=True");
con.Open();
cmd = new SqlCommand("INSERT INTO ClientData ([Last Name], [First Name], [Middle Name], Address, [Email Address], [Contact Number], Nationality, [Arrival Date], [Check-out Date], [Room Type], [Daily Rate], [No of Guests], [No of Rooms]) VALUES (@[Last Name], @[First Name], @[Middle Name], @Address, @[Email Address], @[Contact Number], @Nationality, @[Arrival Date], @[Check-out Date], @[Room Type], @[Daily Rate], @[No of Guests], @[No of Rooms]", con);
cmd.Parameters.Add("@[Last Name]", txtLName.Text);
cmd.Parameters.Add("@[First Name]", txtFName.Text);
cmd.Parameters.Add("@[Middle Name]", txtMName.Text);
cmd.Parameters.Add("@Address", txtAdd.Text);
cmd.Parameters.Add("@[Email Address]", txtEmail.Text);
cmd.Parameters.Add("@[Contact Number]", txtNumber.Text);
cmd.Parameters.Add("@Nationality", txtNational.Text);
cmd.Parameters.Add("@[Arrival Date]", txtArrive.Text);
cmd.Parameters.Add("@[Check-out Date]", txtOut.Text);
cmd.Parameters.Add("@[Room Type]", txtType.Text);
cmd.Parameters.Add("@[Daily Rate]", txtRate.Text);
cmd.Parameters.Add("@[No of Guests]", txtGuest.Text);
cmd.Parameters.Add("@[No of Rooms]", txtRoom.Text);
cmd.ExecuteNonQuery();
I don't see any margin
or margin-left
declarations for #footer-wrap li
.
This ought to do the trick:
#footer-wrap ul,
#footer-wrap li {
margin-left: 0;
list-style-type: none;
}
This error happened to me because I had @@model instead of @model... copy & paste error in my case. Changing to @model fixed it for me.
i did find something like this, helps get rid of hardcoded tempdata tags
public class AccountController : Controller
{
[HttpGet]
public ActionResult Index(IndexPresentationModel model)
{
return View(model);
}
[HttpPost]
public ActionResult Save(SaveUpdateModel model)
{
// save the information
var presentationModel = new IndexPresentationModel();
presentationModel.Message = model.Message;
return this.RedirectToAction(c => c.Index(presentationModel));
}
}
If you always want the loop to execute at least once. It's not common, but I do use it from time to time. One case where you might want to use it is trying to access a resource that could require a retry, e.g.
do
{
try to access resource...
put up message box with retry option
} while (user says retry);
A very simple and elegant solution to this is provided by W3C. Simply use the margin:0 auto declaration as follows:
.top_image img { margin:0 auto; }
More information and examples from W3C.
You can use mplayer.
mencoder -nocache -rtsp-stream-over-tcp rtsp://192.168.XXX.XXX/test.sdp -oac copy -ovc copy -o test.avi
The "copy" codec is just a dumb copy of the stream. Mencoder adds a header and stuff you probably want.
In the mplayer source file "stream/stream_rtsp.c" is a prebuffer_size setting of 640k and no option to change the size other then recompile. The result is that writing the stream is always delayed, which can be annoying for things like cameras, but besides this, you get an output file, and can play it back most places without a problem.
After spending many hours, I forged out following solution.
Follow these steps to create custom UIView
.
1) Create class myCustomView inherited from UIView.
2) Create .xib with name myCustomView.
3) Change Class of UIView inside your .xib file, assign myCustomView Class there.
5) Load .xib in myCustomView * customView. Use following sample code.
myCustomView * myView = [[[NSBundle mainBundle] loadNibNamed:@"myCustomView" owner:self options:nil] objectAtIndex:0];
[myView.description setText:@"description"];
Note: For those who still face issue can comment, I will provide them link of sample project with myCustomView
You could put all of your code under one namespace like this:
var namespace = {};
namespace.someClassObj = {};
delete namespace.someClassObj;
Using the delete
keyword will delete the reference to the property, but on the low level the JavaScript garbage collector (GC) will get more information about which objects to be reclaimed.
You could also use Chrome Developer Tools to get a memory profile of your app, and which objects in your app are needing to be scaled down.
I can only assume that your ${project.server.config} property is something custom defined and is outside of the standard directory layout.
If so, then I'd use the copy task.
Strings are immutable, meaning their contents cannot change. When you call replace(this,that)
you end up with a totally new String. If you want to keep this new copy, you need to assign it to a variable. You can overwrite the old reference (a la sentence = sentence.replace(this,that)
or a new reference as seen below:
public class Test{
public static void main(String[] args) {
String sentence = "Define, Measure, Analyze, Design and Verify";
String replaced = sentence.replace("and", "");
System.out.println(replaced);
}
}
As an aside, note that I've removed the contains()
check, as it is an unnecessary call here. If it didn't contain it, the replace will just fail to make any replacements. You'd only want that contains method if what you're replacing was different than the actual condition you're checking.
You can do:
foo.instance_of?(String)
And the more general:
foo.kind_of?(String)
Two years late, but I have the solution you're looking for. Not intending to take credit form the original author, here's a plugin which I found works exceptionally well for what you need, but gets all possible styles in all browsers, even IE.
Warning: This code generates a lot of output, and should be used sparingly. It not only copies all standard CSS properties, but also all vendor CSS properties for that browser.
jquery.getStyleObject.js:
/*
* getStyleObject Plugin for jQuery JavaScript Library
* From: http://upshots.org/?p=112
*/
(function($){
$.fn.getStyleObject = function(){
var dom = this.get(0);
var style;
var returns = {};
if(window.getComputedStyle){
var camelize = function(a,b){
return b.toUpperCase();
};
style = window.getComputedStyle(dom, null);
for(var i = 0, l = style.length; i < l; i++){
var prop = style[i];
var camel = prop.replace(/\-([a-z])/g, camelize);
var val = style.getPropertyValue(prop);
returns[camel] = val;
};
return returns;
};
if(style = dom.currentStyle){
for(var prop in style){
returns[prop] = style[prop];
};
return returns;
};
return this.css();
}
})(jQuery);
Basic usage is pretty simple, but he's written a function for that as well:
$.fn.copyCSS = function(source){
var styles = $(source).getStyleObject();
this.css(styles);
}
Hope that helps.
How about this:
$ grep -rl "needle text" my_folder | tr '\n' '\0' | xargs -r -0 file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable'
If you want the filenames without the file types, just add a final sed
filter.
$ grep -rl "needle text" my_folder | tr '\n' '\0' | xargs -r -0 file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable' | sed 's|:[^:]*$||'
You can filter-out unneeded file types by adding more -e 'type'
options to the last grep
command.
EDIT:
If your xargs
version supports the -d
option, the commands above become simpler:
$ grep -rl "needle text" my_folder | xargs -d '\n' -r file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable' | sed 's|:[^:]*$||'
Thanks to Chris for the starting point here is a improvement which addresses the resizing of the images used, the use of first-child is just to indicate you could use a variety of icons within the list to give you full control.
ul li:first-child:before {
content: '';
display: inline-block;
height: 25px;
width: 35px;
background-image: url('../images/Money.png');
background-size: contain;
background-repeat: no-repeat;
margin-left: -35px;
}
This seems to work well in all modern browsers, you will need to ensure that the width and the negative margin left have the same value, hope it helps
Deep Copy
A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.
Shallow Copy
Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.
$(document).ready(function() {
var $startAt = null;
$(document.body).live("mousemove", function(e) {
if ($startAt) {
$("#someDiv").offset({
top: e.pageY,
left: $("#someDiv").position().left-$startAt+e.pageX
});
$startAt = e.pageX;
}
});
$("#someDiv").live("mousedown", function (e) {$startAt = e.pageX;});
$(document.body).live("mouseup", function (e) {$startAt = null;});
});
We were able to solve a similar issue here using Oracle LISTAGG. There was a point where what we were grouping on exceeded the 4K limit but this was easily solved by having the first dataset take the first 15 items to aggregate, each of which have a 256K limit.
More info: We have projects, which have change orders, which in turn have explanations. Why the database is set up to take change text in chunks of 256K limits is not known but its one of the design constraints. So the application that feeds change explanations into the table stops at 254K and inserts, then gets the next set of text and if > 254K generates another row, etc. So we have a project to a change order, a 1:1. Then we have these as 1:n for explanations. LISTAGG concatenates all these. We have RMRKS_SN values, 1 for each remark and/or for each 254K of characters.
The largest RMRKS_SN was found to be 31, so I did the first dataset pulling SN 0 to 15, the 2nd dataset 16 to 30 and the last dataset 31 to 45 -- hey, let's plan on someone adding a LOT of explanation to some change orders!
In the SQL report, the Tablix ties to the first dataset. To get the other data, here's the expression:
=First(Fields!NON_STD_TXT.Value, "DataSet_EXPLAN") & First(Fields!NON_STD_TXT.Value, "ds_EXPLAN_SN_16_TO_30") & First(Fields!NON_STD_TXT.Value, "ds_EXPLAN_SN_31_TO_45")
For us, we have to have DB Group create functions, etc. because of security constraints. So with a bit of creativity, we didn't have to do a User Aggregate or a UDF.
If your application has some sort of SN to aggregate by, this method should work. I don't know what the equivalent TSQL is -- we're fortunate to be dealing with Oracle for this report, for which LISTAGG is a Godsend.
The code is:
SELECT
LT.C_O_NBR AS LT_CO_NUM,
RT.C_O_NBR AS RT_CO_NUM,
LT.STD_LN_ITM_NBR,
RT.NON_STD_LN_ITM_NBR,
RT.NON_STD_PRJ_NBR,
LT.STD_PRJ_NBR,
NVL(LT.PRPSL_LN_NBR, RT.PRPSL_LN_NBR) AS PRPSL_LN_NBR,
LT.STD_CO_EXPL_TXT AS STD_TXT,
LT.STD_CO_EXPLN_T,
LT.STD_CO_EXPL_SN,
RT.NON_STD_CO_EXPLN_T,
LISTAGG(RT.RMRKS_TXT_FLD, '')
WITHIN GROUP(ORDER BY RT.RMRKS_SN) AS NON_STD_TXT
FROM ...
WHERE RT.RMRKS_SN BETWEEN 0 AND 15
GROUP BY
LT.C_O_NBR,
RT.C_O_NBR,
...
And in the other 2 datasets just select the LISTAGG only for the subqueries in the FROM:
SELECT
LISTAGG(RT.RMRKS_TXT_FLD, '')
WITHIN GROUP(ORDER BY RT.RMRKS_SN) AS NON_STD_TXT
FROM ...
WHERE RT.RMRKS_SN BETWEEN 31 AND 45
...
... and so on.
I know this is old but the solution does not work for negative index so I add a patch to it. hope it helps someone
String.prototype.replaceAt=function(index, character) {
if(index>-1) return this.substr(0, index) + character + this.substr(index+character.length);
else return this.substr(0, this.length+index) + character + this.substr(index+character.length);
}
SELECT ID , Date , Name into #temp from [TableName]
Order of magnitude: zero.
In other words, you won't see your throughput cut in half, or anything like it, when you add TLS. Answers to the "duplicate" question focus heavily on application performance, and how that compares to SSL overhead. This question specifically excludes application processing, and seeks to compare non-SSL to SSL only. While it makes sense to take a global view of performance when optimizing, that is not what this question is asking.
The main overhead of SSL is the handshake. That's where the expensive asymmetric cryptography happens. After negotiation, relatively efficient symmetric ciphers are used. That's why it can be very helpful to enable SSL sessions for your HTTPS service, where many connections are made. For a long-lived connection, this "end-effect" isn't as significant, and sessions aren't as useful.
Here's an interesting anecdote. When Google switched Gmail to use HTTPS, no additional resources were required; no network hardware, no new hosts. It only increased CPU load by about 1%.
Sounds like an error you would get when your forms authentication ticket has expired. What is the timeout period for your ticket? Is it set to sliding or absolute expiration?
I believe the default for the timeout is 20 minutes with sliding expiration so if a user gets authenticated and at some point doesn't hit your site for 20 minutes their ticket would be expired. If it is set to absolute expiration it will expire X number of minutes after it was issued where X is your timeout setting.
You can set the timeout and expiration policy (e.g. sliding, absolute) in your web/machine.config
under /configuration/system.web/authentication/forms
http://www.internetdoc.info/javascript-function/remove-key-from-array.htm
removeKey(arrayName,key);
function removeKey(arrayName,key)
{
var x;
var tmpArray = new Array();
for(x in arrayName)
{
if(x!=key) { tmpArray[x] = arrayName[x]; }
}
return tmpArray;
}
The following code were written in ES6 and it will work in most of the browsers without an issue.
var test_array = [["name1", 2, 3], ["name2", 4, 5], ["name3", 6, 7], ["name4", 8, 9], ["name5", 10, 11]];_x000D_
_x000D_
// Construct the comma seperated string_x000D_
// If a column values contains a comma then surround the column value by double quotes_x000D_
const csv = test_array.map(row => row.map(item => (typeof item === 'string' && item.indexOf(',') >= 0) ? `"${item}"`: String(item)).join(',')).join('\n');_x000D_
_x000D_
// Format the CSV string_x000D_
const data = encodeURI('data:text/csv;charset=utf-8,' + csv);_x000D_
_x000D_
// Create a virtual Anchor tag_x000D_
const link = document.createElement('a');_x000D_
link.setAttribute('href', data);_x000D_
link.setAttribute('download', 'export.csv');_x000D_
_x000D_
// Append the Anchor tag in the actual web page or application_x000D_
document.body.appendChild(link);_x000D_
_x000D_
// Trigger the click event of the Anchor link_x000D_
link.click();_x000D_
_x000D_
// Remove the Anchor link form the web page or application_x000D_
document.body.removeChild(link);
_x000D_
The pack syntax you are using here is for an image that is contained as a Resource within your application, not for a loose file in the file system.
You simply want to pass the actual path to the UriSource:
logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png");
<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>
I use these:
.right {display:table; margin:-18px 0 0 auto;}
.center {display:table; margin:-18px auto 0 auto;}
You are experiencing this issue for two reasons.
When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)
User.java
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="iduser")
private Long idUser;
@Column(name="user_name")
private String userName;
@OneToOne()
@JoinColumn(name="idarea")
private Area area;
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
}
Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:
@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")
While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.
Area.java
@Entity
@Table(name = "area")
public class Area {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="idarea")
private Long idArea;
@Column(name="area_name")
private String areaName;
@OneToOne(fetch=FetchType.LAZY, mappedBy="area")
private User user;
public Long getIdArea() {
return idArea;
}
public void setIdArea(Long idArea) {
this.idArea = idArea;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Make sure you are loading those modules (myApp.services and myApp.directives) as dependencies of your main app module, like this:
angular.module('myApp', ['myApp.directives', 'myApp.services']);
plunker: http://plnkr.co/edit/wxuFx6qOMfbuwPq1HqeM?p=preview
If you want everyone to be able to access the Node app, then try using
res.header('Access-Control-Allow-Origin', "*")
That will allow requests from any origin. The CORS enable site has a lot of information on the different Access-Control-Allow headers and how to use them.
I you are using Chrome, please look at this bug bug regarding localhost and Access-Control-Allow-Origin. There is another StackOverflow question here that details the issue.
Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.
As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:
var clone = _.clone(data, true);
data[1].values.d = 'x';
_.isEqual(data, clone) === false
_.isEqual(data, clone) === true
I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.
Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).
Inside your current folder, simply press Shift+Alt+F --then--> Enter.
The prompt will appear with your current folder's path set.
Note: That works only in Windows 7 / Vista. What it does is that drops the "File" menu down for you, because the "Shift" key is pressed the option "Open command window here" is enabled and focused as the first available option of "File" menu. Pressing enter starts the focused option therefor the command window.
Edit:
In case you are in a folder and you already selected some of its contents (file/folder) this wont work. In that case Click on the empty area inside the folder to deselect any previously selected files and repeat.
Edit2:
Another way you can open terminal in current directory is to type cmd
on file browser navigation bar where the path of current folder is written.
In order to focus with your keyboard on the navigation bar Ctrl+L. Then you can type cmd
and hit Enter
Am i understanding your question only? You need .bat file to compile and execute java class files?
if its a .bat file. you can just double click.
and in your .bat file, you just need to javac Main.java ((make sure your bat has the path to ur Main.java) java Main
If you want to echo compilation warnings/statements, that would need something else. But since, you want that to be automated, maybe you eventually don't need that.
The BlackBerry browser and Safari for iOS (iPhone/iPod/iPad) automatically detect phone numbers and email addresses and convert them to links. If you don’t want this feature, you should use the following meta tags.
For Safari:
<meta name="format-detection" content="telephone=no">
For BlackBerry:
<meta http-equiv="x-rim-auto-match" content="none">
Source: mobilexweb.com
Update your SP and handle exception in it using declare handler with get diagnostics so that you will know if there is an exception. e.g.
CREATE DEFINER=`root`@`localhost` PROCEDURE `validar_egreso`(
IN codigo_producto VARCHAR(100),
IN cantidad INT,
OUT valido INT(11)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1
@p1 = RETURNED_SQLSTATE, @p2 = MESSAGE_TEXT;
SELECT @p1, @p2;
END
DECLARE resta INT(11);
SET resta = 0;
SELECT (s.stock - cantidad) INTO resta
FROM stock AS s
WHERE codigo_producto = s.codigo;
IF (resta > s.stock_minimo) THEN
SET valido = 1;
ELSE
SET valido = -1;
END IF;
SELECT valido;
END
tl;dr takeaway:
If you're looking for a very high standard for yourself or team, JSLint. But its not necessarily THE standard, just A standard, some of which comes to us dogmatically from a javascript god named Doug Crockford. If you want to be a bit more flexible, or have some old pros on your team that don't buy into JSLint's opinions, or are going back and forth between JS and other C-family languages on a regular basis, try JSHint.
long version:
The reasoning behind the fork explains pretty well why JSHint exists:
http://badassjs.com/post/3364925033/jshint-an-community-driven-fork-of-jslint http://anton.kovalyov.net/2011/02/20/why-i-forked-jslint-to-jshint/
So I guess the idea is that it's "community-driven" rather than Crockford-driven. In practicality, JSHint is generally a bit more lenient (or at least configurable or agnostic) on a few stylistic and minor syntactical "opinions" that JSLint is a stickler on.
As an example, if you think both the A and B below are fine, or if you want to write code with one or more of the aspects of A that aren't available in B, JSHint is for you. If you think B is the only correct option... JSLint. I'm sure there are other differences, but this highlights a few.
A) Passes JSHint out of the box - fails JSLint
(function() {
"use strict";
var x=0, y=2;
function add(val1, val2){
return val1 + val2;
}
var z;
for (var i=0; i<2; i++){
z = add(y, x+i);
}
})();
B) Passes Both JSHint and JSLint
(function () {
"use strict";
var x = 0, y = 2, i, z;
function add(val1, val2) {
return val1 + val2;
}
for (i = 0; i < 2; i += 1) {
z = add(y, x + i);
}
}());
Personally I find JSLint code very nice to look at, and the only hard features of it that I disagree with are its hatred of more than one var declaration in a function and of for-loop var i = 0
declarations, and some of the whitespace enforcements for function declarations.
A few of the whitespace things that JSLint enforces, I find to be not necessarily bad, but out of sync with some pretty standard whitespace conventions for other languages in the family (C, Java, Python, etc...), which are often followed as conventions in Javascript as well. Since I'm writing in various of these languages throughout the day, and working with team members who don't like Lint-style whitespace in our code, I find JSHint to be a good balance. It catches stuff that's a legitimate bug or really bad form, but doesn't bark at me like JSLint does (sometimes, in ways I can't disable) for the stylistic opinions or syntactic nitpicks that I don't care for.
A lot of good libraries aren't Lint'able, which to me demonstrates that there's some truth to the idea that some of JSLint is simply just about pushing 1 version of "good code" (which is, indeed, good code). But then again, the same libraries (or other good ones) probably aren't Hint'able either, so, touché.
Explicitly declaring the inputs for that mapping function should do the trick:
let imageToDeleteParameters = imagesToDelete.map {
(whatever : WhateverClass) -> Dictionary<String, Any> in
["id": whatever.id, "url": whatever.url.absoluteString, "_destroy": true]
}
Substitute the real class of "$0" for "WhateverClass" in that code snippet, and it should work.
Simplest & most correct way is:
from distutils.util import strtobool
parser.add_argument('--feature', dest='feature',
type=lambda x: bool(strtobool(x)))
Do note that True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.
I adjusted the code of @madprops for Python 3
# getem.py
# python2 script to download all images in a given url
# use: python getem.py http://url.where.images.are
from bs4 import BeautifulSoup
import urllib.request
import shutil
import requests
from urllib.parse import urljoin
import sys
import time
def make_soup(url):
req = urllib.request.Request(url, headers={'User-Agent' : "Magic Browser"})
html = urllib.request.urlopen(req)
return BeautifulSoup(html, 'html.parser')
def get_images(url):
soup = make_soup(url)
images = [img for img in soup.findAll('img')]
print (str(len(images)) + " images found.")
print('Downloading images to current working directory.')
image_links = [each.get('src') for each in images]
for each in image_links:
try:
filename = each.strip().split('/')[-1].strip()
src = urljoin(url, each)
print('Getting: ' + filename)
response = requests.get(src, stream=True)
# delay to avoid corrupted previews
time.sleep(1)
with open(filename, 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
except:
print(' An error occured. Continuing.')
print('Done.')
if __name__ == '__main__':
get_images('http://www.wookmark.com')
An alternative would be instead of passing the parameters to the constructor you might have them as getter and setters and then in a @PostConstruct initialize the values as you want. In this case Spring will create the bean using the default constructor. An example is below
@Component
public class MyConstructorClass{
String var;
public void setVar(String var){
this.var = var;
}
public void getVar(){
return var;
}
@PostConstruct
public void init(){
setVar("var");
}
...
}
@Service
public class MyBeanService{
//field autowiring
@Autowired
MyConstructorClass myConstructorClass;
....
}
I'm not sure what you're trying to do, but here's something to consider: c();
won't do anything. c
is an instance of the class checkbox
and not a method to be called. So consider this:
public class FirstWindow extends JFrame { public FirstWindow() { checkbox c = new checkbox(); c.yourMethod(yourParameters); // call the method you made in checkbox } } public class checkbox extends JFrame { public checkbox(yourParameters) { // this is the constructor method used to initialize instance variables } public void yourMethod() // doesn't have to be void { // put your code here } }
To expand on @cybersnoopy 's suggestion here
if you had a .proto file with a message like so:
message Request {
oneof option {
int64 option_value = 1;
}
}
You can make use of the case options provided (java generated code):
So we can now write some code as follows:
Request.OptionCase optionCase = request.getOptionCase();
OptionCase optionNotSet = OPTION_NOT_SET;
if (optionNotSet.equals(optionCase)){
// value not set
} else {
// value set
}
DROP
The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.
TRUNCATE
TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUNCATE is faster and doesn't use as much undo space as a DELETE. Table level lock will be added when Truncating.
DELETE
The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire. Row level lock will be added when deleting.
From: http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands
This has been an old question but solution is very simple to that. If you are ever unsure about how to write criterias, joins etc in hibernate then best way is using native queries. This doesn't slow the performance and very useful. Eq. below
@Query(nativeQuery = true, value = "your sql query")
returnTypeOfMethod methodName(arg1, arg2);
If you can re-create or parse your input data, you can specify an escape character for the CREATE TABLE:
ROW FORMAT DELIMITED FIELDS TERMINATED BY "," ESCAPED BY '\\';
Will accept this line as 4 fields
1,some text\, with comma in it,123,more text
You can also try:
{
"dateProp": { $gt: new Date('06/15/2016').getTime() }
}
A StringBuffer is used to create a single string from many strings, e.g. when you want to append parts of a String in a loop.
You should use a StringBuilder instead of a StringBuffer when you have only a single Thread accessing the StringBuffer, since the StringBuilder is not synchronized and thus faster.
AFAIK there is no upper limit for String size in Java as a language, but the JVMs probably have an upper limit.
use FileInputStream's readLine() method to read and parse the returned String to int using Integer.parseInt() method.
Using try/except is the best way to test for a variable's existence. But there's almost certainly a better way of doing whatever it is you're doing than setting/testing global variables.
For example, if you want to initialize a module-level variable the first time you call some function, you're better off with code something like this:
my_variable = None
def InitMyVariable():
global my_variable
if my_variable is None:
my_variable = ...
I suggest a mix of using X-macros are the best solution and the following template functions:
To borrow off marcinkoziukmyopenidcom and extended
enum Colours {
# define X(a) a,
# include "colours.def"
# undef X
ColoursCount
};
char const* const colours_str[] = {
# define X(a) #a,
# include "colours.def"
# undef X
0
};
template <class T> T str2enum( const char* );
template <class T> const char* enum2str( T );
#define STR2ENUM(TYPE,ARRAY) \
template <> \
TYPE str2enum<TYPE>( const char* str ) \
{ \
for( int i = 0; i < (sizeof(ARRAY)/sizeof(ARRAY[0])); i++ ) \
if( !strcmp( ARRAY[i], str ) ) \
return TYPE(i); \
return TYPE(0); \
}
#define ENUM2STR(TYPE,ARRAY) \
template <> \
const char* enum2str<TYPE>( TYPE v ) \
{ \
return ARRAY[v]; \
}
#define ENUMANDSTR(TYPE,ARRAY)\
STR2ENUM(TYPE,ARRAY) \
ENUM2STR(TYPE,ARRAY)
ENUMANDSTR(Colours,colours_str)
colour.def
X(Red)
X(Green)
X(Blue)
X(Cyan)
X(Yellow)
X(Magenta)
None of these answer were working for me on my macbook pro. So what i had to do was go to:
Preferences -> Source Code -> Code Formatting -> C# source code.
From here I could change my style and spacing tabs etc. This is the only project i have where the lead developer has different formatting than i do. It was a pain in the butt that my IDE would format my code different than theirs.
You need to create a thread to handle the update loop and use it to update the textarea. The tricky part though is that only the main thread can actually modify the ui so the update loop thread needs to signal the main thread to do the update. This is done using a Handler.
Check out this link: http://developer.android.com/guide/topics/ui/dialogs.html# Click on the section titled "Example ProgressDialog with a second thread". It's an example of exactly what you need to do, except with a progress dialog instead of a textfield.
Implement the return statement like the example below! You should be good. I hope it helps someone..
class Example(object):
def the_example(self):
itsProblem = "problem"
return itsProblem
theExample = Example()
print theExample.the_example()
I'm using babel
and the following syntax is working for me:
class MyClass {
static constant1 = 33;
static constant2 = {
case1: 1,
case2: 2,
};
// ...
}
MyClass.constant1 === 33
MyClass.constant2.case1 === 1
Please consider that you need the preset "stage-0"
.
To install it:
npm install --save-dev babel-preset-stage-0
// in .babelrc
{
"presets": ["stage-0"]
}
Update:
currently use stage-3
Short and universal approach
If you want to check any array if it has falsy values (like false, undefined, null or empty strings) you can just use every() method like this:
array.every(function(element) {return !!element;}); // returns true or false
For example:
['23', null, 2, {key: 'value'}].every(function(element) {return !!element;}); // returns false
['23', '', 2, {key: 'value'}].every(function(element) {return !!element;}); // returns false
['23', true, 2, {key: 'value'}].every(function(element) {return !!element;}); // returns true
If you need to get a first index of falsy value, you can do it like this:
let falsyIndex;
if(!['23', true, 2, null, {key: 'value'}].every(function(element, index) {falsyIndex = index; return !!element;})) {
console.log(falsyIndex);
} // logs 3
If you just need to check a falsy value of an array for a given index you can just do it like this:
if (!!array[index]) {
// array[index] is a correct value
}
else {
// array[index] is a falsy value
}
Roughly speaking:
getClass().getResource("/")
~= Thread.currentThread().getContextClassLoader().getResource(".")
Suppose your project structure is like the following:
+-- src
¦ +-- main
¦ +-- test
¦ +-- test
¦ +-- java
¦ ¦ +-- com
¦ ¦ +-- github
¦ ¦ +-- xyz
¦ ¦ +-- proj
¦ ¦ +-- MainTest.java
¦ ¦ +-- TestBase.java
¦ +-- resources
¦ +-- abcd.txt
+-- target
+-- test-classes
+-- com
+-- abcd.txt
// in MainClass.java
this.getClass.getResource("/") -> "~/proj_dir/target/test-classes/"
this.getClass.getResource(".") -> "~/proj_dir/target/test-classes/com/github/xyz/proj/"
Thread.currentThread().getContextClassLoader().getResources(".") -> "~/proj_dir/target/test-classes/"
Thread.currentThread().getContextClassLoader().getResources("/") -> null
Github said on April 3rd 2012 :
Today we're removing two features. They've been gathering dust for a while and it's time to throw them out : Fork Queue & Private Messaging
In my case the solution was:
Permissions on the config file should be 600.
chmod 600 config
As mentioned in the comments above by generalopinion
No need to touch the config file contents.
It looks like you are not providing a value for the primary key field DB_ID. If that is a primary key, you must provide a unique value for that column. The only way not to provide it would be to create a database trigger that, on insert, would provide a value, most likely derived from a sequence.
If this is a restoration from another database and there is a sequence on this new instance, it might be trying to reuse a value. If the old data had unique keys from 1 - 1000 and your current sequence is at 500, it would be generating values that already exist. If a sequence does exist for this table and it is trying to use it, you would need to reconcile the values in your table with the current value of the sequence.
You can use SEQUENCE_NAME.CURRVAL to see the current value of the sequence (if it exists of course)
I guess you will get ORA-01741: illegal zero-length identifier if you use the following
SELECT "" AS Contact FROM Customers;
And if you use the following 2 statements, you will be getting the same null value populated in the column.
SELECT '' AS Contact FROM Customers; OR SELECT null AS Contact FROM Customers;
This may not be an option for you, but if you can use the Parallel Extension for .NET then you could use Task
s instead of raw threads and then use Task.WaitAll()
to wait for them to complete.
-X [your method]
X lets you override the default 'Get'
** corrected lowercase x
to uppercase X
I was heard that, one of the reasons is , the project is too large, so increasing the post buffer could solve the problem. so open the editSystemWideGitConfig, and add the following statements under [http] , postBuffer = 524288000. maybe work.
You can import them like this:
In [7]: import scipy, numpy, math
In [8]: scipy.math.factorial, numpy.math.factorial, math.factorial
Out[8]:
(<function math.factorial>,
<function math.factorial>,
<function math.factorial>)
scipy.math.factorial
and numpy.math.factorial
seem to simply be aliases/references for/to math.factorial
, that is scipy.math.factorial is math.factorial
and numpy.math.factorial is math.factorial
should both give True
.
if someone facing issue of CORS not working in mobile browser or mobile applications, you can set ALLOWED_HOSTS = ["your host ip"] in backend servers where your rest api exists, here your host ip is external ip to access ionic , like External: http://192.168.1.120:8100
After that in ionic type script make post or get using IP of backened server
in my case i used django rest framwork and i started server as:- python manage.py runserver 192.168.1.120:8000
and used this ip in ionic get and post calls of rest api
If you have issues like the question ask above regarding the exception thrown when the solution is executed, the problem is permission, not properly granted to the users of that group to access the database/stored procedure. All you need do is to do something like what i have below, replacing mine with your database name, stored procedures (function)and the type of permission or role or who you are granting the access to.
USE [StableEmployee]
GO
GRANT EXEC ON dbo.GetAllEmployees TO PUBLIC
/****** Object: StoredProcedure [dbo].[GetAllEmployees] Script Date: 01/27/2016 16:27:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[GetAllEmployees]
as
Begin
Select EmployeeId, Name, Gender, City, DepartmentId
From tblEmployee
End
You need to assign display: block;
property to the wrapping anchor. Otherwise it won't wrap correctly.
<a style="display:block" href="http://justinbieber.com">
<div class="xyz">My div contents</div>
</a>
I had problem with Eclipse (started as GUI, not from script) on Maverics that it did not take custom PATH. I tried all the methods mentioned above to no avail. Finally I found the simplest working answer based on hints from here:
Go to /Applications/eclipse/Eclipse.app/Contents folder
Edit Info.plist file with text editor (or XCode), add LSEnvironment dictionary for environment variable with full path. Note that it includes also /usr/bin etc:
<dict>
<key>LSEnvironment</key>
<dict>
<key>PATH</key>
<string>/usr/bin:/bin:/usr/sbin:/sbin:/dev/android-ndk-r9b</string>
</dict>
<key>CFBundleDisplayName</key>
<string>Eclipse</string>
...
Reload parameters for app with
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.fra??mework/Support/lsregister -v -f /Applications/eclipse/Eclipse.app
Restart Eclipse
I have set up margins directly using below code
LinearLayout layout = (LinearLayout)findViewById(R.id.yourrelative_layout);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
params.setMargins(3, 300, 3, 3);
layout.setLayoutParams(params);
Only thing here is to notice that LayoutParams
should be imported for following package android.widget.RelativeLayout.LayoutParams
, or else there will be an error.
To do without reinstalling spyder in all environments follow official reference here.
In summary (tested with conda):
From the system prompt:
Create an new environment. Note that depending on how you create it (conda, virtualenv) the environment folder will be located at different place on your system)
Activate the environment (e.g., conda activate [yourEnvName]
)
Install spyder-kernels inside the environment (e.g., conda install spyder-kernels
)
Find and copy the path for the python executable inside the environment. Finding this path can be done using from the prompt this command python -c "import sys; print(sys.executable)"
Deactivate the environment (i.e., return to base conda deactivate
)
run spyder (spyder3
)
Finally in spyder Tool menu go to Preferences > Python Interpreter > Use the following interpreter and paste the environment python executable path
Restart the ipython console
PS: in spyder you should see at the bottom something like this
Voila
Well, using the static Drawable.createFromPath(String pathName)
seems a bit more straightforward to me than decoding it yourself... :-)
If your mImg
is a simple ImageView
, you don't even need it, use mImg.setImageUri(Uri uri)
directly.
After reading many articles I decided to put all the attributes information together:
- atomic //default
- nonatomic
- strong=retain //default
- weak= unsafe_unretained
- retain
- assign //default
- unsafe_unretained
- copy
- readonly
- readwrite //default
Below is a link to the detailed article where you can find these attributes.
Many thanks to all the people who give best answers here!!
Here is the Sample Description from Article
Example :
@property (retain) NSString *name;
@synthesize name;
Example:
@property (nonatomic, retain) NSString *name;
@synthesize name;
Explain:
Suppose there is an atomic string property called "name", and if you call [self setName:@"A"] from thread A, call [self setName:@"B"] from thread B, and call [self name] from thread C, then all operation on different thread will be performed serially which means if one thread is executing setter or getter, then other threads will wait. This makes property "name" read/write safe but if another thread D calls [name release] simultaneously then this operation might produce a crash because there is no setter/getter call involved here. Which means an object is read/write safe (ATOMIC) but not thread safe as another threads can simultaneously send any type of messages to the object. Developer should ensure thread safety for such objects.
If the property "name" was nonatomic, then all threads in above example - A,B, C and D will execute simultaneously producing any unpredictable result. In case of atomic, Either one of A, B or C will execute first but D can still execute in parallel.
Example:
@property (strong, nonatomic) ViewController *viewController;
@synthesize viewController;
Example :
@property (weak, nonatomic) IBOutlet UIButton *myButton;
@synthesize myButton;
Strong & Weak Explanation, Thanks to BJ Homer:
Imagine our object is a dog, and that the dog wants to run away (be deallocated). Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached. Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it. As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out. When we use weak? The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).
Example:
@property (nonatomic, retain) NSString *name;
@synthesize name;
Example:
@property (nonatomic, assign) NSString *address;
@synthesize address;
unsafe_unretained
-unsafe_unretained is an ownership qualifier that tells ARC how to insert retain/release calls -unsafe_unretained is the ARC version of assign.
Example:
@property (nonatomic, unsafe_unretained) NSString *nickName;
@synthesize nickName;
Example:
@property (nonatomic, copy) NSArray *myArray;
@synthesize myArray;
This is a maven specific problem I think. Maven does not copy the files form /src/main/resources
to the target-test folder. You will have to do this yourself by configuring the resources plugin, if you absolutely want to go this way.
An easier way is to instead put a test specific context definition in the /src/test/resources
directory and load via:
@ContextConfiguration(locations = { "classpath:mycontext.xml" })