You could get a JavaScript object containing the parameters with something like this:
var regex = /[?&]([^=#]+)=([^&#]*)/g,
url = window.location.href,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by =
characters, and pairs themselves separated by &
characters (or an =
character for the first one). For your example, the above would result in:
{v: "123", p: "hello"}
Here's a working example.
I had the same problem. In which i have to remove white background from jpg/png image format using ImageMagick.
What worked for me was:
1) Convert image format to png: convert input.jpg input.png
2) convert input.png -fuzz 2% -transparent white output.png
Yes:
Use this to experiment with mailto form elements and link encoding.
You can enter subject, body (i.e. content), etc. into the form, hit the button and see the mailto html link that you can paste into your page.
You can even specify elements that are rarely known and used: cc, bcc, from emails.
download the right version of mysqllib.dll then copy it to ruby bin really works for me. Follow this link plases mysql2 gem compiled for wrong mysql client library
I use the following to parse Yaml files associative arrays into an object state.
This checks all supplied arrays if there are objects hiding there, and turns them also in objects.
/**
* Makes a config object from an array, making the first level keys properties a new object.
* Property values are converted to camelCase and are not set if one already exists.
* @param array $configArray Config array.
* @param boolean $strict To return an empty object if $configArray is not an array
* @return stdObject The config object
*/
public function makeConfigFromArray($configArray = [],$strict = true)
{
$object = new stdClass();
if (!is_array($configArray)) {
if(!$strict && !is_null($configArray)) {
return $configArray;
}
return $object;
}
foreach ($configArray as $name => $value) {
$_name = camel_case($name);
if(is_array($value)) {
$makeobject = true;
foreach($value as $key => $val) {
if(is_numeric(substr($key,0,1))) {
$makeobject = false;
}
if(is_array($val)) {
$value[$key] = $this->makeConfigFromArray($val,false);
}
}
if($makeobject) {
$object->{$name} = $object->{$_name} = $this->makeConfigFromArray($value,false);
}
else {
$object->{$name} = $object->{$_name} = $value;
}
}
else {
$object->{$name} = $object->{$_name} = $value;
}
}
return $object;
}
This turns a yaml configured as
fields:
abc:
type: formfield
something:
- a
- b
- c
- d:
foo:
bar
to an array consisting of:
array:1 [
"fields" => array:1 [
"abc" => array:2 [
"type" => "formfield"
"something" => array:4 [
0 => "a"
1 => "b"
2 => "c"
3 => array:1 [
"d" => array:1 [
"foo" => "bar"
]
]
]
]
]
]
to an object of:
{#325
+"fields": {#326
+"abc": {#324
+"type": "formfield"
+"something": array:4 [
0 => "a"
1 => "b"
2 => "c"
3 => {#328
+"d": {#327
+"foo": "bar"
}
}
]
}
}
}
.nil?
can be used on any object and is true if the object is nil.
.empty?
can be used on strings, arrays and hashes and returns true if:
Running .empty?
on something that is nil will throw a NoMethodError
.
That is where .blank?
comes in. It is implemented by Rails and will operate on any object as well as work like .empty?
on strings, arrays and hashes.
nil.blank? == true
false.blank? == true
[].blank? == true
{}.blank? == true
"".blank? == true
5.blank? == false
0.blank? == false
.blank?
also evaluates true on strings which are non-empty but contain only whitespace:
" ".blank? == true
" ".empty? == false
Rails also provides .present?
, which returns the negation of .blank?
.
Array gotcha: blank?
will return false
even if all elements of an array are blank. To determine blankness in this case, use all?
with blank?
, for example:
[ nil, '' ].blank? == false
[ nil, '' ].all? &:blank? == true
There is some small processing overhead in calculating the actual needed size for a column value and allocating the space for a Varchar, so if you are definitely sure how long the value will always be, it is better to use Char and avoid the hit.
I need to have two properties files, one for production and an override for development (that will not be deployed).
To have both, a Properties Bean that can be autowired and a PropertyConfigurer, you can write:
<bean id="appProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="singleton" value="true" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>classpath:live.properties</value>
<value>classpath:development.properties</value>
</list>
</property>
</bean>
and reference the Properties Bean in the PropertyConfigurer
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties" ref="appProperties" />
</bean>
The most compatible command I've found for gcc and clang on Linux (thanks to armando.sano):
$ gcc -m64 -Xlinker --verbose 2>/dev/null | grep SEARCH | sed 's/SEARCH_DIR("=\?\([^"]\+\)"); */\1\n/g' | grep -vE '^$'
if you give -m32
, it will output the correct library directories.
Examples on my machine:
for g++ -m64
:
/usr/x86_64-linux-gnu/lib64
/usr/i686-linux-gnu/lib64
/usr/local/lib/x86_64-linux-gnu
/usr/local/lib64
/lib/x86_64-linux-gnu
/lib64
/usr/lib/x86_64-linux-gnu
/usr/lib64
/usr/local/lib
/lib
/usr/lib
for g++ -m32
:
/usr/i686-linux-gnu/lib32
/usr/local/lib32
/lib32
/usr/lib32
/usr/local/lib/i386-linux-gnu
/usr/local/lib
/lib/i386-linux-gnu
/lib
/usr/lib/i386-linux-gnu
/usr/lib
Brush brush = new SolidColorBrush(color);
The other way around:
if (brush is SolidColorBrush colorBrush)
Color color = colorBrush.Color;
Or something like that.
Point being not all brushes are colors but you could turn all colors into a (SolidColor)Brush.
You should use:
protected void btn1_Click(object sender, EventArgs e)
{
Response.Redirect("otherpage.aspx");
}
This is the simple example to understand about python unpacking,
>>> def f(*args, **kwargs):
... print 'args', args, 'kwargs', kwargs
eg1:
>>>f(1, 2)
>>> args (1,2) kwargs {} #args return parameter without reference as a tuple
>>>f(a = 1, b = 2)
>>> args () kwargs {'a': 1, 'b': 2} #args is empty tuple and kwargs return parameter with reference as a dictionary
I had to change:
function start_lvl(&$output, $depth)
to:
function start_lvl( &$output, $depth = 0, $args = array() )
Because I was getting an incompatibility error:
Strict Standards: Declaration of My_Walker_Nav_Menu::start_lvl() should be compatible with Walker_Nav_Menu::start_lvl(&$output, $depth = 0, $args = Array)
Use weekday()
:
>>> import datetime
>>> datetime.datetime.today()
datetime.datetime(2012, 3, 23, 23, 24, 55, 173504)
>>> datetime.datetime.today().weekday()
4
From the documentation:
Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
I see no one has mentioned the section in the Baseline Requirements yet. I feel they are important.
Q: SSL - How do Common Names (CN) and Subject Alternative Names (SAN) work together?
A: Not at all. If there are SANs, then CN can be ignored. -- At least if the software that does the checking adheres very strictly to the CABForum's Baseline Requirements.
(So this means I can't answer the "Edit" to your question. Only the original question.)
CABForum Baseline Requirements, v. 1.2.5 (as of 2 April 2015), page 9-10:
9.2.2 Subject Distinguished Name Fields
a. Subject Common Name Field
Certificate Field: subject:commonName (OID 2.5.4.3)
Required/Optional: Deprecated (Discouraged, but not prohibited)
Contents: If present, this field MUST contain a single IP address or Fully-Qualified Domain Name that is one of the values contained in the Certificate’s subjectAltName extension (see Section 9.2.1).
RFC 2818: HTTP Over TLS, 2000, Section 3.1: Server Identity:
If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.
RFC 6125: Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS), 2011, Section 6.4.4: Checking of Common Names:
[...] if and only if the presented identifiers do not include a DNS-ID, SRV-ID, URI-ID, or any application-specific identifier types supported by the client, then the client MAY as a last resort check for a string whose form matches that of a fully qualified DNS domain name in a Common Name field of the subject field (i.e., a CN-ID).
With the following function you are just sending the pure ICMP packets using socket_create. I got the following code from a user note there. N.B. You must run the following as root.
Although you can't put this in a standard web page you can run it as a cron job and populate a database with the results.
So it's best suited if you need to monitor a site.
function twitterIsUp() {
return ping('twitter.com');
}
function ping ($host, $timeout = 1) {
/* ICMP ping packet with a pre-calculated checksum */
$package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost";
$socket = socket_create(AF_INET, SOCK_RAW, 1);
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0));
socket_connect($socket, $host, null);
$ts = microtime(true);
socket_send($socket, $package, strLen($package), 0);
if (socket_read($socket, 255)) {
$result = microtime(true) - $ts;
} else {
$result = false;
}
socket_close($socket);
return $result;
}
The <!-- -->
is only for HTML commenting and the PHP will still run anyway...
Therefore the best thing I would do is also to comment out the PHP...
Returning false
from the function will stop the event continuing. I.e. it will stop the form submitting.
i.e.
function someFunction()
{
if (allow) // For example, checking that a field isn't empty
{
return true; // Allow the form to submit
}
else
{
return false; // Stop the form submitting
}
}
I don't think you can design the if-then-else construct without taking the design for other constructs into account. I think it's a good principle that each expression should be an element, and its subexpressions should be child elements. There are then questions about whether the name of an element should reflect the type of expression it is, or its role relative to the parent. Or you can do both:
<if>
<condition>
<equals>
<number>2</number>
<number>3</number>
<equals>
<condition>
<then>
<string>Mary</string>
</then>
<else>
<concat>
<string>John</string>
<string>Smith</string>
</concat>
</else>
</if>
But you can sometimes get away with a design that omits the role-names (condition, then else) and relies on positional significance of elements relative to their parent. It depends a bit on how much you want to keep it concise.
sleep(int)
works as a good delay. For a minute:
//Doing some stuff...
sleep(60); //Freeze for A minute
//Continue doing stuff...
SQL stands for Structured Query Language, and it is a programming language designed for querying data from a database. MySQL is a relational database management system, which is a completely different thing.
MySQL is an open-source platform that uses SQL, just like MSSQL, which is Microsoft's product (not open-source) that uses SQL for database management.
To be safe you don't break stuff (for example when these strings are changed in your code or further up), or crash you program (in case the returned string was literal for example like "hello I'm a literal string"
and you start to edit it), make a copy of the returned string.
You could use strdup()
for this, but read the small print. Or you can of course create your own version if it's not there on your platform.
IF you need to softly suppress the delete and backspace keys in your Web app, so that when they are editing / deleting items the page does not get redirected unexpectedly, you can use this code:
window.addEventListener('keydown', function(e) {
var key = e.keyCode || e.which;
if (key == 8 /*BACKSPACE*/ || key == 46/*DELETE*/) {
var len=window.location.href.length;
if(window.location.href[len-1]!='#') window.location.href += "#";
}
},false);
Is the snippet you posted just a sample to show what you are trying to do?
The reason I ask is that you've named a method increment
, but you seem to be using that to set the value of a text label, rather than incrementing a value.
If you are trying to do something more complicated - such as setting an integer value and having the label display this value, you could consider using bindings. e.g
You declare a property count
and your increment
action sets this value to whatever, and then in IB, you bind the label's text to the value of count
. As long as you follow Key Value Coding (KVC) with count
, you don't have to write any code to update the label's display. And from a design perspective you've got looser coupling.
Sample application using Vue. Requires a backend server running on localhost to process the request:
var app = new Vue({
el: "#app",
data: {
file: ''
},
methods: {
submitFile() {
let formData = new FormData();
formData.append('file', this.file);
console.log('>> formData >> ', formData);
// You should have a server side REST API
axios.post('http://localhost:8080/restapi/fileupload',
formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function () {
console.log('SUCCESS!!');
})
.catch(function () {
console.log('FAILURE!!');
});
},
handleFileUpload() {
this.file = this.$refs.file.files[0];
console.log('>>>> 1st element in files array >>>> ', this.file);
}
}
});
Considering your previous example:
inventory file:
[db]
10.112.83.37
group_vars/all
data_base_url=jdbc:oracle:thin:@{{ db }}:1521/ssdenwdb
template file:
oracle_url = {{ data_base_url }}
You might want to replace your group_vars/all with
data_base_url="jdbc:oracle:thin:@{{ groups['db'][0] }}:1521/ssdenwdb"
Select * from your_table
WHERE col1 and col2 and col3 and col4 and col5 IS NOT NULL;
The only disadvantage of this approach is that you can only compare 5 columns, after that the result will always be false, so I do compare only the fields that can be NULL
.
With ASP.NET, you need to consider the reference point for a "relative URL" - is it relative to the page request, a user control, or if it is "relative" simply by virtue of using "~/"?
The Uri
class contains a simple way to convert a relative URL to an absolute URL (given an absolute URL as the reference point for the relative URL):
var uri = new Uri(absoluteUrl, relativeUrl);
If relativeUrl
is in fact an abolute URL, then the absoluteUrl
is ignored.
The only question then remains what the reference point is, and whether "~/" URLs are allowed (the Uri
constructor does not translate these).
JMX now uses port 7199 instead of port 8080 (as of Cassandra 0.8.xx).
This is configurable in your cassandra-env.sh file, but the default is 7199.
For completeness:
Along the lines of Chase's answer, I usually use as.data.frame
to coerce the matrix to a data.frame:
m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))
EDIT: speed test data.frame
vs. as.data.frame
system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
8.005 0.108 8.165
system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
3.759 0.048 3.802
Yes, it appears to be faster (by about 2 times).
Solaris has the pstack command, which was also copied into Linux.
I forgot to select Microsoft Office Developer Tools for installation initially. In my case Visual Studio Professional 2013 and also 2015.
Actually, you just need to use the following to install the tkinter for python3:
sudo apt-get install python3-tk
In addition, for Fedora users, use the following command:
sudo dnf install python3-tkinter
AFAIK, {...}
can only be used as a path, not inside a query-param. Try this instead:
public interface FooService {
@GET("/maps/api/geocode/json?sensor=false")
void getPositionByZip(@Query("address") String address, Callback<String> cb);
}
If you have an unknown amount of parameters to pass, you can use do something like this:
public interface FooService {
@GET("/maps/api/geocode/json")
@FormUrlEncoded
void getPositionByZip(@FieldMap Map<String, String> params, Callback<String> cb);
}
Using the same as approach as Romeo, I adapted it to Visual Studio 2010 :
<None Condition=" '$(Configuration)' == 'Debug' " Include="appDebug\App.config" />
<None Condition=" '$(Configuration)' == 'Release' " Include="appRelease\App.config" />
Here you need to keep both App.config files in different directories (appDebug and appRelease). I tested it and it works fine!
There's not really any "raw string"; there are raw string literals, which are exactly the string literals marked by an 'r'
before the opening quote.
A "raw string literal" is a slightly different syntax for a string literal, in which a backslash, \
, is taken as meaning "just a backslash" (except when it comes right before a quote that would otherwise terminate the literal) -- no "escape sequences" to represent newlines, tabs, backspaces, form-feeds, and so on. In normal string literals, each backslash must be doubled up to avoid being taken as the start of an escape sequence.
This syntax variant exists mostly because the syntax of regular expression patterns is heavy with backslashes (but never at the end, so the "except" clause above doesn't matter) and it looks a bit better when you avoid doubling up each of them -- that's all. It also gained some popularity to express native Windows file paths (with backslashes instead of regular slashes like on other platforms), but that's very rarely needed (since normal slashes mostly work fine on Windows too) and imperfect (due to the "except" clause above).
r'...'
is a byte string (in Python 2.*), ur'...'
is a Unicode string (again, in Python 2.*), and any of the other three kinds of quoting also produces exactly the same types of strings (so for example r'...'
, r'''...'''
, r"..."
, r"""..."""
are all byte strings, and so on).
Not sure what you mean by "going back" - there is no intrinsically back and forward directions, because there's no raw string type, it's just an alternative syntax to express perfectly normal string objects, byte or unicode as they may be.
And yes, in Python 2.*, u'...'
is of course always distinct from just '...'
-- the former is a unicode string, the latter is a byte string. What encoding the literal might be expressed in is a completely orthogonal issue.
E.g., consider (Python 2.6):
>>> sys.getsizeof('ciao')
28
>>> sys.getsizeof(u'ciao')
34
The Unicode object of course takes more memory space (very small difference for a very short string, obviously ;-).
Open Oracle SQLDeveloper
Right click on connection tab and select new connection
Enter HR_ORCL in connection name and HR for the username and password.
Specify localhost for your Hostname and enter ORCL for the SID.
Click Test.
The status of the connection Test Successfully.
The connection was not saved however click on Save button to save the connection. And then click on Connect button to connect your database.
The connection is saved and you see the connection list.
The link you referenced in your question recommends using django-cors-headers
, whose documentation says to install the library
pip install django-cors-headers
and then add it to your installed apps:
INSTALLED_APPS = (
...
'corsheaders',
...
)
You will also need to add a middleware class to listen in on responses:
MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
)
Please browse the configuration section of its documentation, paying particular attention to the various CORS_ORIGIN_
settings. You'll need to set some of those based on your needs.
Also, this might help finding the actual location the btsnoop_hci.log is being saved:
adb shell "cat /etc/bluetooth/bt_stack.conf | grep FileName"
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
Use NSLock in Swift4:
let lock = NSLock()
lock.lock()
if isRunning == true {
print("Service IS running ==> please wait")
return
} else {
print("Service not running")
}
isRunning = true
lock.unlock()
Warning The NSLock class uses POSIX threads to implement its locking behavior. When sending an unlock message to an NSLock object, you must be sure that message is sent from the same thread that sent the initial lock message. Unlocking a lock from a different thread can result in undefined behavior.
workignHoursListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,View view, int position, long id) {
viewtype yourview=yourListViewId.getChildAt(position).findViewById(R.id.viewid);
}
});
var tds = document.getElementById("ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a").getElementsByTagName("td");
time = tds[0].firstChild.value;
address = tds[3].firstChild.value;
You don't even have to set a specific width for the cells, table-layout: fixed
suffices to spread the cells evenly.
ul {_x000D_
width: 100%;_x000D_
display: table;_x000D_
table-layout: fixed;_x000D_
border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
display: table-cell;_x000D_
text-align: center;_x000D_
border: 1px solid hotpink;_x000D_
vertical-align: middle;_x000D_
word-wrap: break-word;_x000D_
}
_x000D_
<ul>_x000D_
<li>foo<br>foo</li>_x000D_
<li>barbarbarbarbar</li>_x000D_
<li>baz</li>_x000D_
</ul>
_x000D_
Note that for
table-layout
to work the table styled element must have a width set (100% in my example).
Update 2018 (as of Bootstrap 4.1)
Yes, pull-left
and pull-right
have been replaced with float-left
and float-right
in Bootstrap 4.
However, floats will not work in all cases since Bootstrap 4 is now flexbox.
To align flexbox children to the right, use auto-margins (ie: ml-auto
) or the flexbox utils (ie: justify-content-end
, align-self-end
, etc..).
Navs:
<ul class="nav">
<li><a href class="nav-link">Link</a></li>
<li><a href class="nav-link">Link</a></li>
<li class="ml-auto"><a href class="nav-link">Right</a></li>
</ul>
Breadcrumbs:
<ul class="breadcrumb">
<li><a href="/">Home</a></li>
<li class="active"><a href="/">Link</a></li>
<li class="ml-auto"><a href="/">Right</a></li>
</ul>
https://www.codeply.com/go/6ITgrV7pvL
Grid:
<div class="row">
<div class="col-3">Left</div>
<div class="col-3 ml-auto">Right</div>
</div>
Remember that when you use an instead trigger, it will not commit the insert unless you specifically tell it to in the trigger. Instead of really means do this instead of what you normally do, so none of the normal insert actions would happen.
template<class...>struct types{using type=types;};
template<class T>struct tag{using type=T;};
template<class Tag>using type_t=typename Tag::type;
the above helpers let you work with types as values.
class A {
template<class T>
A( tag<T> );
};
the tag<T>
type is a variable with no state besides the type it caries. You can use this to pass a pure-type value into a template function and have the type be deduced by the template function:
auto a = A(tag<int>{});
You can pass in more than one type:
class A {
template<class T, class U, class V>
A( types<T,U,V> );
};
auto a = A(types<int,double,std::string>{});
Both keywords are equivalent, but there are a few caveats. One is that declaring a function pointer with using T = int (*)(int, int);
is clearer than with typedef int (*T)(int, int);
. Second is that template alias form is not possible with typedef
. Third is that exposing C API would require typedef
in public headers.
The idea that you need to get the reference to the object that is contained inside a Set object is common. It can be archived by 2 ways:
Use HashSet as you wanted, then:
public Object getObjectReference(HashSet<Xobject> set, Xobject obj) {
if (set.contains(obj)) {
for (Xobject o : set) {
if (obj.equals(o))
return o;
}
}
return null;
}
For this approach to work, you need to override both hashCode() and equals(Object o) methods In the worst scenario we have O(n)
Second approach is to use TreeSet
public Object getObjectReference(TreeSet<Xobject> set, Xobject obj) {
if (set.contains(obj)) {
return set.floor(obj);
}
return null;
}
This approach gives O(log(n)), more efficient. You don't need to override hashCode for this approach but you have to implement Comparable interface. ( define function compareTo(Object o)).
Using shell,
1) For Deleting the table:
python manage.py dbshell
>> DROP TABLE {app_name}_{model_name}
2) For removing all data from table:
python manage.py shell
>> from {app_name}.models import {model_name}
>> {model_name}.objects.all().delete()
use the 'web server for chrome app'. (you actually have it on your pc, wether you know or not. just search it in cortana!). open it and click 'choose file' choose the folder with your file in it. do not actually select your file. select your files folder then click on the link(s) under the 'choose folder' button.
if it doesnt take you to the file, then add the name of the file to the urs. like this:
https://127.0.0.1:8887/fileName.txt
link to web server for chrome: click me
Giving match_parent to inflated items will do the trick. GridLayout will automatically divide max parent length based on given column number and inflate those items fitting the whole screen.
From Visual Studio 2015 and onward, you need to go to the "Exception Settings" dialog (Ctrl+Alt+E) and check off the "Common Language Runtime Exceptions" (or a specific one you want i.e. ArgumentNullException
) to make it break on handled exceptions.
If the issue is that your SpringBootApplication/Configuration you are bringing in is component scanning the package your test configurations are in, you can actually remove the @Configuration annotation from the test configurations and you can still use them in the @SpringBootTest annotations. For example, if you have a class Application that is your main configuration and a class TestConfiguration that is a configuration for certain, but not all tests, you can set up your classes as follows:
@Import(Application.class) //or the specific configurations you want
//(Optional) Other Annotations that will not trigger an autowire
public class TestConfiguration {
//your custom test configuration
}
And then you can configure your tests in one of two ways:
With the regular configuration:
@SpringBootTest(classes = {Application.class}) //won't component scan your configuration because it doesn't have an autowire-able annotation
//Other annotations here
public class TestThatUsesNormalApplication {
//my test code
}
With the test custom test configuration:
@SpringBootTest(classes = {TestConfiguration.class}) //this still works!
//Other annotations here
public class TestThatUsesCustomTestConfiguration {
//my test code
}
This should be enough to force an IE
user to drop compatibility mode in any IE
version:
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
However, there are a couple of caveats one should be aware of:
<head>
. Only the <title>
tag may be placed above it.If you don't do that, you'll get an error on IE9
Dev Tools: X-UA-Compatible META tag ignored because document mode is already finalized.
If you want this markup to validate, make sure you remember to close the meta
tag with a />
instead of just >
.
Starting with IE11
, edge mode is the preferred document mode. To support/enable that, use the HTML5 document type declaration <!doctype html>
.
If you need to support webfonts on IE7
, make sure you use <!DOCTYPE html>
. I've tested it and found that rendering webfonts on IE7
got pretty unreliable when using <!doctype html>
.
The use of Google Chrome Frame is popular, but unfortunately it's going to be dropped sometime this month, Jan. 2014.
<meta http-equiv="X-UA-Compatible" content="IE=EDGE,chrome=1">
Extensive related info here. The tip on using it as the first meta tag is on a previously mentioned source here, which has been updated.
You don't need to convert to decimal; you can also enter 46 23S, 115 22E. You can add seconds after the minutes, also separated by a space.
SELECT [UserID] FROM [User] u LEFT JOIN (
SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) t on t.TailUser=u.USerID
Using docker-compose
, you can inherit env variables in docker-compose.yml and subsequently any Dockerfile(s) called by docker-compose
to build images. This is useful when the Dockerfile
RUN
command should execute commands specific to the environment.
(your shell has RAILS_ENV=development
already existing in the environment)
docker-compose.yml:
version: '3.1'
services:
my-service:
build:
#$RAILS_ENV is referencing the shell environment RAILS_ENV variable
#and passing it to the Dockerfile ARG RAILS_ENV
#the syntax below ensures that the RAILS_ENV arg will default to
#production if empty.
#note that is dockerfile: is not specified it assumes file name: Dockerfile
context: .
args:
- RAILS_ENV=${RAILS_ENV:-production}
environment:
- RAILS_ENV=${RAILS_ENV:-production}
Dockerfile:
FROM ruby:2.3.4
#give ARG RAILS_ENV a default value = production
ARG RAILS_ENV=production
#assign the $RAILS_ENV arg to the RAILS_ENV ENV so that it can be accessed
#by the subsequent RUN call within the container
ENV RAILS_ENV $RAILS_ENV
#the subsequent RUN call accesses the RAILS_ENV ENV variable within the container
RUN if [ "$RAILS_ENV" = "production" ] ; then echo "production env"; else echo "non-production env: $RAILS_ENV"; fi
This way, I don't need to specify environment variables in files or docker-compose
build
/up
commands:
docker-compose build
docker-compose up
I fixed it by adding .encode("utf-8")
to soup
.
That means that print(soup)
becomes print(soup.encode("utf-8"))
.
In the first question, you don't need an event listener on every input that would be wasteful.
Instead, listen for the enter key and to find the currently focused element use document.activeElement
window.onkeypress = function(e) {
if (e.which == 13) {
e.preventDefault();
var nextInput = inputs.get(inputs.index(document.activeElement) + 1);
if (nextInput) {
nextInput.focus();
}
}
};
One event listener is better than many, especially on low power / mobile browsers.
I know this question already have been answer but I have made some update to the GD function :
### COST FUNCTION
def cost(theta,X,y):
### Evaluate half MSE (Mean square error)
m = len(y)
error = np.dot(X,theta) - y
J = np.sum(error ** 2)/(2*m)
return J
cost(theta,X,y)
def GD(X,y,theta,alpha):
cost_histo = [0]
theta_histo = [0]
# an arbitrary gradient, to pass the initial while() check
delta = [np.repeat(1,len(X))]
# Initial theta
old_cost = cost(theta,X,y)
while (np.max(np.abs(delta)) > 1e-6):
error = np.dot(X,theta) - y
delta = np.dot(np.transpose(X),error)/len(y)
trial_theta = theta - alpha * delta
trial_cost = cost(trial_theta,X,y)
while (trial_cost >= old_cost):
trial_theta = (theta +trial_theta)/2
trial_cost = cost(trial_theta,X,y)
cost_histo = cost_histo + trial_cost
theta_histo = theta_histo + trial_theta
old_cost = trial_cost
theta = trial_theta
Intercept = theta[0]
Slope = theta[1]
return [Intercept,Slope]
res = GD(X,y,theta,alpha)
This function reduce the alpha over the iteration making the function too converge faster see Estimating linear regression with Gradient Descent (Steepest Descent) for an example in R. I apply the same logic but in Python.
You could probably hack something together by detecting mouse movement on the body of the form and updating a global variable with the last movement time. You'd then need to have an interval timer running that periodically checks the last movement time and does something if it has been sufficiently long since the last mouse movement was detected.
If you're writing a bash script, call it by name:
#!/bin/bash
/bin/sh is not guaranteed to be bash. This caused a ton of broken scripts in Ubuntu some years ago (IIRC).
The source builtin works just fine in bash; but you might as well just use dot like Norman suggested.
Android studio 2.1.2 (or possibly earlier) will let you pick from a color wheel:
I got this by adding the following to my layout:
android:background="#FFFFFF"
Then I clicked on the FFFFFF color and clicked on the lightbulb that appeared.
I pre-allocate a vector with
> (a <- rep(NA, 10))
[1] NA NA NA NA NA NA NA NA NA NA
You can then use [] to insert values into it.
Look at these to build a solution more or less from scratch:
You always have the option of calling external tools from Java using the exec()
and similar methods. For instance, you could use wget
, or cURL
.
Then if you want to go into more fully-fledged stuff, thankfully the need for automated web-testing as given us very practical tools for this. Look at:
Some other libs are purposefully written with web-scraping in mind:
Java is a language, but also a platform, with many other languages running on it. Some of which integrate great syntactic sugar or libraries to easily build scrapers.
Check out:
If you know of a great library for Ruby (JRuby, with an article on scraping with JRuby and HtmlUnit) or Python (Jython) or you prefer these languages, then give their JVM ports a chance.
Some other similar questions:
JSON regulates key type to be string. The purpose is to support the dot notation to access the members of the object.
For example, person = {"height":170, "weight":60, "age":32}. You can access members by person.height, person.weight, etc. If JSON supports value keys, then it would look like person.0, person.1, person.2.
Jus use this code on Document.read()
$.fn.modal.Constructor.prototype.enforceFocus = function () {};
imread
is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.
Use imageio.imread
instead.
import imageio
im = imageio.imread('astronaut.png')
im.shape # im is a numpy array
(512, 512, 3)
imageio.imwrite('imageio:astronaut-gray.jpg', im[:, :, 0])
The other queries are all going base on any ONE of the conditions qualifying and it will return a record... if you want to make sure the BOTH columns of table A are matched, you'll have to do something like...
select
tA.Col1,
tA.Col2,
tB.Val
from
TableA tA
join TableB tB
on ( tA.Col1 = tB.Col1 OR tA.Col1 = tB.Col2 )
AND ( tA.Col2 = tB.Col1 OR tA.Col2 = tB.Col2 )
After installing openjdk with brew and runnning brew info openjdk
I got this
And from that I got this command here, and after running it I got Java working
sudo ln -sfn /usr/local/opt/openjdk/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk
Pecl PDO package is now deprecated. By the way the debian package php5-pgsql now includes both the regular and the PDO driver, so just:
apt-get install php-pgsql
Apache also needs to be restarted before sites can use it:
sudo systemctl restart apache2
The code you wrote will always return true
because state
cannot be both 10 and 15 for the statement to be false. if ((state != 10) && (state != 15)....
AND
is what you need not OR
.
Use $.inArray instead. This returns the index of the element in the array.
var statesArray = [10, 15, 19]; // list out all
var index = $.inArray(state, statesArray);
if(index == -1) {
console.log("Not there in array");
return true;
} else {
console.log("Found it");
return false;
}
I think this suits perfect for any color you have:
a {
color: inherit;
}
These are the directories that gcc looks in by default for the specified header files ( given that the header files are included in chevrons <>); 1. /usr/local/include/ --used for 3rd party header files. 2. /usr/include/ -- used for system header files.
If in case you decide to put your custom header file in a place other than the above mentioned directories, you can include them as follows: 1. using quotes ("./custom_header_files/foo.h") with files path, instead of chevrons in the include statement. 2. using the -I switch when compiling the code. gcc -I /home/user/custom_headers/ -c foo.c -p foo.o Basically the -I switch tells the compiler to first look in the directory specified with the -I switch ( before it checks the standard directories).When using the -I switch the header files may be included using chevrons.
just like Gregory Seront said here:
Actually if you downloaded the icons pack from the android web site, you will see that you have one folder per resolution named drawable-mdpi etc. Copy all folders into the res (not the drawable) folder in Android Studio. This will automatically make all the different resolution of the icon available.
but if your not getting the images from a generator site (maybe your UX team provides them), just make sure your folders are named drawable-hdpi, drawable-mdpi, etc. then in mac select all folders by holding shift and then copy them (DO NOT DRAG). Paste the folders into the res folder. android will take care of the rest and copy all drawables into the correct folder.
For PHP 5 >= 5.3.0 http://www.php.net/manual/en/datetime.createfromformat.php
$datetime = "20130409163705";
$d = DateTime::createFromFormat("YmdHis", $datetime);
echo $d->format("d/m/Y H:i:s"); // or any you want
Result:
09/04/2013 16:37:05
Adding to exebook's response, the mathematics usage of the keyword let also encapsulates well the scoping implications of let
when used in Javascript/ES6. Specifically, just as the following ES6 code is not aware of the assignment in braces of toPrint
when it prints out the value of 'Hello World'
,
let toPrint = 'Hello World.';
{
let toPrint = 'Goodbye World.';
}
console.log(toPrint); // Prints 'Hello World'
let as used in formalized mathematics (especially the writing of proofs) indicates that the current instance of a variable exists only for the scope of that logical idea. In the following example, x immediately gains a new identity upon entering the new idea (usually these are concepts necessary to prove the main idea) and reverts immediately to the old x upon the conclusion of the sub-proof. Of course, just as in coding, this is considered somewhat confusing and so is usually avoided by choosing a different name for the other variable.
Let x be so and so...
Proof stuff
New Idea { Let x be something else ... prove something } Conclude New Idea
Prove main idea with old x
Why not? You can use switch implementation with equivalent syntax and same semantics.
The C
language does not have objects and strings objects at all, but
strings in C
is null terminated strings referenced by pointer.
The C++
language have possibility to make overload functions for
objects comparision or checking objects equalities.
As C
as C++
is enough flexible to have such switch for strings for C
language and for objects of any type that support comparaison or check
equality for C++
language. And modern C++11
allow to have this switch
implementation enough effective.
Your code will be like this:
std::string name = "Alice";
std::string gender = "boy";
std::string role;
SWITCH(name)
CASE("Alice") FALL
CASE("Carol") gender = "girl"; FALL
CASE("Bob") FALL
CASE("Dave") role = "participant"; BREAK
CASE("Mallory") FALL
CASE("Trudy") role = "attacker"; BREAK
CASE("Peggy") gender = "girl"; FALL
CASE("Victor") role = "verifier"; BREAK
DEFAULT role = "other";
END
// the role will be: "participant"
// the gender will be: "girl"
It is possible to use more complicated types for example std::pairs
or any structs or classes that support equality operations (or comarisions for quick mode).
Sintax differences with language switch is
For C++97
language used linear search.
For C++11
and more modern possible to use quick
mode wuth tree search where return statement in CASE becoming not allowed.
The C
language implementation exists where char*
type and zero-terminated string comparisions is used.
Read more about this switch implementation.
I you only want to see what was printed in the console you could simple add the "printed" part somewhere in your HTML so it will appear in on the webpage. You could do it for yourself, but there is a javascript file that does this for you. You can read about it here:
http://www.hnldesign.nl/work/code/mobileconsole-javascript-console-for-mobile-devices/
The code is available from Github; you can download it and paste it into a javascipt file and add it in to your HTML
In arraylist you have a positional order and not a nominal order, so you need to know in advance the element position you need to select or you must loop between elements until you find the element that you need to use. To do this you can use an iterator and an if, for example:
Iterator iter = list.iterator();
while (iter.hasNext())
{
// if here
System.out.println("string " + iter.next());
}
To export a single component in ES6, you can use export default
as follows:
class MyClass extends Component {
...
}
export default MyClass;
And now you use the following syntax to import that module:
import MyClass from './MyClass.react'
If you are looking to export multiple components from a single file the declaration would look something like this:
export class MyClass1 extends Component {
...
}
export class MyClass2 extends Component {
...
}
And now you can use the following syntax to import those files:
import {MyClass1, MyClass2} from './MyClass.react'
You can use setattr
name = 'varname'
value = 'something'
setattr(self, name, value) #equivalent to: self.varname= 'something'
print (self.varname)
#will print 'something'
But, since you should inform an object to receive the new variable, this only works inside classes or modules.
Another way you can achieve a pause between animations is to apply a second animation that hides the element for the amount of delay you want. This has the benefit of allowing you to use a CSS easing function like you would normally.
.star {
animation: shooting-star 1000ms ease-in-out infinite,
delay-animation 2000ms linear infinite;
}
@keyframes shooting-star {
0% {
transform: translate(0, 0) rotate(45deg);
}
100% {
transform: translate(300px, 300px) rotate(45deg);
}
}
@keyframes delay-animation {
0% {
opacity: 1;
}
50% {
opacity: 1;
}
50.01% {
opacity: 0;
}
100% {
opacity: 0;
}
}
This only works if you want the delay to be a multiple of the animation duration. I used this to make a shower of shooting stars appear more random: https://codepen.io/ericdjohnson/pen/GRpOgVO
There's no built-in function for this.
Function SheetExists(SheetName As String, Optional wb As Excel.Workbook)
Dim s As Excel.Worksheet
If wb Is Nothing Then Set wb = ThisWorkbook
On Error Resume Next
Set s = wb.Sheets(SheetName)
On Error GoTo 0
SheetExists = Not s Is Nothing
End Function
The only hard rule where list
must be used is where you need to distribute pointers to elements of the container.
Unlike with vector
, you know that the memory of elements won't be reallocated. If it could be then you might have pointers to unused memory, which is at best a big no-no and at worst a SEGFAULT
.
(Technically a vector
of *_ptr
would also work but in that case you are emulating list
so that's just semantics.)
Other soft rules have to do with the possible performance issues of inserting elements into the middle of a container, whereupon list
would be preferable.
If you are storing keys/values as strings, then this will work:
HashMap<String, String> newMap = new HashMap<String, String>();
newMap.put("my_code", "shhh_secret");
String value = newMap.get("my_code");
The question is what gets populated in the HashMap (key & value)
You can also do string concat with template literals. I updated the other posters' JSPerf tests to include it.
for (var res = '', i = 0; i < data.length; i++) {
res = `${res}${data[i]}`;
}
you can also print the data onto your HTML/JSP document. like:-
<!DOCTYPE html>
<html>
<head>
<title>Jsp Sample</title>
<%@page import="java.sql.*;"%>
</head>
<body bgcolor=yellow>
<%
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=(Connection)DriverManager.getConnection(
"jdbc:mysql://localhost:3306/forum","root","root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from student;");
%><table border=1 align=center style="text-align:center">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>SKILL</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
<%while(rs.next())
{
%>
<tr>
<td><%=rs.getString("id") %></td>
<td><%=rs.getString("name") %></td>
<td><%=rs.getString("skill") %></td>
<td><%=rs.getString("action") %></td>
</tr>
<%}%>
</tbody>
</table><br>
<%}
catch(Exception e){
out.print(e.getMessage());%><br><%
}
finally{
st.close();
con.close();
}
%>
</body>
</html>
<!--executeUpdate() mainupulation and executeQuery() for retriving-->
Lock makes programmers' life easier. Here are a few situations that can be achieved easily with lock.
While, the lock, and conditions build on the synchronized mechanism. Therefore, can certainly be able to achieve the same functionality that you can achieve using the lock. However, solving complex scenarios with synchronized may make your life difficult and can deviate you from solving the actual problem.
DECLARE @TABLE TABLE
(RowNo INT,ScripName VARCHAR(10),ScripCode VARCHAR(10)
,Price VARCHAR(10))
INSERT INTO @TABLE VALUES
(1,'20 MICRONS ','533022','39')
SELECT ColumnName,ColumnValue from @Table
Unpivot(ColumnValue For ColumnName IN (ScripName,ScripCode,Price)) AS H
The first case (export default {...}
) is ES2015 syntax for making some object definition available for use.
The second case (new Vue (...)
) is standard syntax for instantiating an object that has been defined.
The first will be used in JS to bootstrap Vue, while either can be used to build up components and templates.
See https://vuejs.org/v2/guide/components-registration.html for more details.
You've already got it: A if test else B
is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
The final if
clause acts as a filter, which is different from having the conditional expression.
this will solve, it will accept empty string or exact an email id
"^$|^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"
Another way, inspired from previous posts to make an extension.
We can put the image on the right or on the left
extension UITextField {
enum Direction {
case Left
case Right
}
// add image to textfield
func withImage(direction: Direction, image: UIImage, colorSeparator: UIColor, colorBorder: UIColor){
let mainView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 45))
mainView.layer.cornerRadius = 5
let view = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 45))
view.backgroundColor = .white
view.clipsToBounds = true
view.layer.cornerRadius = 5
view.layer.borderWidth = CGFloat(0.5)
view.layer.borderColor = colorBorder.cgColor
mainView.addSubview(view)
let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFit
imageView.frame = CGRect(x: 12.0, y: 10.0, width: 24.0, height: 24.0)
view.addSubview(imageView)
let seperatorView = UIView()
seperatorView.backgroundColor = colorSeparator
mainView.addSubview(seperatorView)
if(Direction.Left == direction){ // image left
seperatorView.frame = CGRect(x: 45, y: 0, width: 5, height: 45)
self.leftViewMode = .always
self.leftView = mainView
} else { // image right
seperatorView.frame = CGRect(x: 0, y: 0, width: 5, height: 45)
self.rightViewMode = .always
self.rightView = mainView
}
self.layer.borderColor = colorBorder.cgColor
self.layer.borderWidth = CGFloat(0.5)
self.layer.cornerRadius = 5
}
}
Use :
if let myImage = UIImage(named: "my_image"){
textfield.withImage(direction: .Left, image: myImage, colorSeparator: UIColor.orange, colorBorder: UIColor.black)
}
Enjoy :)
Complete guide related to Screen sizes
JavaScript
For height:
document.body.clientHeight // Inner height of the HTML document body, including padding
// but not the horizontal scrollbar height, border, or margin
screen.height // Device screen height (i.e. all physically visible stuff)
screen.availHeight // Device screen height minus the operating system taskbar (if present)
window.innerHeight // The current document's viewport height, minus taskbars, etc.
window.outerHeight // Height the current window visibly takes up on screen
// (including taskbars, menus, etc.)
Note: When the window is maximized this will equal screen.availHeight
For width:
document.body.clientWidth // Full width of the HTML page as coded, minus the vertical scroll bar
screen.width // Device screen width (i.e. all physically visible stuff)
screen.availWidth // Device screen width, minus the operating system taskbar (if present)
window.innerWidth // The browser viewport width (including vertical scroll bar, includes padding but not border or margin)
window.outerWidth // The outer window width (including vertical scroll bar,
// toolbars, etc., includes padding and border but not margin)
Jquery
For height:
$(document).height() // Full height of the HTML page, including content you have to
// scroll to see
$(window).height() // The current document's viewport height, minus taskbars, etc.
$(window).innerHeight() // The current document's viewport height, minus taskbars, etc.
$(window).outerHeight() // The current document's viewport height, minus taskbars, etc.
For width:
$(document).width() // The browser viewport width, minus the vertical scroll bar
$(window).width() // The browser viewport width (minus the vertical scroll bar)
$(window).innerWidth() // The browser viewport width (minus the vertical scroll bar)
$(window).outerWidth() // The browser viewport width (minus the vertical scroll bar)
set android:dividerHeight="1dp"
<ListView
android:id="@+id/myphnview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@drawable/dividerheight"
android:background="#E9EAEC"
android:clickable="true"
android:divider="@color/white"
android:dividerHeight="1dp"
android:headerDividersEnabled="true" >
</ListView>
Since there's a chance that your excel files are coming from different computers/people; there's a chance that the formatting is messy; so be extra cautious.
I just imported data from 50 odd excels where the dates were entered in DD/MM/YYYY
or DD-MM-YYYY
, but most of the Excel files stored them as MM/DD/YYYY
(Probably because the PCs were setup with en-us
instead of en-gb
or en-in
).
Even more irritating was the fact that dates above 13/MM/YYYY
were in DD/MM/YYYY
format still. So there was variations within the Excel files.
The most reliable solution I figured out was to manually set the Date column on each excel file to to be Plain Text -- then use this code to parse it:
if date_str_from_excel:
try:
return datetime.strptime(date_str_from_excel, '%d/%m/%Y')
except ValueError:
print("Unable to parse date")
LocalDate::plusMonths
Example:
LocalDate.now( )
.plusMonths( 1 );
Better to specify time zone.
LocalDate.now( ZoneId.of( "America/Montreal" )
.plusMonths( 1 );
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
. The Joda-Time team also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
If you want the date-only, use the LocalDate
class.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
today.toString(): 2017-01-23
Add a month.
LocalDate oneMonthLater = today.plusMonths( 1 );
oneMonthLater.toString(): 2017-02-23
Perhaps you want a time-of-day along with the date.
First get the current moment in UTC with a resolution of nanoseconds.
Instant instant = Instant.now();
Adding a month means determining dates. And determining dates means applying a time zone. For any given moment, the date varies around the world with a new day dawning earlier to the east. So adjust that Instant
into a time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Now add your month. Let java.time handle Leap month, and the fact that months vary in length.
ZonedDateTime zdtMonthLater = zdt.plusMonths( 1 );
You might want to adjust the time-of-day to the first moment of the day when making this kind of calculation. That first moment is not always 00:00:00.0
so let java.time determine the time-of-day.
ZonedDateTime zdtMonthLaterStartOfDay = zdtMonthLater.toLocalDate().atStartOfDay( zoneId );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Update: The Joda-Time project is now in maintenance mode. Its team advises migration to the java.time classes. I am leaving this section intact for posterity.
The Joda-Time library offers a method to add months in a smart way.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime now = DateTime.now( timeZone );
DateTime nextMonth = now.plusMonths( 1 );
You might want to focus on the day by adjust the time-of-day to the first moment of the day.
DateTime nextMonth = now.plusMonths( 1 ).withTimeAtStartOfDay();
Choosing older simulator versions is not obvious in Xcode 3.2.5. Older Xcodes had separate lists of "iOS Device SDKs" and "iOS Simulator SDKs" in the "Base SDK" build setting popup menu, but in Xcode 3.2.5 these have been replaced with a single "iOS SDKs" list that only offers 4.2 and "latest".
If you create a new default iOS project, it defaults to 4.2 for both Base SDK and Deployment Target, and in the "Overview" popup in the project's top-left corner, only the 4.2 Simulator is available.
To run an older iOS simulator, you must choose an older iOS version in the "iOS Deployment Target" build setting popup. Only then will the "Overview" popup offer older Simulators: back to 4.0 for iPhone and to 3.2 for iPad.
I would put an absolutely positioned, z-index: 100;
span (or spans) with the background: url("myImageWithRoundedCorners.jpg");
set on it inside the #mainWrapperDivWithBGImage
.
$(document).ready(function() {
$('#div_one').bind('click', function() {
$('#div_two').addClass('large');
});
});
If I understood your question.
Or you can modify css directly:
var $speech = $('div.speech');
var currentSize = $speech.css('fontSize');
$speech.css('fontSize', '10px');
1) Add On Error Resume Next
at top of the page
2) Add following code at bottom of the page
If Err.Number <> 0 Then
Response.Write (Err.Description)
Response.End
End If
On Error GoTo 0
Window -> New Window
This opens a new window and you can then open another project in it. You can use this as a workaround hopefully.
It actually allows you to work in same workspace.
For reference, these are very similar questions.
These seem to work the best for me. They also work with spaces, and don't re-add ignored files. I didn't see them listed on any of the other answers I saw.
adding:
svn st | grep ^? | sed 's/? //' | xargs svn add
removing:
svn st | grep ^! | sed 's/! //' | xargs svn rm
Edit: It's important to NOT use "add *" if you want to keep your ignored files, otherwise everything that was ignored will be re-added.
CSS properties should be set by cssText
property or setAttribute
method.
// Set multiple styles in a single statement
elt.style.cssText = "color: blue; border: 1px solid black";
// Or
elt.setAttribute("style", "color:red; border: 1px solid blue;");
Styles should not be set by assigning a string directly to the style
property (as in elt.style = "color: blue;"
), since it is considered read-only, as the style
attribute returns a CSSStyleDeclaration
object which is also read-only.
I was looking through source 1.3.2, when using JSONP, the request is made by building a SCRIPT element dynamically, which gets past the browsers Same-domain policy. Naturally, you can't make a POST request using a SCRIPT element, the browser would fetch the result using GET.
As you are requesting a JSONP call, the SCRIPT element is not generated, because it only does this when the Type of AJAX call is set to GET.
I also recommend httplib2 by Joe Gregario. I use this regularly instead of httplib in the standard lib.
Practically speaking size_t
represents the number of bytes you can address. On most modern architectures for the last 10-15 years that has been 32 bits which has also been the size of a unsigned int. However we are moving to 64bit addressing while the uint
will most likely stay at 32bits (it's size is not guaranteed in the c++ standard). To make your code that depends on the memory size portable across architectures you should use a size_t
. For example things like array sizes should always use size_t
's. If you look at the standard containers the ::size()
always returns a size_t
.
Also note, visual studio has a compile option that can check for these types of errors called "Detect 64-bit Portability Issues".
The correct answer is:
Blah.find({}).sort({date: -1}).execFind(function(err,docs){
});
I ended up using the schedule module. The API is nice.
import schedule
import time
def job():
print("I'm working...")
schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every(5).to(10).minutes.do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)
schedule.every().minute.at(":17").do(job)
while True:
schedule.run_pending()
time.sleep(1)
maybe problem with margin?
width:auto;
padding: 0px;
margin: 0px
This should work in modern browsers:
input[value]:not([value=""])
It selects all inputs with value attribute and then select inputs with non empty value among them.
The main reason why the error has been generated is because there is already an existing value of 1
for the column ID
in which you define it as PRIMARY KEY
(values are unique) in the table you are inserting.
Why not set the column ID
as AUTO_INCREMENT
?
CREATE TABLE IF NOT EXISTS `PROGETTO`.`UFFICIO-INFORMAZIONI` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`viale` VARCHAR(45) NULL ,
.....
and when you are inserting record, you can now skip the column ID
INSERT INTO `PROGETTO`.`UFFICIO-INFORMAZIONI` (`viale`, `num_civico`, ...)
VALUES ('Viale Cogel ', '120', ...)
This depends on implementation, but usually on x86 and other popular architectures like ARM int
s take 4 bytes. You can always check at compile time using sizeof(int)
or whatever other type you want to check.
If you want to make sure you use a type of a specific size, use the types in <stdint.h>
new String(byteArray, Charset.defaultCharset())
This will convert a byte array to the default charset in java. It may throw exceptions depending on what you supply with the byteArray.
For swift:
cell.selectionStyle = .None
cell.userInteractionEnabled = false
In C++17, use std::to_chars
as:
std::array<char, 10> str;
std::to_chars(str.data(), str.data() + str.size(), 42);
In C++11, use std::to_string
as:
std::string s = std::to_string(number);
char const *pchar = s.c_str(); //use char const* as target type
And in C++03, what you're doing is just fine, except use const
as:
char const* pchar = temp_str.c_str(); //dont use cast
The key here is to visualise the call tree. Once done that, the complexity is:
nodes of the call tree * complexity of other code in the function
the latter term can be computed the same way we do for a normal iterative function.
Instead, the total nodes of a complete tree are computed as
C^L - 1
------- , when C>1
/ C - 1
/
# of nodes =
\
\
L , when C=1
Where C is number of children of each node and L is the number of levels of the tree (root included).
It is easy to visualise the tree. Start from the first call (root node) then draw a number of children same as the number of recursive calls in the function. It is also useful to write the parameter passed to the sub-call as "value of the node".
So, in the examples above:
n level 1 n-1 level 2 n-2 level 3 n-3 level 4 ... ~ n levels -> L = n
n n-5 n-10 n-15 ... ~ n/5 levels -> L = n/5
n n/5 n/5^2 n/5^3 ... ~ log5(n) levels -> L = log5(n)
n level 1 n-1 n-1 level 2 n-2 n-2 n-2 n-2 ... n-3 n-3 n-3 n-3 n-3 n-3 n-3 n-3 ... ... ~ n levels -> L = n
n n-5 n-10 n-15 ... ~ n/5 levels -> L = n/5
Run the following command (it will work):
export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
sudo dpkg-reconfigure locales
You can do this without moment.js
A way to do this in native Javascript code :
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
firstDay = moment(firstDay).format(yourFormat);
lastDay = moment(lastDay).format(yourFormat);
You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):
Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
Write-Host $_.IP1
Write-Host $_.IP2
...
}
The data is UTF-8 encoded bytes escaped with URL quoting, so you want to decode, with urllib.parse.unquote()
, which handles decoding from percent-encoded data to UTF-8 bytes and then to text, transparently:
from urllib.parse import unquote
url = unquote(url)
Demo:
>>> from urllib.parse import unquote
>>> url = 'example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0'
>>> unquote(url)
'example.com?title=????????+??????'
The Python 2 equivalent is urllib.unquote()
, but this returns a bytestring, so you'd have to decode manually:
from urllib import unquote
url = unquote(url).decode('utf8')
We have to consider the orientation of device too:
CGFloat screenHeight;
// it is important to do this after presentModalViewController:animated:
if ([[UIApplication sharedApplication] statusBarOrientation] == UIDeviceOrientationPortrait || [[UIApplication sharedApplication] statusBarOrientation] == UIDeviceOrientationPortraitUpsideDown){
screenHeight = [UIScreen mainScreen].applicationFrame.size.height;
}
else{
screenHeight = [UIScreen mainScreen].applicationFrame.size.width;
}
See ?read.table
. Basically, when you use read.table
, you specify a number indicating the column:
##Row names in the first column
read.table(filname.txt, row.names=1)
Using the awesome psutil
library it's pretty simple:
p = psutil.Process(pid)
p.terminate() #or p.kill()
If you don't want to install a new library, you can use the os
module:
import os
import signal
os.kill(pid, signal.SIGTERM) #or signal.SIGKILL
See also the os.kill
documentation.
If you are interested in starting the command python StripCore.py
if it is not running, and killing it otherwise, you can use psutil
to do this reliably.
Something like:
import psutil
from subprocess import Popen
for process in psutil.process_iter():
if process.cmdline() == ['python', 'StripCore.py']:
print('Process found. Terminating it.')
process.terminate()
break
else:
print('Process not found: starting it.')
Popen(['python', 'StripCore.py'])
Sample run:
$python test_strip.py #test_strip.py contains the code above
Process not found: starting it.
$python test_strip.py
Process found. Terminating it.
$python test_strip.py
Process not found: starting it.
$killall python
$python test_strip.py
Process not found: starting it.
$python test_strip.py
Process found. Terminating it.
$python test_strip.py
Process not found: starting it.
Note: In previous psutil
versions cmdline
was an attribute instead of a method.
The only thing which works with no side-effects is to create a custom back button. As long as you don't provide a custom action, even the slide gesture works.
extension UIViewController {
func setupBackButton() {
let customBackButton = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = customBackButton
}}
Unfortunately, if you want all back buttons in the not to have any titles, you need to setup this custom back button in all your view controllers :/
override func viewDidLoad() {
super.viewDidLoad()
setupBackButton()
}
It is very important you set a whitespace as the title and not the empty string.
const urlParams = new URLSearchParams(window.location.search);
urlParams.set('order', 'date');
window.location.search = urlParams;
.set first agrument is the key, the second one is the value.
You can do something like this
<html ng-app="App" >
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
angular.module("App",[])
.controller("ctrl",['$scope',function($scope){
$scope.changedValue = function(item){
alert(item);
}
}]);
</script>
<div >
<div ng-controller="ctrl">
<select ng-model="blisterPackTemplateSelected" ng-change="changedValue(blisterPackTemplateSelected)" >
<option value="">Select Account</option>
<option value="Add">Add</option>
</select>
</div>
</div>
</html>
instead of add option you should use data-ng-options.I have used Add option for testing purpose
You just can put your query as a subquery:
SELECT avg(count)
FROM
(
SELECT COUNT (*) AS Count
FROM Table T
WHERE T.Update_time =
(SELECT MAX (B.Update_time )
FROM Table B
WHERE (B.Id = T.Id))
GROUP BY T.Grouping
) as counts
Edit: I think this should be the same:
SELECT count(*) / count(distinct T.Grouping)
FROM Table T
WHERE T.Update_time =
(SELECT MAX (B.Update_time)
FROM Table B
WHERE (B.Id = T.Id))
Often times we are interested in calculating the full significant digits, but for the visual aesthetics, we may want to see only few decimal point when we display the dataframe.
In jupyter-notebook, pandas can utilize the html formatting taking advantage of the method called style
.
For the case of just seeing two significant digits of some columns, we can use this code snippet:
import numpy as np
import pandas as pd
df = pd.DataFrame({'var1': [1.458315, 1.576704, 1.629253, 1.6693310000000001, 1.705139, 1.740447, 1.77598, 1.812037, 1.85313, 1.9439849999999999],
'var2': [1.500092, 1.6084450000000001, 1.652577, 1.685456, 1.7120959999999998, 1.741961, 1.7708009999999998, 1.7993270000000001, 1.8229819999999999, 1.8684009999999998],
'var3': [-0.0057090000000000005, -0.005122, -0.0047539999999999995, -0.003525, -0.003134, -0.0012230000000000001, -0.0017230000000000001, -0.002013, -0.001396, 0.005732]})
print(df)
var1 var2 var3
0 1.458315 1.500092 -0.005709
1 1.576704 1.608445 -0.005122
2 1.629253 1.652577 -0.004754
3 1.669331 1.685456 -0.003525
4 1.705139 1.712096 -0.003134
5 1.740447 1.741961 -0.001223
6 1.775980 1.770801 -0.001723
7 1.812037 1.799327 -0.002013
8 1.853130 1.822982 -0.001396
9 1.943985 1.868401 0.005732
df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})
Gives:
var1 var2 var3
id
0 1.46 1.50 -0.57%
1 1.58 1.61 -0.51%
2 1.63 1.65 -0.48%
3 1.67 1.69 -0.35%
4 1.71 1.71 -0.31%
5 1.74 1.74 -0.12%
6 1.78 1.77 -0.17%
7 1.81 1.80 -0.20%
8 1.85 1.82 -0.14%
9 1.94 1.87 0.57%
If display command is not found try following:
from IPython.display import display
df_style = df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})
display(df_style)
display
command, you need to have installed Ipython in your machine.display
command does not work in online python interpreter which do not have IPyton
installed such as https://repl.it/languages/python3These answers are all very good, but I wanted to share another thing I discovered on stackoverflow that is really quite useful, here is the direct link
Basically, @DidzisElferts shows how you can get all the colours, coordinates, etc that ggplot uses to build a plot you created. Very nice!
p <- ggplot(mpg,aes(x=class,fill=class)) + geom_bar()
ggplot_build(p)$data
[[1]]
fill y count x ndensity ncount density PANEL group ymin ymax xmin xmax
1 #F8766D 5 5 1 1 1 1.111111 1 1 0 5 0.55 1.45
2 #C49A00 47 47 2 1 1 1.111111 1 2 0 47 1.55 2.45
3 #53B400 41 41 3 1 1 1.111111 1 3 0 41 2.55 3.45
4 #00C094 11 11 4 1 1 1.111111 1 4 0 11 3.55 4.45
5 #00B6EB 33 33 5 1 1 1.111111 1 5 0 33 4.55 5.45
6 #A58AFF 35 35 6 1 1 1.111111 1 6 0 35 5.55 6.45
7 #FB61D7 62 62 7 1 1 1.111111 1 7 0 62 6.55 7.45
Shorter version for those who like short code:
// usage: deleteOldFiles("./xml", "xml,xsl", 24 * 3600)
function deleteOldFiles($dir, $patterns = "*", int $timeout = 3600) {
// $dir is directory, $patterns is file types e.g. "txt,xls", $timeout is max age
foreach (glob($dir."/*"."{{$patterns}}",GLOB_BRACE) as $f) {
if (is_writable($f) && filemtime($f) < (time() - $timeout))
unlink($f);
}
}
Well Boys and Girls after reading through the release notes for build 17093 in the wee small hours of the night, I have found the change point that affects my VMware Workstation VM's causing them not to work, it is the Core Isolation settings under Device Security under windows security (new name for windows defender page) in settings.
By default it is turned on, however when I turned it off and restarted my pc all my VMware VM's resumed working correctly. Perhaps a by device option could be incorporated in the next build to allow us to test individual devices / Apps responses to allow the core isolation to be on or off per device or App as required .
Open SQL Server as SA account and click on new query past the below queries
then click on execute, it will rollback all owned schema back to SA account
alter authorization on schema::[db_datareader] to [dbo]
alter authorization on schema::[db_datareader] to [db_datareader]
alter authorization on schema::[db_datawriter] to [dbo]
alter authorization on schema::[db_datawriter] to [db_datawriter]
alter authorization on schema::[db_securityadmin] to [dbo]
alter authorization on schema::[db_securityadmin] to [db_securityadmin]
alter authorization on schema::[db_accessadmin] to [dbo]
alter authorization on schema::[db_accessadmin] to [db_accessadmin]
alter authorization on schema::[db_backupoperator] to [dbo]
alter authorization on schema::[db_backupoperator] to [db_backupoperator]
alter authorization on schema::[db_ddladmin] to [dbo]
alter authorization on schema::[db_ddladmin] to [db_ddladmin]
alter authorization on schema::[db_owner] to [dbo]
alter authorization on schema::[db_owner] to [db_owner]
For those of you who get to this page using Xcode 4.3 and Lion, the command line tools are no longer bundled by default, and there is no /Developer anymore. To install them, open Xcode, go to Preferences -> Downloads -> Components -> Command Line Tools. This should install make, gcc etc.
You need to use a link function in your directive:
link: function(scope, element, attrs) {
element.on('click', function() {
$window.history.back();
});
}
See jsFiddle.
Following command worked for me, all the local committed changes are dropped & local is reset to the same as remote origin/master branch.
git reset --hard origin
The map you using here, is not the .map()
in javascript, it's Rxjs map function which working on Observables
in Angular...
So in that case you need to import it if you'd like to use map on the result data...
map(project: function(value: T, index: number): R, thisArg: any): Observable<R>
Applies a given project function to each value emitted by the source Observable, and emits the resulting values as an Observable.
So simply import it like this:
import 'rxjs/add/operator/map';
None of the other answers worked for me but this did:
SELECT CONCAT(Cust_First, ' ', Cust_Last) AS CustName FROM customer
Here is the very nice link which explains the storage of signed and unsigned INT in C -
http://answers.yahoo.com/question/index?qid=20090516032239AAzcX1O
Taken from this above article -
"process called two's complement is used to transform positive numbers into negative numbers. The side effect of this is that the most significant bit is used to tell the computer if the number is positive or negative. If the most significant bit is a 1, then the number is negative. If it's 0, the number is positive."
In the manual for GNU make, they talk about this specific example when describing the value
function:
The value function provides a way for you to use the value of a variable without having it expanded. Please note that this does not undo expansions which have already occurred; for example if you create a simply expanded variable its value is expanded during the definition; in that case the value function will return the same result as using the variable directly.
The syntax of the value function is:
$(value variable)
Note that variable is the name of a variable; not a reference to that variable. Therefore you would not normally use a ‘$’ or parentheses when writing it. (You can, however, use a variable reference in the name if you want the name not to be a constant.)
The result of this function is a string containing the value of variable, without any expansion occurring. For example, in this makefile:
FOO = $PATH all: @echo $(FOO) @echo $(value FOO)
The first output line would be ATH, since the “$P” would be expanded as a make variable, while the second output line would be the current value of your $PATH environment variable, since the value function avoided the expansion.
Instead of saying:
if [ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]; then
say:
if [[ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]]; then
You might also want to refer to Conditional Constructs.
Here is an example of Jon Adams suggestion above in order to fix a div (toolbar) to the right hand side of your page element using jQuery. The idea is to find the distance from the right hand side of the viewport to the right hand side of the page element and to keep the right hand side of the toolbar there!
<div id="pageElement"></div>
<div id="toolbar"></div>
#toolbar {
position: fixed;
}
....
function placeOnRightHandEdgeOfElement(toolbar, pageElement) {
$(toolbar).css("right", $(window).scrollLeft() + $(window).width()
- $(pageElement).offset().left
- parseInt($(pageElement).css("borderLeftWidth"),10)
- $(pageElement).width() + "px");
}
$(document).ready(function() {
$(window).resize(function() {
placeOnRightHandEdgeOfElement("#toolbar", "#pageElement");
});
$(window).scroll(function () {
placeOnRightHandEdgeOfElement("#toolbar", "#pageElement");
});
$("#toolbar").resize();
});
You probably want something like this overload of String.Join:
String.Join<T> Method (String, IEnumerable<T>)
Docs:
http://msdn.microsoft.com/en-us/library/dd992421.aspx
In your example, you'd use
String.Join("", Client);
1 for month is February. The 30th of February is changed to 1st of March. You should set 0 for month. The best is to use the constant defined in Calendar:
c1.set(2000, Calendar.JANUARY, 30);
You can try this:
Me.cbo1.Text = Me.Cbo1.Items(0).Tostring
Choose a valid timezone from the tzinfo database. They tend to take the form e.g. Africa/Gaborne
and US/Eastern
Find the one which matches the city nearest you, or the one which has your timezone, then set your value of TIME_ZONE
to match.
Small hint which other people didn't talk about: git doesn't record changes if you add empty folders in your project folder. That's it, I was adding empty folders with random names to check wether it was recording changes, it wasn't. But it started to do it as soon as I began adding files in them. Cheers.
data.matrix(SFI)
From ?data.matrix
:
Description:
Return the matrix obtained by converting all the variables in a
data frame to numeric mode and then binding them together as the
columns of a matrix. Factors and ordered factors are replaced by
their internal codes.
select status, timeplaced
from orders
where TIMEPLACED>'2017-06-12 00:00:00'
The real reason because set
does not work is the fact, that it uses the hash function to distinguish different values. This means that sets only allows hashable objects. Why a list is not hashable is already pointed out.
Trying ?max
, you'll see that it actually has a na.rm =
argument, set by default to FALSE
. (That's the common default for many other R functions, including sum()
, mean()
, etc.)
Setting na.rm=TRUE
does just what you're asking for:
d <- c(1, 100, NA, 10)
max(d, na.rm=TRUE)
If you do want to remove all of the NA
s, use this idiom instead:
d <- d[!is.na(d)]
A final note: Other functions (e.g. table()
, lm()
, and sort()
) have NA
-related arguments that use different names (and offer different options). So if NA
's cause you problems in a function call, it's worth checking for a built-in solution among the function's arguments. I've found there's usually one already there.
routes.rb
match 'controller_name/action_name' => 'controller_name#action_name', via: [:get, :post], :as => :abc
Any controller you want to redirect with parameters are given below:
redirect_to abc_path(@abc, id: @id), :notice => "message fine"
You may want to consider using <<<
e.g.
<<<VARIABLE
this is some
random text
that I'm typing
here and I will end it with the
same word I started it with
VARIABLE
More info at: http://php.net/manual/en/language.types.string.php
Btw - Some Coding environments don't know how to handle the above syntax.
var appName = System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe";
using (var Key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true))
Key.SetValue(appName, 99999, RegistryValueKind.DWord);
According to what I read here (Controlling WebBrowser Control Compatibility:
What Happens if I Set the FEATURE_BROWSER_EMULATION Document Mode Value Higher than the IE Version on the Client?
Obviously, the browser control can only support a document mode that is less than or equal to the IE version installed on the client. Using the FEATURE_BROWSER_EMULATION key works best for enterprise line of business apps where there is a deployed and support version of the browser. In the case you set the value to a browser mode that is a higher version than the browser version installed on the client, the browser control will choose the highest document mode available.
The simplest thing is to put a very high decimal number ...
I had the same problem.
I already had a g++ compiler installed thru MinGW (the package mingw32-gcc-g++) but I needed a C compiler so I ran mingw-get-setup.exe where I was able to have it install the mingw32-base package, the one with the C compiler.
Alas! I had this error when I use gcc to compile:
gcc: error: createprocess: no such file or directory
What I did was, still using the MinGW Installation Manager, I removed the C and C++ compiler packages, namely mingw32-base and mingw32-gcc-g++ and ALSO deleted the C:\MinGW directory itself. Then I reran mingw-get-setup.exe, installed mingw32-base, and voila, it worked :)
What about just using a global variable within your library, like so?
single.dart
:
library singleton;
var Singleton = new Impl();
class Impl {
int i;
}
main.dart
:
import 'single.dart';
void main() {
var a = Singleton;
var b = Singleton;
a.i = 2;
print(b.i);
}
Or is this frowned upon?
The singleton pattern is necessary in Java where the concept of globals doesn't exist, but it seems like you shouldn't need to go the long way around in Dart.
matrix.size
according to the numpy docs returns the Number of elements in the array.
Hope that helps.
Maybe a little late, but I found an easier way to set the defaults! You have to right-click on the right of your tab and choose "size", then click on your window, and it should keep it as the default size.
I guess GameObject
is a reference type. Default for reference types is null =>
you have an array of nulls.
You need to initialize each member of the array separatedly.
houses[0] = new GameObject(..);
Only then can you access the object without compilation errors.
So you can explicitly initalize the array:
for (int i = 0; i < houses.Length; i++)
{
houses[i] = new GameObject();
}
or you can change GameObject
to value type.
The formula above didn't work for me, but I used this without any issue. Pass your current location to the function, and loop through an array of markers to find the closest:
function find_closest_marker( lat1, lon1 ) {
var pi = Math.PI;
var R = 6371; //equatorial radius
var distances = [];
var closest = -1;
for( i=0;i<markers.length; i++ ) {
var lat2 = markers[i].position.lat();
var lon2 = markers[i].position.lng();
var chLat = lat2-lat1;
var chLon = lon2-lon1;
var dLat = chLat*(pi/180);
var dLon = chLon*(pi/180);
var rLat1 = lat1*(pi/180);
var rLat2 = lat2*(pi/180);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(rLat1) * Math.cos(rLat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
distances[i] = d;
if ( closest == -1 || d < distances[closest] ) {
closest = i;
}
}
// (debug) The closest marker is:
console.log(markers[closest]);
}
In the C standard, a standalone implementation doesn't have to provide all of the library functions that a hosted implementation has to provide. The C standard doesn't care about embedded, but vendors of embedded systems usually provide standalone implementations with whatever amount of libraries they're willing to provide.
C is a widely used general purpose high level programming language mainly intended for system programming.
Embedded C is an extension to C programming language that provides support for developing efficient programs for embedded devices.It is not a part of the C language
You can also refer to the articles below:
Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application.....
with filename = GetFileName(Range("A1"))
Function GetFileName(rngNamedCell As Range) As String
Dim strSaveDirectory As String: strSaveDirectory = ""
Dim strFileName As String: strFileName = ""
Dim strTestPath As String: strTestPath = ""
Dim strFileBaseName As String: strFileBaseName = ""
Dim strFilePath As String: strFilePath = ""
Dim intFileCounterIndex As Integer: intFileCounterIndex = 1
' Get the users desktop directory.
strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
Debug.Print "Saving to: " & strSaveDirectory
' Base file name
strFileBaseName = Trim(rngNamedCell.Value)
Debug.Print "File Name will contain: " & strFileBaseName
' Loop until we find a free file number
Do
If intFileCounterIndex > 1 Then
' Build test path base on current counter exists.
strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
Else
' Build test path base just on base name to see if it exists.
strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
End If
If (Dir(strTestPath) = "") Then
' This file path does not currently exist. Use that.
strFileName = strTestPath
Else
' Increase the counter as we have not found a free file yet.
intFileCounterIndex = intFileCounterIndex + 1
End If
Loop Until strFileName <> ""
' Found useable filename
Debug.Print "Free file name: " & strFileName
GetFileName = strFileName
End Function
The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.
In Action
My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.
Sub Testing()
Dim filename As String: filename = GetFileName(Range("o1"))
ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
filename:=filename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.
Try including stdint.h
or inttypes.h
.
do these
git rm --cached *
git add .
git commit -m"upload"
git push --set-upstream origin master
Happy coding!
Step 1 - Open anaconda prompt with administrator privileges.
Step 2 - check pip version pip --version
Step 3 - enter this command
**python -m pip install --upgrade pip**
The code:
public class Test {
public static void main(String args[]) {
String string = args[0];
System.out.println("last character: " +
string.substring(string.length() - 1));
}
}
The output of java Test abcdef
:
last character: f
I've been using this module ng2 truncate, its pretty easy, import module and u are ready to go... in {{ data.title | truncate : 20 }}
Utilizing the fact that you can do set operations on arrays by doing &
(intersection), -
(difference), and |
(union).
Obviously I didn't implement the MultiSet to spec, but this should get you started:
class MultiSet
attr_accessor :set
def initialize(set)
@set = set
end
# intersection
def &(other)
@set & other.set
end
# difference
def -(other)
@set - other.set
end
# union
def |(other)
@set | other.set
end
end
x = MultiSet.new([1,1,2,2,3,4,5,6])
y = MultiSet.new([1,3,5,6])
p x - y # [2,2,4]
p x & y # [1,3,5,6]
p x | y # [1,2,3,4,5,6]
A worked, completed and simple example:
package io.github.baijifeilong.excel;
import lombok.SneakyThrows;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
/**
* Created by [email protected] at 2019/12/6 11:41
*/
public class ExcelBoldTextDemo {
@SneakyThrows
public static void main(String[] args) {
new XSSFWorkbook() {{
XSSFRow row = createSheet().createRow(0);
row.setRowStyle(createCellStyle());
row.getRowStyle().getFont().setBold(true);
row.createCell(0).setCellValue("Alpha");
row.createCell(1).setCellValue("Beta");
row.createCell(2).setCellValue("Gamma");
}}.write(new FileOutputStream("demo.xlsx"));
}
}
I managed to fix it finally. The problem is not related to HikariCP.
The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting the pool. Either annotating these methods as @Transactional
or enveloping all the logic in a single call to transactional service method seem to solve the problem.
As long and your input
and label
elements are associated by their id
and for
attributes, you should be able to do something like this:
$('.input').each(function() {
$this = $(this);
$label = $('label[for="'+ $this.attr('id') +'"]');
if ($label.length > 0 ) {
//this input has a label associated with it, lets do something!
}
});
If for
is not set then the elements have no semantic relation to each other anyway, and there is no benefit to using the label tag in that instance, so hopefully you will always have that relationship defined.
I have noticed these differences:
A. We iterate the list in different way, foreach can be used for IEnumerable and while loop for IEnumerator.
B. IEnumerator can remember the current index when we pass from one method to another (it start working with current index) but IEnumerable can't remember the index and it reset the index to beginning. More in this video https://www.youtube.com/watch?v=jd3yUjGc9M0
Technically ECMAScript is the language that everyone is using and implementing -- it is the specification created many years ago when Netscape and Microsoft sat down and attempted to standardise the scripting between JavaScript (Netscape's scripting language) and JScript (Microsoft's).
Subsequently all these engines are ostensibly implementing ECMAScript, however JavaScript (the name) now hangs around for both traditional naming reasons, and as a marketing term by Mozilla for their various non-standard extensions (which they want to be able to actually "version")
This doesn't work for a fact:
$table->timestamp('created_at')->default('CURRENT_TIMESTAMP');
It doesn't remove the 'default 0' that seems to come with selecting timestamp and it just appends the custom default. But we kind of need it without the quotes. Not everything that manipulates a DB is coming from Laravel4. That's his point. He wants custom defaults on certain columns like:
$table->timestamps()->default('CURRENT_TIMESTAMP');
I don't think it's possible with Laravel. I've been searching for an hour now to see whether it's possible.
Update: Paulos Freita's answer shows that it is possible, but the syntax isn't straightforward.
You can just use: $("#msform").hide()
. This sets the element to display: none
delete the assemeblyinfo.cs file from project under properties menu and rebulid it.
For those who use Bootstrap 3, it has a great CSS class to do the job:
<img src="..." class="img-circle">
Try this:
declare @MyFloatVal float;
set @MyFloatVal=(select convert(decimal(10, 2), 10.254000))
select @MyFloatVal
Convert(decimal(18,2),r.AdditionAmount) as AdditionAmount
Add this at your TODO point:
aRange.Columns.AutoFit();
You need to start creating the JAR at the root of the files.
So, for instance:
jar cvf program.jar -C path/to/classes .
That assumes that path/to/classes
contains the com
directory.
FYI, these days it is relatively uncommon for most people to use the jar
command directly, as they will use a build tool such as Ant or Maven to take care of that (and other aspects of the build). It is well worth the effort of allowing one of those tools to take care of all aspects of your build, and it's even easier with a good IDE to help write the build.xml
(Ant) or pom.xml
(Maven).
Going back to absolute basics here. The answers on this page and a little googling have brought me to the following resolution to my issue. Steps to restart the apache service with Xampp installed:-
cd C:\xampp\apache\bin
(the default installation path for Xampp)httpd -k restart
I hope that this is of use to others just starting out with running a local Apache server.
cd ~ && apt-get source coreutils && ls -d coreutils*
You should be able to use a command like this on ubuntu to gather the source for a package, you can omit sudo
assuming your downloading to a location you own.
The C++ committee took one step forward (scoping enums out of global namespace) and fifty steps back (no enum type decay to integer). Sadly, enum class
is simply not usable if you need the value of the enum in any non-symbolic way.
The best solution is to not use it at all, and instead scope the enum yourself using a namespace or a struct. For this purpose, they are interchangable. You will need to type a little extra when refering to the enum type itself, but that will likely not be often.
struct TextureUploadFormat {
enum Type : uint32 {
r,
rg,
rgb,
rgba,
__count
};
};
// must use ::Type, which is the extra typing with this method; beats all the static_cast<>()
uint32 getFormatStride(TextureUploadFormat::Type format){
const uint32 formatStride[TextureUploadFormat::__count] = {
1,
2,
3,
4
};
return formatStride[format]; // decays without complaint
}
If you need to create each ArrayList item in a single line then you can use this code
private void createFile(String file, ArrayList<String> arrData)
throws IOException {
FileWriter writer = new FileWriter(file + ".txt");
int size = arrData.size();
for (int i=0;i<size;i++) {
String str = arrData.get(i).toString();
writer.write(str);
if(i < size-1)**//This prevent creating a blank like at the end of the file**
writer.write("\n");
}
writer.close();
}
The error happens because of you are trying to map a numeric vector to data
in geom_errorbar
: GVW[1:64,3]
. ggplot
only works with data.frame
.
In general, you shouldn't subset inside ggplot
calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame
and you will be able to plot everything in one call.
Here with a dplyr
solution to summarise the data and compute the standard error beforehand.
library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
summarise(mean = mean(value),se = sd(value) / sqrt(n()))
ggplot(d, aes(x = variable, y = mean, fill = Genotype)) +
geom_bar(position = position_dodge(), stat = "identity",
colour="black", size=.3) +
geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
size=.3, width=.2, position=position_dodge(.9)) +
xlab("Time") +
ylab("Weight [g]") +
scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"),
labels = c("Knock-out", "Wild type")) +
ggtitle("Effect of genotype on weight-gain") +
scale_y_continuous(breaks = 0:20*4) +
theme_bw()
There is small function, it allow to use construction like [1, 2].range(3, 4) -> [1, 2, 3, 4] also it works with negative params. Enjoy.
Array.prototype.range = function(from, to)
{
var range = (!to)? from : Math.abs(to - from) + 1, increase = from < to;
var tmp = Array.apply(this, {"length": range}).map(function()
{
return (increase)?from++ : from--;
}, Number);
return this.concat(tmp);
};
public static List<T> ListCompare<T>(List<T> List1 , List<T> List2 , string key )
{
return List1.Select(t => t.GetType().GetProperty(key).GetValue(t))
.Intersect(List2.Select(t => t.GetType().GetProperty(key).GetValue(t))).ToList();
}
John's answer is 99% correct. I found that (at least in my configuration), you have to open the Build settings inspector for the PROJECT. The build settings for the target do not contain "Code Signing Entitlements". Perhaps this doesn't make a difference if you have only one target in your project. But if you have multiple targets, you need to go to the project build settings. In any case, after doing what John said, my ad-hoc distribution build worked perfectly.
Found this works for me:
In the link:
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#message<?php echo $row['id'];?>">Message</button>
In the modal:
<div id="message<?php echo $row['id'];?>" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
<?php echo $row['id'];?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Dynatrace AJAX Edition shows you the exact sequence of page loading, parsing and execution.
You're right that the SD Card directory is /sdcard
but you shouldn't be hard coding it. Instead, make a call to Environment.getExternalStorageDirectory()
to get the directory:
File sdDir = Environment.getExternalStorageDirectory();
If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Travis-ci and Jenkins, while both are tools for continuous integration are very different.
Travis is a hosted service (free for open source) while you have to host, install and configure Jenkins.
Travis does not have jobs as in Jenkins. The commands to run to test the code are taken from a file named .travis.yml
which sits along your project code. This makes it easy to have different test code per branch since each branch can have its own version of the .travis.yml file.
You can have a similar feature with Jenkins if you use one of the following plugins:
.jervis.yml
file found at the root of project code. If .jervis.yml
does not exist, it will fall back to using .travis.yml
file instead.There are other hosted services you might also consider for continuous integration (non exhaustive list):
You might want to stay with Jenkins because you are familiar with it or don't want to depend on 3rd party for your continuous integration system. Else I would drop Jenkins and go with one of the free hosted CI services as they save you a lot of trouble (host, install, configure, prepare jobs)
Depending on where your code repository is hosted I would make the following choices:
To setup Travis-CI on a github project, all you have to do is:
The features you get are:
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
Here’s an example defines a SimpleDateFormat object as a static field. When two or more threads access “someMethod” concurrently with different dates, they can mess with each other’s results.
public class SimpleDateFormatExample {
private static final SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
public String someMethod(Date date) {
return simpleFormat.format(date);
}
}
You can create a service like below and use jmeter to simulate concurrent users using the same SimpleDateFormat object formatting different dates and their results will be messed up.
public class FormattedTimeHandler extends AbstractHandler {
private static final String OUTPUT_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
private static final String INPUT_TIME_FORMAT = "yyyy-MM-ddHH:mm:ss";
private static final SimpleDateFormat simpleFormat = new SimpleDateFormat(OUTPUT_TIME_FORMAT);
// apache commons lang3 FastDateFormat is threadsafe
private static final FastDateFormat fastFormat = FastDateFormat.getInstance(OUTPUT_TIME_FORMAT);
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
final String inputTime = request.getParameter("time");
Date date = LocalDateTime.parse(inputTime, DateTimeFormat.forPattern(INPUT_TIME_FORMAT)).toDate();
final String method = request.getParameter("method");
if ("SimpleDateFormat".equalsIgnoreCase(method)) {
// use SimpleDateFormat as a static constant field, not thread safe
response.getWriter().println(simpleFormat.format(date));
} else if ("FastDateFormat".equalsIgnoreCase(method)) {
// use apache commons lang3 FastDateFormat, thread safe
response.getWriter().println(fastFormat.format(date));
} else {
// create new SimpleDateFormat instance when formatting date, thread safe
response.getWriter().println(new SimpleDateFormat(OUTPUT_TIME_FORMAT).format(date));
}
}
public static void main(String[] args) throws Exception {
// embedded jetty configuration, running on port 8090. change it as needed.
Server server = new Server(8090);
server.setHandler(new FormattedTimeHandler());
server.start();
server.join();
}
}
The code and jmeter script can be downloaded here .
What the output that you need, select
or print
or .. so on.
so use the following code:
IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') select 1 else select 2
You could just use
DataGridView1.CurrentRow.Cells["ColumnName"].Value