Just put your two textviews host and port in an independant linearlayout horizontal and use android:layout_weight to make the percentage
For EditText in image above, You have to create two xml files in res-->drawable folder. First will be "bg_edittext_focused.xml" paste the lines of code in it
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#FFFFFF" />
<stroke
android:width="2dip"
android:color="#F6F6F6" />
<corners android:radius="2dip" />
<padding
android:bottom="7dip"
android:left="7dip"
android:right="7dip"
android:top="7dip" />
</shape>
Second file will be "bg_edittext_normal.xml" paste the lines of code in it
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#F6F6F6" />
<stroke
android:width="2dip"
android:color="#F6F6F6" />
<corners android:radius="2dip" />
<padding
android:bottom="7dip"
android:left="7dip"
android:right="7dip"
android:top="7dip" />
</shape>
In res-->drawable folder create another xml file with name "bg_edittext.xml" that will call above mentioned code. paste the following lines of code below in bg_edittext.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/bg_edittext_focused" android:state_focused="true"/>
<item android:drawable="@drawable/bg_edittext_normal"/>
</selector>
Finally in res-->layout-->example.xml file in your case wherever you created your editText you'll call bg_edittext.xml as background
<EditText
:::::
:::::
android:background="@drawable/bg_edittext"
:::::
:::::
/>
I wrote about this recently at http://snmaynard.com/2012/12/21/node-error-handling/. A new feature of node in version 0.8 is domains and allow you to combine all the forms of error handling into one easier manage form. You can read about them in my post.
You can also use something like Bugsnag to track your uncaught exceptions and be notified via email, chatroom or have a ticket created for an uncaught exception (I am the co-founder of Bugsnag).
This is microsoft's page on the location
tag: http://msdn.microsoft.com/en-us/library/b6x6shw7%28v=vs.100%29.aspx
It may be helpful to some folks.
with factory
/ service
/ provider
:
var myApp = angular.module('myApp', []);
//service style, probably the simplest one
myApp.service('helloWorldFromService', function() {
this.sayHello = function() {
return "Hello, World!"
};
});
//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
return {
sayHello: function() {
return "Hello, World!"
}
};
});
//provider style, full blown, configurable version
myApp.provider('helloWorld', function() {
// In the provider function, you cannot inject any
// service or factory. This can only be done at the
// "$get" method.
this.name = 'Default';
this.$get = function() {
var name = this.name;
return {
sayHello: function() {
return "Hello, " + name + "!"
}
}
};
this.setName = function(name) {
this.name = name;
};
});
//hey, we can configure a provider!
myApp.config(function(helloWorldProvider){
helloWorldProvider.setName('World');
});
function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {
$scope.hellos = [
helloWorld.sayHello(),
helloWorldFromFactory.sayHello(),
helloWorldFromService.sayHello()];
}?
In Bootstrap 3.3.x make sure you use the scrollspy JavaScript capability to track active elements. It's easy to include it in your HTML. Just do the following:
<body data-spy="scroll" data-target="Id or class of the element you want to track">
In most cases I usually track active elements on my navbar, so I do the following:
<body data-spy="scroll" data-target=".navbar-fixed-top" >
Now in your CSS you can target .navbar-fixed-top .active a
:
.navbar-fixed-top .active a {
// Put in some styling
}
This should work if you are tracking active li elements in your top fixed navigation bar.
As long as you don't want anything silly like continuous chunks:
>>> def chunkify(lst,n):
... return [lst[i::n] for i in xrange(n)]
...
>>> chunkify(range(13), 3)
[[0, 3, 6, 9, 12], [1, 4, 7, 10], [2, 5, 8, 11]]
Have a wrapper around your program that does the following.
import sys
req_version = (2,5)
cur_version = sys.version_info
if cur_version >= req_version:
import myApp
myApp.run()
else:
print "Your Python interpreter is too old. Please consider upgrading."
You can also consider using sys.version()
, if you plan to encounter people who are using pre-2.0 Python interpreters, but then you have some regular expressions to do.
And there might be more elegant ways to do this.
You have to actively choose to install MSYS to get the make.exe. So you should always have at least (the native) mingw32-make.exe if MinGW was installed properly. And if you installed MSYS you will have make.exe (in the MSYS subfolder probably).
Note that many projects require first creating a makefile (e.g. using a configure script or automake .am file) and it is this step that requires MSYS or cygwin. Makes you wonder why they bothered to distribute the native make at all.
Once you have the makefile, it is unclear if the native executable requires a different path separator than the MSYS make (forward slashes vs backward slashes). Any autogenerated makefile is likely to have unix-style paths, assuming the native make can handle those, the compiled output should be the same.
For Dropzone.js case.
In my case it's was caused because of timeout
option value was too low by default. So increase it by your needs.
{
// other dropzone options
timeout: 60000 * 10, // 10 minutes
...
}
We solved the problem by stopping the FinalizerWatchdogDaemon
.
public static void fix() {
try {
Class clazz = Class.forName("java.lang.Daemons$FinalizerWatchdogDaemon");
Method method = clazz.getSuperclass().getDeclaredMethod("stop");
method.setAccessible(true);
Field field = clazz.getDeclaredField("INSTANCE");
field.setAccessible(true);
method.invoke(field.get(null));
}
catch (Throwable e) {
e.printStackTrace();
}
}
You can call the method in Application's lifecycle, like attachBaseContext()
.
For the same reason, you also can specific the phone's manufacture to fix the problem, it's up to you.
Use sprintf
(or snprintf
if like me you can't count) with format string "pre_%d_suff"
.
For what it's worth, with itoa/strcat you could do:
char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");
The reason you are getting the unexpected result is that hist(...)
calculates the distribution from a numeric vector. In your code, table(animalFactor)
behaves like a numeric vector with three elements: 1, 3, 7. So hist(...)
plots the number of 1's (1), the number of 3's (1), and the number of 7's (1). @Roland's solution is the simplest.
Here's a way to do this using ggplot
:
library(ggplot2)
ggp <- ggplot(data.frame(animals),aes(x=animals))
# counts
ggp + geom_histogram(fill="lightgreen")
# proportion
ggp + geom_histogram(fill="lightblue",aes(y=..count../sum(..count..)))
You would get precisely the same result using animalFactor
instead of animals
in the code above.
UPDATE: Keep in mind, at the time the answer was initially written in 2010, the bellow function toFixed() worked slightly different. toFixed() seems to do some rounding now, but not in the strictly mathematical manner. So be careful with it. Do your tests... The method described bellow will do rounding well, as mathematician would expect.
toFixed()
- method converts a number into a string, keeping a specified number of decimals. It does not actually rounds up a number, it truncates the number.Math.round(n)
- rounds a number to the nearest integer. Thus turning:0.5 -> 1; 0.05 -> 0
so if you want to round, say number 0.55555, only to the second decimal place; you can do the following(this is step-by-step concept):
0.55555 * 100
= 55.555 Math.Round(55.555)
-> 56.00056.000 / 100
= 0.56000 (0.56000).toFixed(2)
-> 0.56and this is the code:
(Math.round(number * 100)/100).toFixed(2);
this work for me, thanks. I want change text size only not change font name.
var fontSizeButtonBig:Int = 30
btnMenu9.titleLabel?.font = .systemFont(ofSize: CGFloat(fontSizeButtonBig))
There are two parts to that answer (I wrote it). One part is easy to quantify, the other is more empirical.
This is the easy to quantify part. Appendix F of the current CUDA programming guide lists a number of hard limits which limit how many threads per block a kernel launch can have. If you exceed any of these, your kernel will never run. They can be roughly summarized as:
If you stay within those limits, any kernel you can successfully compile will launch without error.
This is the empirical part. The number of threads per block you choose within the hardware constraints outlined above can and does effect the performance of code running on the hardware. How each code behaves will be different and the only real way to quantify it is by careful benchmarking and profiling. But again, very roughly summarized:
The second point is a huge topic which I doubt anyone is going to try and cover it in a single StackOverflow answer. There are people writing PhD theses around the quantitative analysis of aspects of the problem (see this presentation by Vasily Volkov from UC Berkley and this paper by Henry Wong from the University of Toronto for examples of how complex the question really is).
At the entry level, you should mostly be aware that the block size you choose (within the range of legal block sizes defined by the constraints above) can and does have a impact on how fast your code will run, but it depends on the hardware you have and the code you are running. By benchmarking, you will probably find that most non-trivial code has a "sweet spot" in the 128-512 threads per block range, but it will require some analysis on your part to find where that is. The good news is that because you are working in multiples of the warp size, the search space is very finite and the best configuration for a given piece of code relatively easy to find.
Does anybody know if deep merging exists in the ES6/ES7 spec?
No, it does not.
Use the set -e
builtin:
#!/bin/bash
set -e
# Any subsequent(*) commands which fail will cause the shell script to exit immediately
Alternatively, you can pass -e
on the command line:
bash -e my_script.sh
You can also disable this behavior with set +e
.
You may also want to employ all or some of the the -e
-u
-x
and -o pipefail
options like so:
set -euxo pipefail
-e
exits on error, -u
errors on undefined variables, and -o (for option) pipefail
exits on command pipe failures. Some gotchas and workarounds are documented well here.
(*) Note:
The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test following the if or elif reserved words, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command's return value is being inverted with !
(from man bash
)
As best coding practices suggests, use setTimeout
instead of setInterval
.
function foo() {
// your function code here
setTimeout(foo, 5000);
}
foo();
Please note that this is NOT a recursive function. The function is not calling itself before it ends, it's calling a setTimeout
function that will be later call the same function again.
Basically, what is happening is that your user is either closing the browser tab, or is navigating away to a different page, before communication was complete. Your webserver (Jetty) generates this exception because it is unable to send the remaining bytes.
org.eclipse.jetty.io.EofException: null
! at org.eclipse.jetty.http.HttpGenerator.flushBuffer(HttpGenerator.java:914)
! at org.eclipse.jetty.http.HttpGenerator.complete(HttpGenerator.java:798)
! at org.eclipse.jetty.server.AbstractHttpConnection.completeResponse(AbstractHttpConnection.java:642)
!
This is not an error on your application logic side. This is simply due to user behavior. There is nothing wrong in your code per se.
There are two things you may be able to do:
If you plan on writing any asynchronous, parallel, or distributed code, you will probably prefer map
over a list comprehension -- as most asynchronous, parallel, or distributed packages provide a map
function to overload python's map
. Then by passing the appropriate map
function to the rest of your code, you may not have to modify your original serial code to have it run in parallel (etc).
With JUnit 5 I was able to solve this using the @RepeatedTest annotation:
@RepeatedTest(10)
public void testMyCode() {
//your test code goes here
}
Note that @Test
annotation shouldn't be used along with @RepeatedTest
.
as @Aurand to said, tomcat is not running. you can use the
ps -ef |grep java | grep tomcat
command to ignore the ps
programs.
worked for me in the shell scripte files.
The error suggests that the application you are trying to run cannot instantiate an instance of apache tomcat. Make sure you are running the application with tomcat.
if after checking all your dependencies you experience the same problem, try to add the following in your configuration class
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory factory =
new TomcatEmbeddedServletContainerFactory();
return factory;
}
If you are using an external instance of tomcat (especially for intellij), the problem could be that the IDE is trying to start the embedded tomcat. In this case, remove the following from your pom.xml then configure the external tomcat using the 'Edit Configurations' wizard.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
To use the window
object is not a good idea. As I see in comments,
'use strict';
function showMessage() {
window.say_hello = 'hello!';
}
console.log(say_hello);
This will throw an error to use the say_hello
variable we need to first call the showMessage function
.
Also remember that you can pass a second argument to the .forEach()
function specifying the object to use as the this
keyword.
// myOjbect is the object you want to iterate.
// Notice the second argument (secondArg) we passed to .forEach.
Object.keys(myObject).forEach(function(element, key, _array) {
// element is the name of the key.
// key is just a numerical value for the array
// _array is the array of all the keys
// this keyword = secondArg
this.foo;
this.bar();
}, secondArg);
@media only screen and (max-width: 1026px) {
#fadeshow1 {
display: none;
}
}
Any time the screen is less than 1026 pixels wide, anything inside the { }
will apply.
Some browsers don't support media queries. You can get round this using a javascript library like Respond.JS
Try this:
layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));
and for API 16<:
layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready));
Hope this code helps for creating Thumbnail for JPG, PNG & GIF formats.
<?php
$file = "D:/server/sites/Sourcefol/high/bucket/kath23.png"; /*Your Original Source Image */
$pathToSave = "D:/server/sites/Sourcefol/high/bucket/New/"; /*Your Destination Folder */
$sourceWidth =60;
$sourceHeight = 60;
$what = getimagesize($file);
$file_name = basename($file);/* Name of the Image File*/
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
/* Adding image name _thumb for thumbnail image */
$file_name = basename($file_name, ".$ext") . '_thumb.' . $ext;
switch(strtolower($what['mime']))
{
case 'image/png':
$img = imagecreatefrompng($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/png');
break;
case 'image/jpeg':
$img = imagecreatefromjpeg($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/jpeg');
break;
case 'image/gif':
$img = imagecreatefromgif($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/gif');
break;
default: die();
}
imagejpeg($new,$pathToSave.$file_name);
imagedestroy($new);
?>
This is fixed in Hamcrest 1.3. The below code compiles and does not generate any warnings:
// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, is(not(empty())));
But if you have to use older version - instead of bugged empty()
you could use:
hasSize(greaterThan(0))
(import static org.hamcrest.number.OrderingComparison.greaterThan;
or
import static org.hamcrest.Matchers.greaterThan;
)
Example:
// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, hasSize(greaterThan(0)));
The most important thing about above solutions is that it does not generate any warnings. The second solution is even more useful if you would like to estimate minimum result size.
Executing a click via JavaScript has some behaviors of which you should be aware. If for example, the code bound to the onclick
event of your element invokes window.alert()
, you may find your Selenium code hanging, depending on the implementation of the browser driver. That said, you can use the JavascriptExecutor
class to do this. My solution differs from others proposed, however, in that you can still use the WebDriver methods for locating the elements.
// Assume driver is a valid WebDriver instance that
// has been properly instantiated elsewhere.
WebElement element = driver.findElement(By.id("gbqfd"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
You should also note that you might be better off using the click()
method of the WebElement
interface, but disabling native events before instantiating your driver. This would accomplish the same goal (with the same potential limitations), but not force you to write and maintain your own JavaScript.
The "table-column" display type means it acts like the <col>
tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.
See the W3C standard for more information about the CSS table model.
* And a few other properties like borders, backgrounds.
Rune Kaagaard provided a great and compact solution that worked for me, I expanded on it a little:
def urljoin(*args):
trailing_slash = '/' if args[-1].endswith('/') else ''
return "/".join(map(lambda x: str(x).strip('/'), args)) + trailing_slash
This allows all arguments to be joined regardless of trailing and ending slashes while preserving the last slash if present.
Heavy-weight:
Lightweight:
Drawing frameworks without GUI widgets:
int min and max values
Int -2,147,483,648 / 2,147,483,647 Int 64 -9,223,372,036,854,775,808 / 9,223,372,036,854,775,807
i guess you could set a to equal 9,223,372,036,854,775,807 but it would need to be an int64
if you always want a to be grater that b why do you need to check it? just set it to be true always
I had a similar problem. The version of bootstrap.js that visual studio seems to be hosed. I just pointed to this URL instead:
<link id="active_style" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/3.1.1/cosmo/bootstrap.min.css">
For completeness, here's the HTML and javascript
<ul class="nav navbar-nav navbar-right">
<li id="theme_selector" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Theme <b class="caret"></b></a>
<ul id="theme" class="dropdown-menu" role="menu">
<li><a href="#">Amelia</a></li>
<li><a href="#">Cerulean</a></li>
<li><a href="#">Cyborg</a></li>
<li><a href="#">Cosmo</a></li>
<li><a href="#">Darkly</a></li>
<li><a href="#">Flatly</a></li>
<li><a href="#">Lumen</a></li>
<li><a href="#">Simplex</a></li>
<li><a href="#">Slate</a></li>
<li><a href="#">Spacelab</a></li>
<li><a href="#">Superhero</a></li>
<li><a href="#">United</a></li>
<li><a href="#">Yeti</a></li>
</ul>
</li>
</ul>
Javascript
$('#theme li').click(function () {
//alert('item: ' + $(this).text());
switch_style($(this).text());
});
Hope it helps someone
This does the trick, without the need to add an inline style
<div class="row-fluid">
<div class="span6">
<p>text left</p>
</div>
<div class="span6">
<div class="pull-right">
<p>text right</p>
</div>
</div>
</div>
The answer is in nesting another <div>
with the "pull-right" class. Combining the two classes won't work.
You should use $evalAsync or $timeout according to the context.
This is a link with a good explanation:
http://www.bennadel.com/blog/2605-scope-evalasync-vs-timeout-in-angularjs.htm
This is possible with a bit of format conversion.
To extract the private key in a format openssh can use:
openssl pkcs12 -in pkcs12.pfx -nocerts -nodes | openssl rsa > id_rsa
To convert the private key to a public key:
openssl rsa -in id_rsa -pubout | ssh-keygen -f /dev/stdin -i -m PKCS8
To extract the public key in a format openssh can use:
openssl pkcs12 -in pkcs12.pfx -clcerts -nokeys | openssl x509 -pubkey -noout | ssh-keygen -f /dev/stdin -i -m PKCS8
You can't push into other people's repositories. This is because push permanently gets code into their repository, which is not cool.
What you should do, is to ask them to pull from your repository. This is done in GitHub by going to the other repository and sending a "pull request".
There is a very informative article on the GitHub's help itself: https://help.github.com/articles/using-pull-requests
To interact with your own repository, you have the following commands. I suggest you start reading on Git a bit more for these instructions (lots of materials online).
To add new files to the repository or add changed files to staged area:
$ git add <files>
To commit them:
$ git commit
To commit unstaged but changed files:
$ git commit -a
To push to a repository (say origin
):
$ git push origin
To push only one of your branches (say master
):
$ git push origin master
To fetch the contents of another repository (say origin
):
$ git fetch origin
To fetch only one of the branches (say master
):
$ git fetch origin master
To merge a branch with the current branch (say other_branch
):
$ git merge other_branch
Note that origin/master
is the name of the branch you fetched in the previous step from origin
. Therefore, updating your master branch from origin is done by:
$ git fetch origin master
$ git merge origin/master
You can read about all of these commands in their manual pages (either on your linux or online), or follow the GitHub helps:
I also just changed the "Start in" setting of the shortcut icon to: %HOMEDRIVE%/xampp/htdocs/
Say you want Comic Sans for the title and Helvetica for the x label.
csfont = {'fontname':'Comic Sans MS'}
hfont = {'fontname':'Helvetica'}
plt.title('title',**csfont)
plt.xlabel('xlabel', **hfont)
plt.show()
document.getElementsByName("name")
will get several elements called by same name .
document.getElementsByName("name")[Number]
will get one of them.
document.getElementsByName("name")[Number].value
will get the value of paticular element.
The key of this question is this:
The name of elements is not unique, it is usually used for several input elements in the form.
On the other hand, the id of the element is unique, which is the only definition for a particular element in a html file.
Winstone is pretty good http://blog.jayway.com/2008/11/28/executable-war-with-winstone-maven-plugin/. But not for complex sites. And that's a shame because all it takes is to include the plugin.
Turns out I was doing it wrong, I needed to perform a nested select first of just the important columns, and do a distinct select off that to prevent trash columns of 'unique' data from corrupting my good data. The following appears to have resolved the issue... but I will try on the full dataset later.
SELECT DISTINCT P2.*
FROM (
SELECT
IDNo
, FirstName
, LastName
FROM people P
) P2
Here is some play data as requested: http://sqlfiddle.com/#!3/050e0d/3
CREATE TABLE people
(
[entry] int
, [IDNo] varchar(3)
, [FirstName] varchar(5)
, [LastName] varchar(7)
);
INSERT INTO people
(entry,[IDNo], [FirstName], [LastName])
VALUES
(1,'uqx', 'bob', 'smith'),
(2,'abc', 'john', 'willis'),
(3,'ABC', 'john', 'willis'),
(4,'aBc', 'john', 'willis'),
(5,'WTF', 'jeff', 'bridges'),
(6,'Sss', 'bill', 'doe'),
(7,'sSs', 'bill', 'doe'),
(8,'ssS', 'bill', 'doe'),
(9,'ere', 'sally', 'abby'),
(10,'wtf', 'jeff', 'bridges')
;
The simple answer is to shoot your call off to an external scrip via AJAX request. Then handle the response how you like.
As said before, Control
/Command
+ Shift
+ A
gives you basic support for tag matching. Press it again to extend the match to the parent element. Press arrow left/right to jump to the start/end tag.
Anyway, there is no built-in highlighting of matching tags. Emmet is a popular plugin but it's overkill for this purpose and can get in the way if you don't want Emmet-like editing. Bracket Highlighter seems to be a better choice for this use case.
Template argument deduction for class templates
[*this]{ std::cout << could << " be " << useful << '\n'; }
[[fallthrough]]
, [[nodiscard]]
, [[maybe_unused]]
attributes
using
in attributes to avoid having to repeat an attribute namespace.
Compilers are now required to ignore non-standard attributes they don't recognize.
Simple static_assert(expression);
with no string
no throw
unless throw()
, and throw()
is noexcept(true)
.
std::tie
with auto
const auto [it, inserted] = map.insert( {"foo", bar} );
it
and inserted
with deduced type from the pair
that map::insert
returns.std::array
s and relatively flat structsif (init; condition)
and switch (init; condition)
if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
if(decl)
to cases where decl
isn't convertible-to-bool sensibly.Generalizing range-based for loops
Fixed order-of-evaluation for (some) expressions with some modifications
.then
on future work.Forward progress guarantees (FPG) (also, FPGs for parallel algorithms)
u8'U', u8'T', u8'F', u8'8'
character literals (string already existed)
inherited constructors fixes to some corner cases (see P0136R0 for examples of behavior changes)
std::string
like reference-to-character-array or substringstring const&
again. Also can make parsing a bajillion times faster."hello world"sv
char_traits
std::byte
off more than they could chew.
std::invoke
std::apply
std::make_from_tuple
, std::apply
applied to object construction
is_invocable
, is_invocable_r
, invoke_result
result_of
is_invocable<Foo(Args...), R>
is "can you call Foo
with Args...
and get something compatible with R
", where R=void
is default.invoke_result<Foo, Args...>
is std::result_of_t<Foo(Args...)>
but apparently less confusing?[class.directory_iterator]
and [class.recursive_directory_iterator]
fstream
s can be opened with path
s, as well as with const path::value_type*
strings.
for_each_n
reduce
transform_reduce
exclusive_scan
inclusive_scan
transform_exclusive_scan
transform_inclusive_scan
Added for threading purposes, exposed even if you aren't using them threaded
atomic<T>
::is_always_lockfree
std::lock
pain when locking more than one mutex at a time.std
algorithms, and related machinery[func.searchers]
and [alg.search]
std::function
for allocatorsstd::sample
, sampling from a range?
try_emplace
and insert_or_assign
Splicing for map<>
, unordered_map<>
, set<>
, and unordered_set<>
non-const .data()
for string.
non-member std::size
, std::empty
, std::data
std::begin
/end
The emplace
family of functions now returns a reference to the created object.
unique_ptr<T[]>
fixes and other unique_ptr
tweaks.weak_from_this
and some fixed to shared from thisstd
datatype improvements:{}
construction of std::tuple
and other improvementsC++17 library is based on C11 instead of C99
Reserved std[0-9]+
for future standard libraries
std
implementations exposedstd::clamp()
std::clamp( a, b, c ) == std::max( b, std::min( a, c ) )
roughlygcd
and lcm
std::uncaught_exceptions
std::as_const
std::bool_constant
_v
template variablesstd::void_t<T>
std::owner_less<void>
std::less<void>
, but for smart pointers to sort based on contentsstd::chrono
polishstd::conjunction
, std::disjunction
, std::negation
exposedstd::not_fn
std
std::less
.<codecvt>
memory_order_consume
result_of
, replaced with invoke_result
shared_ptr::unique
, it isn't very threadsafeIsocpp.org has has an independent list of changes since C++14; it has been partly pillaged.
Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.
Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.
Additional entries pillaged from SD-6 feature-test list.
clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.
these slides had some features missing elsewhere.
While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:
register
, keyword reserved for future usebool b; ++b;
<functional>
stuff, random_shuffle
std::function
There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:
P0505R0 (constexpr chrono)
P0418R2 (atomic tweaks)
P0512R0 (template argument deduction tweaks)
P0490R0 (structured binding tweaks)
P0513R0 (changes to std::hash
)
P0502R0 (parallel exceptions)
P0509R1 (updating restrictions on exception handling)
P0012R1 (make exception specifications be part of the type system)
P0510R0 (restrictions on variants)
P0504R0 (tags for optional/variant/any)
P0497R0 (shared ptr tweaks)
P0508R0 (structured bindings node handles)
P0521R0 (shared pointer use count and unique changes?)
https://isocpp.org/files/papers/p0636r0.html
with your BigViewModel you do:
@model BigViewModel
@using(Html.BeginForm()) {
@Html.EditorFor(o => o.LoginViewModel.Email)
...
}
you can create 2 additional views
Login.cshtml
@model ViewModel.LoginViewModel
@using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
@Html.TextBoxFor(model => model.Email)
@Html.PasswordFor(model => model.Password)
}
and register.cshtml same thing
after creation you have to render them in the main view and pass them the viewmodel/viewdata
so it could be like this:
@{Html.RenderPartial("login", ViewBag.Login);}
@{Html.RenderPartial("register", ViewBag.Register);}
or
@{Html.RenderPartial("login", Model.LoginViewModel)}
@{Html.RenderPartial("register", Model.RegisterViewModel)}
using ajax parts of your web-site become more independent
iframes
, but probably this is not the case
The PHP equivalent is time()
: http://php.net/manual/en/function.time.php
After a lot of searching, the best explanation I've found is from Java Performance Tuning website in Question of the month: 1.4.1 Garbage collection algorithms, January 29th, 2003
Young generation garbage collection algorithms
The (original) copying collector (Enabled by default). When this collector kicks in, all application threads are stopped, and the copying collection proceeds using one thread (which means only one CPU even if on a multi-CPU machine). This is known as a stop-the-world collection, because basically the JVM pauses everything else until the collection is completed.
The parallel copying collector (Enabled using -XX:+UseParNewGC). Like the original copying collector, this is a stop-the-world collector. However this collector parallelizes the copying collection over multiple threads, which is more efficient than the original single-thread copying collector for multi-CPU machines (though not for single-CPU machines). This algorithm potentially speeds up young generation collection by a factor equal to the number of CPUs available, when compared to the original singly-threaded copying collector.
The parallel scavenge collector (Enabled using -XX:UseParallelGC). This is like the previous parallel copying collector, but the algorithm is tuned for gigabyte heaps (over 10GB) on multi-CPU machines. This collection algorithm is designed to maximize throughput while minimizing pauses. It has an optional adaptive tuning policy which will automatically resize heap spaces. If you use this collector, you can only use the the original mark-sweep collector in the old generation (i.e. the newer old generation concurrent collector cannot work with this young generation collector).
From this information, it seems the main difference (apart from CMS cooperation) is that UseParallelGC supports ergonomics while UseParNewGC doesn't.
Any JavaScript or CSS method is easily circumvented with Firebug (like Flickr's case).
You can use the ::selection
pseudo-element in CSS to alter the highlight color.
If the tabs are links and the dotted rectangle in active state is of concern, you can remove that too (consider usability of course).
I am using Intellij Idea 2017 and I got into the same problem. What solved the problem for me was to simply
I did a little experiment to see which of these methods
string.startswith('hello')
string.rfind('hello') == 0
string.rpartition('hello')[0] == ''
string.rindex('hello') == 0
are most efficient to return whether a certain string begins with another string.
Here is the result of one of the many test runs I've made, where each list is ordered to show the least time it took (in seconds) to parse 5 million of each of the above expressions during each iteration of the while
loop I used:
['startswith: 1.37', 'rpartition: 1.38', 'rfind: 1.62', 'rindex: 1.62']
['startswith: 1.28', 'rpartition: 1.44', 'rindex: 1.67', 'rfind: 1.68']
['startswith: 1.29', 'rpartition: 1.42', 'rindex: 1.63', 'rfind: 1.64']
['startswith: 1.28', 'rpartition: 1.43', 'rindex: 1.61', 'rfind: 1.62']
['rpartition: 1.48', 'startswith: 1.48', 'rfind: 1.62', 'rindex: 1.67']
['startswith: 1.34', 'rpartition: 1.43', 'rfind: 1.64', 'rindex: 1.64']
['startswith: 1.36', 'rpartition: 1.44', 'rindex: 1.61', 'rfind: 1.63']
['startswith: 1.29', 'rpartition: 1.37', 'rindex: 1.64', 'rfind: 1.67']
['startswith: 1.34', 'rpartition: 1.44', 'rfind: 1.66', 'rindex: 1.68']
['startswith: 1.44', 'rpartition: 1.41', 'rindex: 1.61', 'rfind: 2.24']
['startswith: 1.34', 'rpartition: 1.45', 'rindex: 1.62', 'rfind: 1.67']
['startswith: 1.34', 'rpartition: 1.38', 'rindex: 1.67', 'rfind: 1.74']
['rpartition: 1.37', 'startswith: 1.38', 'rfind: 1.61', 'rindex: 1.64']
['startswith: 1.32', 'rpartition: 1.39', 'rfind: 1.64', 'rindex: 1.61']
['rpartition: 1.35', 'startswith: 1.36', 'rfind: 1.63', 'rindex: 1.67']
['startswith: 1.29', 'rpartition: 1.36', 'rfind: 1.65', 'rindex: 1.84']
['startswith: 1.41', 'rpartition: 1.44', 'rfind: 1.63', 'rindex: 1.71']
['startswith: 1.34', 'rpartition: 1.46', 'rindex: 1.66', 'rfind: 1.74']
['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.64', 'rindex: 1.74']
['startswith: 1.38', 'rpartition: 1.48', 'rfind: 1.68', 'rindex: 1.68']
['startswith: 1.35', 'rpartition: 1.42', 'rfind: 1.63', 'rindex: 1.68']
['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.65', 'rindex: 1.75']
['startswith: 1.37', 'rpartition: 1.46', 'rfind: 1.74', 'rindex: 1.75']
['startswith: 1.31', 'rpartition: 1.48', 'rfind: 1.67', 'rindex: 1.74']
['startswith: 1.44', 'rpartition: 1.46', 'rindex: 1.69', 'rfind: 1.74']
['startswith: 1.44', 'rpartition: 1.42', 'rfind: 1.65', 'rindex: 1.65']
['startswith: 1.36', 'rpartition: 1.44', 'rfind: 1.64', 'rindex: 1.74']
['startswith: 1.34', 'rpartition: 1.46', 'rfind: 1.61', 'rindex: 1.74']
['startswith: 1.35', 'rpartition: 1.56', 'rfind: 1.68', 'rindex: 1.69']
['startswith: 1.32', 'rpartition: 1.48', 'rindex: 1.64', 'rfind: 1.65']
['startswith: 1.28', 'rpartition: 1.43', 'rfind: 1.59', 'rindex: 1.66']
I believe that it is pretty obvious from the start that the startswith
method would come out the most efficient, as returning whether a string begins with the specified string is its main purpose.
What surprises me is that the seemingly impractical string.rpartition('hello')[0] == ''
method always finds a way to be listed first, before the string.startswith('hello')
method, every now and then. The results show that using str.partition
to determine if a string starts with another string is more efficient then using both rfind
and rindex
.
Another thing I've noticed is that string.rindex('hello') == 0
and string.rindex('hello') == 0
have a good battle going on, each rising from fourth to third place, and dropping from third to fourth place, which makes sense, as their main purposes are the same.
Here is the code:
from time import perf_counter
string = 'hello world'
places = dict()
while True:
start = perf_counter()
for _ in range(5000000):
string.startswith('hello')
end = perf_counter()
places['startswith'] = round(end - start, 2)
start = perf_counter()
for _ in range(5000000):
string.rfind('hello') == 0
end = perf_counter()
places['rfind'] = round(end - start, 2)
start = perf_counter()
for _ in range(5000000):
string.rpartition('hello')[0] == ''
end = perf_counter()
places['rpartition'] = round(end - start, 2)
start = perf_counter()
for _ in range(5000000):
string.rindex('hello') == 0
end = perf_counter()
places['rindex'] = round(end - start, 2)
print([f'{b}: {str(a).ljust(4, "4")}' for a, b in sorted(i[::-1] for i in places.items())])
class Program
{
static void Main(string[] args)
{
Task.Factory.StartNew(() => MyMethod("param value"));
}
private static void MyMethod(string p)
{
Console.WriteLine(p);
}
}
You must sort your data according your needs (es. in reverse order) and use select top query
This is because You're sorting entire result-set, You should sort, every part of union separately, or You can use ORDER BY (Something ie. subquery distance) THEN (something ie row id) clause
Here is my logging class based on the accepted answer:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.*;
public class ErrorLogger
{
private Logger logger;
public ErrorLogger()
{
logger = Logger.getAnonymousLogger();
configure();
}
private void configure()
{
try
{
String logsDirectoryFolder = "logs";
Files.createDirectories(Paths.get(logsDirectoryFolder));
FileHandler fileHandler = new FileHandler(logsDirectoryFolder + File.separator + getCurrentTimeString() + ".log");
logger.addHandler(fileHandler);
SimpleFormatter formatter = new SimpleFormatter();
fileHandler.setFormatter(formatter);
} catch (IOException exception)
{
exception.printStackTrace();
}
addCloseHandlersShutdownHook();
}
private void addCloseHandlersShutdownHook()
{
Runtime.getRuntime().addShutdownHook(new Thread(() ->
{
// Close all handlers to get rid of empty .LCK files
for (Handler handler : logger.getHandlers())
{
handler.close();
}
}));
}
private String getCurrentTimeString()
{
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
return dateFormat.format(new Date());
}
public void log(Exception exception)
{
logger.log(Level.SEVERE, "", exception);
}
}
The same thing happened with me , Try checking this by double clicking on the Connection strings on the right pane of IIS 7 when you select a website.
It will give you an error (that there is some problem with web config file), because you have used URL rewrite rules and the respective component is not installed.
Install “Microsoft URL Rewrite Module 2.0 for IIS 7” and this should fix your problem
The accepted answer to how to replace multiple strings together in Oracle suggests using nested REPLACE
statements, and I don't think there is a better way.
If you are going to make heavy use of this, you could consider writing your own function:
CREATE TYPE t_text IS TABLE OF VARCHAR2(256);
CREATE FUNCTION multiple_replace(
in_text IN VARCHAR2, in_old IN t_text, in_new IN t_text
)
RETURN VARCHAR2
AS
v_result VARCHAR2(32767);
BEGIN
IF( in_old.COUNT <> in_new.COUNT ) THEN
RETURN in_text;
END IF;
v_result := in_text;
FOR i IN 1 .. in_old.COUNT LOOP
v_result := REPLACE( v_result, in_old(i), in_new(i) );
END LOOP;
RETURN v_result;
END;
and then use it like this:
SELECT multiple_replace( 'This is #VAL1# with some #VAL2# to #VAL3#',
NEW t_text( '#VAL1#', '#VAL2#', '#VAL3#' ),
NEW t_text( 'text', 'tokens', 'replace' )
)
FROM dual
This is text with some tokens to replace
If all of your tokens have the same format ('#VAL' || i || '#'
), you could omit parameter in_old
and use your loop-counter instead.
you can use DOM
$(this).children().first()
// is equivalent to
$(this.firstChild)
The biggest difference is their functionality. push_back
always puts a new element at the end of the vector
and insert
allows you to select new element's position. This impacts the performance. vector
elements are moved in the memory only when it's necessary to increase it's length because too little memory was allocated for it. On the other hand insert
forces to move all elements after the selected position of a new element. You simply have to make a place for it. This is why insert
might often be less efficient than push_back
.
SELECT distinct
group,
max_date = MAX(date) OVER (PARTITION BY group), checks
FROM table
Should work.
This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC
This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.
We control fork() process call by if, else statement. See my code below:
int main()
{
int forkresult, parent_ID;
forkresult=fork();
if(forkresult !=0 )
{
printf(" I am the parent my ID is = %d" , getpid());
printf(" and my child ID is = %d\n" , forkresult);
}
parent_ID = getpid();
if(forkresult ==0)
printf(" I am the child ID is = %d",getpid());
else
printf(" and my parent ID is = %d", parent_ID);
}
Posting this answer for folks wanting to initialize list with POCOs and also coz this is the first thing that pops up in search but all answers only for list of type string.
You can do this two ways one is directly setting the property by setter assignment or much cleaner by creating a constructor that takes in params and sets the properties.
class MObject {
public int Code { get; set; }
public string Org { get; set; }
}
List<MObject> theList = new List<MObject> { new MObject{ PASCode = 111, Org="Oracle" }, new MObject{ PASCode = 444, Org="MS"} };
OR by parameterized constructor
class MObject {
public MObject(int code, string org)
{
Code = code;
Org = org;
}
public int Code { get; set; }
public string Org { get; set; }
}
List<MObject> theList = new List<MObject> {new MObject( 111, "Oracle" ), new MObject(222,"SAP")};
I've found a solution through configuring the Spring container, but it's still not exactly what I wanted.
I rolled back to Spring 3.0.5, removed and in it's place I changed my config file to:
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</list>
</property>
</bean>
<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="jacksonSerializationConfig" />
<property name="targetMethod" value="setSerializationInclusion" />
<property name="arguments">
<list>
<value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_NULL</value>
</list>
</property>
</bean>
This is of course similar to responses given in other questions e.g.
configuring the jacksonObjectMapper not working in spring mvc 3
The important thing to note is that mvc:annotation-driven and AnnotationMethodHandlerAdapter cannot be used in the same context.
I'm still unable to get it working with Spring 3.1 and mvc:annotation-driven though. A solution that uses mvc:annotation-driven and all the benefits that accompany it would be far better I think. If anyone could show me how to do this, that would be great.
May not be answer for this specific question, but if someone is, like me, searching for answer how to fit image in ImageView with bounded size (for example, maxWidth
) while preserving Aspect Ratio and then get rid of excessive space occupied by ImageView, then the simplest solution is to use the following properties in XML:
android:scaleType="centerInside"
android:adjustViewBounds="true"
No need to use jQuery.noConflict
and all
Try this instead:
// Replace line no. 87 (guessing from your chrome console) to the following
jQuery(document).ready(function($){
// All your code using $
});
If you still get error at line 87, like Uncaught reference error: jQuery is not defined
, then you need to include jQuery file before using it, for which you can check the above answers
It's quite possible that someone will provide a truly detailed answer here, but I've always found this post from Robert Sosinski to be a great explanation of the subtleties between blocks, procs & lambdas.
I should add that I believe the post I'm linking to is specific to ruby 1.8. Some things have changed in ruby 1.9, such as block variables being local to the block. In 1.8, you'd get something like the following:
>> a = "Hello"
=> "Hello"
>> 1.times { |a| a = "Goodbye" }
=> 1
>> a
=> "Goodbye"
Whereas 1.9 would give you:
>> a = "Hello"
=> "Hello"
>> 1.times { |a| a = "Goodbye" }
=> 1
>> a
=> "Hello"
I don't have 1.9 on this machine so the above might have an error in it.
From Linux Terminal:
adb shell getprop | grep "model\|version.sdk\|manufacturer\|hardware\|platform\|revision\|serialno\|product.name\|brand"
From Windows PowerShell:
adb shell
getprop | grep -e 'model' -e 'version.sdk' -e 'manufacturer' -e 'hardware' -e 'platform' -e 'revision' -e 'serialno' -e 'product.name' -e 'brand'
Sample output for Samsung:
[gsm.version.baseband]: [G900VVRU2BOE1]
[gsm.version.ril-impl]: [Samsung RIL v3.0]
[net.knoxscep.version]: [2.0.1]
[net.knoxsso.version]: [2.1.1]
[net.knoxvpn.version]: [2.2.0]
[persist.service.bdroid.version]: [4.1]
[ro.board.platform]: [msm8974]
[ro.boot.hardware]: [qcom]
[ro.boot.serialno]: [xxxxxx]
[ro.build.version.all_codenames]: [REL]
[ro.build.version.codename]: [REL]
[ro.build.version.incremental]: [G900VVRU2BOE1]
[ro.build.version.release]: [5.0]
[ro.build.version.sdk]: [21]
[ro.build.version.sdl]: [2101]
[ro.com.google.gmsversion]: [5.0_r2]
[ro.config.timaversion]: [3.0]
[ro.hardware]: [qcom]
[ro.opengles.version]: [196108]
[ro.product.brand]: [Verizon]
[ro.product.manufacturer]: [samsung]
[ro.product.model]: [SM-G900V]
[ro.product.name]: [kltevzw]
[ro.revision]: [14]
[ro.serialno]: [e5ce97c7]
I guess problem is in width attributes in table and td remove 'px' for example
<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">
Should be
<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">
try this jquery library, jQuery Print Element
http://projects.erikzaadi.com/jQueryPlugins/jQuery.printElement/
How to do this was added to the official Django docs in Django1.4
https://docs.djangoproject.com/en/1.10/topics/db/queries/#copying-model-instances
The official answer is similar to miah's answer, but the docs point out some difficulties with inheritance and related objects, so you should probably make sure you read the docs.
Putting div inside a td made it work for me.
<table width="100%">
<tr><td><div style="font-size:2px; height:2px; vertical-align:middle;"> </div></td></tr>
You could wrap the not-bold text into a span and give the span the following properties:
.notbold{
font-weight:normal
}?
and
<h1>**This text should be bold**, <span class='notbold'>but this text should not</span></h1>
See: http://jsfiddle.net/MRcpa/1/
Use <span>
when you want to change the style of elements without placing them in a new block-level element in the document.
This is how to do it using Java 8+ :
boolean isJohnAlive = list.stream().anyMatch(o -> o.getName().equals("John"));
This sometimes happen in RStudio. In order to solve it you can attempt to plot to an external window (Windows-only):
windows() ## create window to plot your file
## ... your plotting code here ...
dev.off()
This can be done entirely with bash string manipulation:
first="I love Suzy and Mary"
second="Sara"
first=${first/Suzy/$second}
That will replace only the first occurrence; to replace them all, double the first slash:
first="Suzy, Suzy, Suzy"
second="Sara"
first=${first//Suzy/$second}
# first is now "Sara, Sara, Sara"
I don't really understand the full scope of your question, but if all you need is a hash of the string, then it's very easy to get that.
Just use the GetHashCode method.
Like this:
string hash = username.GetHashCode();
If you have both versions of PHP installed, you can switch between versions using the link
and unlink
brew
commands.
For example, to switch between PHP 7.4 and PHP 7.3
brew unlink [email protected]
brew link [email protected]
PS: both versions of PHP have be installed for these commands to work.
It also helps you to stop using your mouse so much!
In Intellij 13, it looks it's slightly different again. Here are the instructions for Intellij 13:
Classes
(even if it's properties), press OK and OK againThis is supposed to print the ASCII value of the character, as %d
is the escape sequence for an integer. So the value given as argument of printf
is taken as integer when printed.
char ch = 'a';
printf("%d", ch);
Same holds for printf("%d", '\0');
, where the NULL character is interpreted as the 0 integer.
Finally, sizeof('\n')
is 4 because in C, this notation for characters stands for the corresponding ASCII integer. So '\n' is the same as 10 as an integer.
It all depends on the interpretation you give to the bytes.
Use unshift
, which modifies the existing array by adding the arguments to the beginning:
TheArray.unshift(TheNewObject);
I think you are near to a possible solution.
Execute mainloop
in a separate thread and extend it with the property shutdown_flag
. The signal can be caught with signal.signal(signal.SIGTERM, handler)
in the main thread (not in a separate thread). The signal handler should set shutdown_flag
to True and wait for the thread to end with thread.join()
My Bots are running well against ReCaptcha.
Here my Solution.
Let your Bot do this Steps:
First write a Human Mouse Move Function to move your Mouse like a B-Spline (Ask me for Source Code). This is the most important Point.
Also use for better results a VPN like https://www.purevpn.com
For every Recpatcha do these Steps:
If you use VPN switch IP first
Clear all Browser Cookies
Clear all Browser Cache
Set one of these Useragents by Random:
a. Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
b. Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0
5 Move your Mouse with the Human Mouse Move Funktion from a RandomPoint into the I am not a Robot Image every time with different 10x10 Randomrange
Then Click ever with random delay between
WM_LBUTTONDOWN
and
WM_LBUTTONUP
Take Screenshot from Image Captcha
Send Screenshot to
or
and let they solve.
After receiving click cooridinates from captcha solver use your Human Mouse move Funktion to move and Click Recaptcha Images
Use your Human Mouse Move Funktion to move and Click to the Recaptcha Verify Button
In 75% all trys Recaptcha will solved
Chears Google
Tom
You can use the SO_RCVTIMEO and SO_SNDTIMEO socket options to set timeouts for any socket operations, like so:
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
sizeof(timeout)) < 0)
error("setsockopt failed\n");
if (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
sizeof(timeout)) < 0)
error("setsockopt failed\n");
Edit: from the setsockopt
man page:
SO_SNDTIMEO
is an option to set a timeout value for output operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for output operations to complete. If a send operation has blocked for this much time, it returns with a partial count or with the error EWOULDBLOCK if no data were sent. In the current implementation, this timer is restarted each time additional data are delivered to the protocol, implying that the limit applies to output portions ranging in size from the low-water mark to the high-water mark for output.
SO_RCVTIMEO
is an option to set a timeout value for input operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for input operations to complete. In the current implementation, this timer is restarted each time additional data are received by the protocol, and thus the limit is in effect an inactivity timer. If a receive operation has been blocked for this much time without receiving additional data, it returns with a short count or with the error EWOULDBLOCK if no data were received. The struct timeval parameter must represent a positive time interval; otherwise, setsockopt() returns with the error EDOM.
unique_ptr
is a smart pointer which owns an object exclusively.
shared_ptr
is a smart pointer for shared ownership. It is both copyable
and movable
. Multiple smart pointer instances can own the same resource. As soon as the last smart pointer owning the resource goes out of scope, the resource will be freed.
In mathematics, there are sets and ordered sets (osets).
In Python, only sets are directly implemented. We can emulate osets with regular dict keys (3.7+).
Given
a = [1, 2, 20, 6, 210, 2, 1]
b = {2, 6}
Code
oset = dict.fromkeys(a).keys()
# dict_keys([1, 2, 20, 6, 210])
Demo
Replicates are removed, insertion-order is preserved.
list(oset)
# [1, 2, 20, 6, 210]
Set-like operations on dict keys.
oset - b
# {1, 20, 210}
oset | b
# {1, 2, 5, 6, 20, 210}
oset & b
# {2, 6}
oset ^ b
# {1, 5, 20, 210}
Details
Note: an unordered structure does not preclude ordered elements. Rather, maintained order is not guaranteed. Example:
assert {1, 2, 3} == {2, 3, 1} # sets (order is ignored)
assert [1, 2, 3] != [2, 3, 1] # lists (order is guaranteed)
One may be pleased to discover that a list and multiset (mset) are two more fascinating, mathematical data structures:
Summary
Container | Ordered | Unique | Implemented
----------|---------|--------|------------
set | n | y | y
oset | y | y | n
list | y | n | y
mset | n | n | n*
*A multiset can be indirectly emulated with collections.Counter()
, a dict-like mapping of multiplicities (counts).
Here is a non-jQuery solution. Note you can't just use .click()
as some browsers do not support it.
<script type="text/javascript">
function performClick(elemId) {
var elem = document.getElementById(elemId);
if(elem && document.createEvent) {
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, false);
elem.dispatchEvent(evt);
}
}
</script>
<a href="#" onclick="performClick('theFile');">Open file dialog</a>
<input type="file" id="theFile" />
You can fix this by passing parameters rather than relying on Globals
def function(Var1, Var2):
if Var2 == 0 and Var1 > 0:
print("Result One")
elif Var2 == 1 and Var1 > 0:
print("Result Two")
elif Var1 < 1:
print("Result Three")
return Var1 - 1
function(1, 1)
I was getting same error (TypeError: unhashable type: 'slice') with below code:
included_cols = [2,4,10]
dataset = dataset[:,included_cols] #Columns 2,4 and 10 are included.
Resolved with below code by putting iloc after dataset:
included_cols = [2,4,10]
dataset = dataset.iloc[:,included_cols] #Columns 2,4 and 10 are included.
REM setting current_schema is required as the 2nd query depends on the current user referred in the session
ALTER SESSION SET CURRENT_SCHEMA=TABLE_OWNER;
SELECT table_name,
TO_NUMBER (
EXTRACTVALUE (
xmltype (
DBMS_XMLGEN.getxml ('select count(*) c from ' || table_name)),
'/ROWSET/ROW/C'))
COUNT
FROM dba_tables
WHERE owner = 'TABLE_OWNER'
ORDER BY COUNT DESC;
If you read the performance and benchmark stats on this website, you'll see that the fastest way to read (because reading, writing, and processing are all different) a text file is the following snippet of code:
using (StreamReader sr = File.OpenText(fileName))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
//do your stuff here
}
}
All up about 9 different methods were bench marked, but that one seem to come out ahead the majority of the time, even out performing the buffered reader as other readers have mentioned.
Have a look at: https://developers.google.com/accounts/docs/OAuth2UserAgent#handlingtheresponse
It says:
Other parameters included in the response include
expires_in
andtoken_type
. These parameters describe the lifetime of the token in seconds...
I was all in favour of throwing IllegalArgumentException
for null parameters, until today, when I noticed the java.util.Objects.requireNonNull
method in Java 7. With that method, instead of doing:
if (param == null) {
throw new IllegalArgumentException("param cannot be null.");
}
you can do:
Objects.requireNonNull(param);
and it will throw a NullPointerException
if the parameter you pass it is null
.
Given that that method is right bang in the middle of java.util
I take its existence to be a pretty strong indication that throwing NullPointerException
is "the Java way of doing things".
I think I'm decided at any rate.
Note that the arguments about hard debugging are bogus because you can of course provide a message to NullPointerException
saying what was null and why it shouldn't be null. Just like with IllegalArgumentException
.
One added advantage of NullPointerException
is that, in highly performance critical code, you could dispense with an explicit check for null (and a NullPointerException
with a friendly error message), and just rely on the NullPointerException
you'll get automatically when you call a method on the null parameter. Provided you call a method quickly (i.e. fail fast), then you have essentially the same effect, just not quite as user friendly for the developer. Most times it's probably better to check explicitly and throw with a useful message to indicate which parameter was null, but it's nice to have the option of changing that if performance dictates without breaking the published contract of the method/constructor.
Would appreciate any thoughts on the situation with 3 data sets. Say a logistic regression model is fitted yielding the following accuracy (Gini): Train: 70%; Test 58% and Out-of-time validation: 66%.
Actually all the possible combinations of predictors bring the same results with quite a huge drop between train and test data sets. The sample size is around 8k divided into train and test 70/30. OOT sample contains a few thousands of cases. Regularization, ensembles didn't help in solving this.
I doubt whether this is something I should concern if OOT performance is acceptable and close to train sample performance?
The motivation is to write code that doesn't depend explicitly on Spring. That way, if you choose to switch containers, you don't have to rewrite any code.
Think of the container as something is invisible to your code, magically providing for its needs, without being asked.
Dependency injection is a counterpoint to the "service locator" pattern. If you are going to lookup dependencies by name, you might as well get rid of the DI container and use something like JNDI.
Prefix is the prefix for url routing. If it's equals to '/' it means it will have no prefix. Then you defined a route with pattern "it should start with /hello".
To create a route for '/' you need to add these lines in your src/Shop/MyShopBundle/Resources/config/routing.yml :
ShopMyShopBundle_homepage:
pattern: /
defaults: { _controller: ShopMyShopBundle:Main:index }
This might solve your problem.
after doing changes you can commit it and then
git remote add origin https://(address of your repo) it can be https or ssh
then
git push -u origin master
hope it works for you.
thanks
When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:
%PATH%
environment variable for the executable file.If the file isn't found in either of those options you will need to either:
%PATH%
by apending it, (recommended only with extreme caution).You can see which locations are specified in %PATH%
from the Command prompt, Echo %Path%
.
Because of your reported error we can assume that Mobile.exe
is not in the current directory or in a location specified within the %Path%
variable, so you need to use 1.
, 2.
or 3.
.
Examples for 1.
C:\directory_path_without_spaces\My-App\Mobile.exe
or:
"C:\directory path with spaces\My-App\Mobile.exe"
Alternatively you may try:
Start C:\directory_path_without_spaces\My-App\Mobile.exe
or
Start "" "C:\directory path with spaces\My-App\Mobile.exe"
Where ""
is an empty title, (you can optionally add a string between those doublequotes).
Examples for 2.
CD /D C:\directory_path_without_spaces\My-App
Mobile.exe
or
CD /D "C:\directory path with spaces\My-App"
Mobile.exe
You could also use the /D
option with Start
to change the working directory for the executable to be run by the start command
Start /D C:\directory_path_without_spaces\My-App Mobile.exe
or
Start "" /D "C:\directory path with spaces\My-App" Mobile.exe
This worked for me to add an array within an array
this.setState(prevState => ({
component: prevState.component.concat(new Array(['new', 'new']))
}));
IF all this dont work, your .htaccess is correct, and permalinks trick didnt work, you may have not enabled your apache2 rewite mod.
I ran this and my issue was solved:
sudo a2enmod rewrite
If using async & await and desire to use a time out without blocking, then an alternative and simpler approach from the answer provide by mcandal is to execute the connect on a background thread and await the result. For example:
Task<bool> t = Task.Run(() => client.ConnectAsync(ipAddr, port).Wait(1000));
await t;
if (!t.Result)
{
Console.WriteLine("Connect timed out");
return; // Set/return an error code or throw here.
}
// Successful Connection - if we get to here.
See the Task.Wait MSDN article for more info and other examples.
Also, you may want to try Data::Dumper. Example:
use Data::Dumper;
# simple procedural interface
print Dumper($foo, $bar);
If you want to check for local files first do:
@font-face {
font-family: 'Green Sans Web';
src:
local('Green Web'),
local('GreenWeb-Regular'),
url('GreenWeb.ttf');
}
There is a more elaborate description of what to do here.
A stub is a controllable replacement for an Existing Dependency (or collaborator) in the system. By using a stub, you can test your code without dealing with the dependency directly.
External Dependency - Existing Dependency:
It is an object in your system that your code
under test interacts with and over which you have no control. (Common
examples are filesystems, threads, memory, time, and so on.)
Forexample in below code:
public void Analyze(string filename)
{
if(filename.Length<8)
{
try
{
errorService.LogError("long file entered named:" + filename);
}
catch (Exception e)
{
mailService.SendEMail("[email protected]", "ErrorOnWebService", "someerror");
}
}
}
You want to test mailService.SendEMail() method, but to do that you need to simulate an Exception in your test method, so you just need to create a Fake Stub errorService object to simulate the result you want, then your test code will be able to test mailService.SendEMail() method. As you see you need to simulate a result which is from an another Dependency which is ErrorService class object (Existing Dependency object).
Go to "Manage Jenkins" > "Script Console"
Run below:
def jobName = "build_name"
def job = Jenkins.instance.getItem(jobName)
job.getBuilds().each { it.delete() }
job.save()
just do len(MyList)
This also works for strings
, tuples
, dict
objects.
Open the project path in terminal and enter the below commands in terminal
1) find . | xargs -0 xattr -c
2) xattr -rc .
This works for me.
First execute composer clearcache
Then clear your vendors folder
rm -rf vendor/*
or better yet just remove the specific module which makes problems to avoid having to download all over again.
The normal layout for a maven multi module project is:
parent
+-- pom.xml
+-- module
+-- pom.xml
Check that you use this layout.
Additionally:
the relativePath
looks strange. Instead of '..'
<relativePath>..</relativePath>
try '../' instead:
<relativePath>../</relativePath>
You can also remove relativePath
if you use the standard layout. This is what I always do, and on the command line I can build as well the parent (and all modules) or only a single module.
The module path may be wrong. In the parent you define the module as:
<module>junitcategorizer.cutdetection</module>
You must specify the name of the folder of the child module, not an artifact identifier. If junitcategorizer.cutdetection
is not the name of the folder than change it accordingly.
Hope that helps..
EDIT have a look at the other post, I answered there.
Here is the python snippet you need to upload one large single file as multipart formdata. With NodeJs Multer middleware running on the server side.
import requests
latest_file = 'path/to/file'
url = "http://httpbin.org/apiToUpload"
files = {'fieldName': open(latest_file, 'rb')}
r = requests.put(url, files=files)
For the server side please check the multer documentation at: https://github.com/expressjs/multer here the field single('fieldName') is used to accept one single file, as in:
var upload = multer().single('fieldName');
In Spring you can escape the html from JSP pages generated by <form>
tags. This closes off a lot avenues for XSS attacks, and can be done automatically in three ways:
For the entire application in the web.xml
file:
<context-param>
<param-name>defaultHtmlEscape</param-name>
<param-value>true</param-value>
</context-param>
For all forms on a given page in the file itself:
<spring:htmlEscape defaultHtmlEscape="true" />
For each form:
<form:input path="someFormField" htmlEscape="true" />
It can also be written this way
this.props.history.push(`${window.location.pathname}&page=${pageNumber}`)
This method is even easier if you're ok with fewer options:
FileCopy source, destination
Here is one trick:
public static int getItself(int itself, int dummy)
{
return itself;
}
public static void main(String[] args)
{
int a = 10;
int b = 20;
a = getItself(b, b = a);
}
One more possible solution...
$last_element = array_reverse( $array )[0];
This may not be the most popular or efficient method, but I tend to forgo strong datatypes in SQLite since they are all essentially dumped in as strings anyway.
I've written a thin C# wrapper around the SQLite library before (when using SQLite with C#, of course) to handle insertions and extractions to and from SQLite as if I were dealing with DateTime objects.
move it out, commit, then move it back in. This has worked for me in the past. There is probably a 'gittier' way to accomplish this.
Save function:
$shopOwner->save()
already do what you want...
Laravel code:
// If the model already exists in the database we can just update our record
// that is already in this database using the current IDs in this "where"
// clause to only update this model. Otherwise, we'll just insert them.
if ($this->exists)
{
$saved = $this->performUpdate($query);
}
// If the model is brand new, we'll insert it into our database and set the
// ID attribute on the model to the value of the newly inserted row's ID
// which is typically an auto-increment value managed by the database.
else
{
$saved = $this->performInsert($query);
}
Please change your code as follows:
<script>
var button = document.getElementById("reactionTester");
var start = document.getElementById("start");
function init() {
var startInterval/*in milliseconds*/ = Math.floor(Math.random()*30)*1000;
setTimeout(startTimer,startInterval);
}
function startTimer(){
document.write("hey");
}
</script>
See if that helps. Basically, the difference is references the 'startTimer' function instead of executing it.
dir /b *.jpg >file.bat
This will give you lines such as:
Vacation2010 001.jpg
Vacation2010 002.jpg
Vacation2010 003.jpg
Edit file.bat in your favorite Windows text-editor, doing the equivalent of:
s/Vacation2010(.+)/rename "&" "December \1"/
That's a regex; many editors support them, but none that come default with Windows (as far as I know). You can also get a command line tool such as sed or perl which can take the exact syntax I have above, after escaping for the command line.
The resulting lines will look like:
rename "Vacation2010 001.jpg" "December 001.jpg"
rename "Vacation2010 002.jpg" "December 002.jpg"
rename "Vacation2010 003.jpg" "December 003.jpg"
You may recognize these lines as rename commands, one per file from the original listing. ;) Run that batch file in cmd.exe.
There are programs that try to detect the encoding of an file like chardet. Then you could convert it to a different encoding using iconv. But that requires that the original text is still intact and no information is lost (for example by removing accents or whole accented letters).
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/temp"
/>
In Ghost4J library (http://ghost4j.sourceforge.net), since version 0.4.0 you can use a SimpleRenderer to do the job with few lines of code:
Load PDF or PS file (use PSDocument class for that):
PDFDocument document = new PDFDocument();
document.load(new File("input.pdf"));
Create the renderer
SimpleRenderer renderer = new SimpleRenderer();
// set resolution (in DPI)
renderer.setResolution(300);
Render
List<Image> images = renderer.render(document);
Then you can do what you want with your image objects, for example, you can write them as PNG like this:
for (int i = 0; i < images.size(); i++) {
ImageIO.write((RenderedImage) images.get(i), "png", new File((i + 1) + ".png"));
}
Note: Ghost4J uses the native Ghostscript C API so you need to have a Ghostscript installed on your box.
I hope it will help you :)
HTML are markup languages, basically they are set of tags like <html>
, <body>
, which is used to present a website using css, and javascript as a whole. All these, happen in the clients system or the user you will be browsing the website.
Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.
So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like php, jsp, asp.net etc.
Now, lets see a snippet of connection using MYSQLi Extension of PHP
$db = mysqli_connect('hostname','username','password','databasename');
This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:
<?php
$db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
<body>
<?php
$query = "SELECT * FROM `mytable`;";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
// Display your datas on the page
}
?>
</body>
</html>
In order to insert new data into the database, you can use phpMyAdmin
or write a INSERT
query and execute them.
There are some misconceptions here.
Frequencies above 500 can be represented in an FFT result of length 1000. Unfortunately these frequencies are all folded together and mixed into the first 500 FFT result bins. So normally you don't want to feed an FFT a signal containing any frequencies at or above half the sampling rate, as the FFT won't care and will just mix the high frequencies together with the low ones (aliasing) making the result pretty much useless. That's why data should be low-pass filtered before being sampled and fed to an FFT.
The FFT returns amplitudes without frequencies because the frequencies depend, not just on the length of the FFT, but also on the sample rate of the data, which isn't part of the FFT itself or it's input. You can feed the same length FFT data at any sample rate, as thus get any range of frequencies out of it.
The reason the result plots ends at 500 is that, for any real data input, the frequencies above half the length of the FFT are just mirrored repeats (complex conjugated) of the data in the first half. Since they are duplicates, most people just ignore them. Why plot duplicates? The FFT calculates the other half of the result for people who feed the FFT complex data (with both real and imaginary components), which does create two different halves.
To terminate a process you know the name of, try:
taskkill /IM notepad.exe
This will ask it to close, but it may refuse, offer to "save changes", etc. If you want to forcibly kill it, try:
taskkill /F /IM notepad.exe
If you want a generic error you can setup all $.ajax()
(which $.get()
uses underneath) requests jQuery makes to display an error using $.ajaxSetup()
, for example:
$.ajaxSetup({
error: function(xhr, status, error) {
alert("An AJAX error occured: " + status + "\nError: " + error);
}
});
Just run this once before making any AJAX calls (no changes to your current code, just stick this before somewhere). This sets the error
option to default to the handler/function above, if you made a full $.ajax()
call and specified the error
handler then what you had would override the above.
For this purpose I would suggest just do the following thing -
int(round(x))
This will give you nearest integer.
Hope this helps!!
Like it always is, after having looked for a long time before writing something to the site, just a minute after I posted here I found my solution.
It thought I'd share it here so someone else can find it.
//Add "parent" class to pages with subpages, change submenu class name, add depth class
class Prio_Walker extends Walker_Nav_Menu {
function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ){
$GLOBALS['dd_children'] = ( isset($children_elements[$element->ID]) )? 1:0;
$GLOBALS['dd_depth'] = (int) $depth;
parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
}
function start_lvl(&$output, $depth) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<ul class=\"children level-".$depth."\">\n";
}
}
add_filter('nav_menu_css_class','add_parent_css',10,2);
function add_parent_css($classes, $item){
global $dd_depth, $dd_children;
$classes[] = 'depth'.$dd_depth;
if($dd_children)
$classes[] = 'parent';
return $classes;
}
//Add class to parent pages to show they have subpages (only for automatic wp_nav_menu)
function add_parent_class( $css_class, $page, $depth, $args )
{
if ( ! empty( $args['has_children'] ) )
$css_class[] = 'parent';
return $css_class;
}
add_filter( 'page_css_class', 'add_parent_class', 10, 4 );
This is where I found the solution: Solution in WordPress support forum
Example 2 on w3schools shows what you are trying to achieve.
<?php header("Content-type:application/pdf"); // It will be called downloaded.pdf header("Content-Disposition:attachment;filename='downloaded.pdf'"); // The PDF source is in original.pdf readfile("original.pdf"); ?>
Also remember that,
It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later, you can use output buffering to solve this problem)
The simplest, and best long-term solution, is to use BuildConfig.DEBUG
. This is a boolean
value that will be true
for a debug build, false
otherwise:
if (BuildConfig.DEBUG) {
// do something for a debug build
}
There have been reports that this value is not 100% reliable from Eclipse-based builds, though I personally have not encountered a problem, so I cannot say how much of an issue it really is.
If you are using Android Studio, or if you are using Gradle from the command line, you can add your own stuff to BuildConfig
or otherwise tweak the debug
and release
build types to help distinguish these situations at runtime.
The solution from Illegal Argument is based on the value of the android:debuggable
flag in the manifest. If that is how you wish to distinguish a "debug" build from a "release" build, then by definition, that's the best solution. However, bear in mind that going forward, the debuggable
flag is really an independent concept from what Gradle/Android Studio consider a "debug" build to be. Any build type can elect to set the debuggable
flag to whatever value that makes sense for that developer and for that build type.
Simple solution is to run this query:
mysql -h yourhostname -u username -p databasename < yoursqlfile.sql
And if you want to import with progress bar, try this:
pv yoursqlfile.sql | mysql -uxxx -pxxxx databasename
You have the line
dots = document.getElementById("txt").value;
in your file, this will set dots to be a string because the contents of txt is not restricted to a number.
to convert it to an int change the line to:
dots = parseInt(document.getElementById("txt").value, 10);
Note: The 10
here specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt
.
tl;dr
"Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.
Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).
Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.
Also, it seems likely the military FUBAR contributed to their popularity.
The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)
OK, so let's find some references.
STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:
On Foo-ism
The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")
As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.
It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!
The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:
By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.
...
It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.
Hopefully yours,
Indignant Mother of Five.
And The Tech in December 1938:
General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."
The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:
FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.
These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:
Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.
And from 1996's Jargon File 4.0.0:
Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."
A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):
Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!
Also 1964's MIT Voo Doo (PDF) references the TMRC usage:
Yes! I want to be an instant success and snow customers. Send me a degree in: ...
Foo Counters
Foo Jung
Let's find "foo", "bar" and "foobar" published in code examples.
So, Jargon File 4.4.7 says of "foobar":
Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.
The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:
Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.
Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z
I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:
car[((FOO . CROCK) . GLITCH)]
It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER
For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:
EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).
Some more recallations.
@Walter Mitty recalled on this site in 2008:
I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.
John V. Everett recalls in 1996:
When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.
Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.
It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.
Daniel P. B. Smith in 1998:
Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.
Robert Schuldenfrei in 1996:
The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?
Paul M. Wexelblat in 1992:
The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.
Bruce B. Reynolds in 1996:
On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...
Here's a straight IBM "BAR" from 1955.
Other early references:
1973 foo bar International Joint Council on Artificial Intelligence
1975 foo bar International Joint Council on Artificial Intelligence
I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.
Here are a some of even earlier F00s but I think they're coincidences/false positives:
echo -ne '\n' | <yourfinecommandhere>
or taking advantage of the implicit newline that echo generates (thanks Marcin)
echo | <yourfinecommandhere>
Now we can simply use the --sk
option:
--sk
,--skip-keypress
Don't wait for a keypress after each test
i.e. sudo rkhunter --sk --checkall
The ');
ends the query, it doesn't start a comment. Then it drops the students table and comments the rest of the query that was supposed to be executed.
The visible width of an element is width + padding + border + outline
, so it seems that you are forgetting about the border on the input element. That is, to say, that the default border width for an input element on most (some?) browsers is actually calculated as 2px, not one. Hence your input is appearing as 2px wider. Try explicitly setting the border-width
on the input, or making your div wider.
You can access the Axes instance (ax
) with plt.gca()
. In this case, you can use
plt.gca().legend()
You can do this either by using the label=
keyword in each of your plt.plot()
calls or by assigning your labels as a tuple or list within legend
, as in this working example:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.75,1,100)
y0 = np.exp(2 + 3*x - 7*x**3)
y1 = 7-4*np.sin(4*x)
plt.plot(x,y0,x,y1)
plt.gca().legend(('y0','y1'))
plt.show()
However, if you need to access the Axes instance more that once, I do recommend saving it to the variable ax
with
ax = plt.gca()
and then calling ax
instead of plt.gca()
.
May be this will help, I'd prefer pure JS wherever possible, it improves the performance drastically as you won't have lots of JQuery function calls.
var obj = [];
var elems = $("input[class=email]");
for (i = 0; i < elems.length; i += 1) {
var id = this.getAttribute('title');
var email = this.value;
tmp = {
'title': id,
'email': email
};
obj.push(tmp);
}
One work-around is to transition the background position to give the effect that the gradient is changing: http://sapphion.com/2011/10/css3-gradient-transition-with-background-position/
CSS3 gradient transition with background-position
Although you can’t directly animate gradients using the CSS transition property, it is possible to animate the background-position property to achieve a simple gradient animation:
The code for this is dead simple:
#DemoGradient{ _x000D_
background: -webkit-linear-gradient(#C7D3DC,#5B798E); _x000D_
background: -moz-linear-gradient(#C7D3DC,#5B798E); _x000D_
background: -o-linear-gradient(#C7D3DC,#5B798E); _x000D_
background: linear-gradient(#C7D3DC,#5B798E); _x000D_
_x000D_
-webkit-transition: background 1s ease-out; _x000D_
-moz-transition: background 1s ease-out; _x000D_
-o-transition: background 1s ease-out; _x000D_
transition: background 1s ease-out; _x000D_
_x000D_
background-size:1px 200px; _x000D_
border-radius: 10px; _x000D_
border: 1px solid #839DB0; _x000D_
cursor:pointer; _x000D_
width: 150px; _x000D_
height: 100px; _x000D_
} _x000D_
#DemoGradient:Hover{ _x000D_
background-position:100px; _x000D_
}
_x000D_
<div id="DemoGradient"></div>
_x000D_
The typical way is as follows:
enum Foo {
One,
Two,
Three,
Last
};
for ( int fooInt = One; fooInt != Last; fooInt++ )
{
Foo foo = static_cast<Foo>(fooInt);
// ...
}
Please note, the enum Last
is meant to be skipped by the iteration. Utilizing this "fake" Last
enum, you don't have to update your terminating condition in the for loop to the last "real" enum each time you want to add a new enum.
If you want to add more enums later, just add them before Last. The loop in this example will still work.
Of course, this breaks down if the enum values are specified:
enum Foo {
One = 1,
Two = 9,
Three = 4,
Last
};
This illustrates that an enum is not really meant to iterate through. The typical way to deal with an enum is to use it in a switch statement.
switch ( foo )
{
case One:
// ..
break;
case Two: // intentional fall-through
case Three:
// ..
break;
case Four:
// ..
break;
default:
assert( ! "Invalid Foo enum value" );
break;
}
If you really want to enumerate, stuff the enum values in a vector and iterate over that. This will properly deal with the specified enum values as well.
I am using Laravel 5.6 and the Notifications Facade.
If I set a variable with comma separating the e-mails and try to send it, I get the error: "Address in mail given does not comply with RFC 2822, 3.6.2"
So, to solve the problem, I got the solution idea from @Toskan, coding the following.
// Get data from Database
$contacts = Contacts::select('email')
->get();
// Create an array element
$contactList = [];
$i=0;
// Fill the array element
foreach($contacts as $contact){
$contactList[$i] = $contact->email;
$i++;
}
.
.
.
\Mail::send('emails.template', ['templateTitle'=>$templateTitle, 'templateMessage'=>$templateMessage, 'templateSalutation'=>$templateSalutation, 'templateCopyright'=>$templateCopyright], function($message) use($emailReply, $nameReply, $contactList) {
$message->from('[email protected]', 'Some Company Name')
->replyTo($emailReply, $nameReply)
->bcc($contactList, 'Contact List')
->subject("Subject title");
});
It worked for me to send to one or many recipients.
Use this jQuery extension by James Padoley
I think this way you can get the file from "anywhere" (including server locations) and you do not need to care about where to put it.
It's usually a bad practice having to care about such things.
Thread.currentThread().getContextClassLoader().getResourceAsStream("abc.properties");
left: initial
This will also set left
back to the browser default.
But important to know property: initial
is not supported in IE.
Above comments are both solid responses, however note that they aren't thread safe. If you are writing to the console with multiple threads, changing colors will add a race condition that can create some strange looking output. It is simple to fix though:
public class ConsoleWriter
{
private static object _MessageLock= new object();
public void WriteMessage(string message)
{
lock (_MessageLock)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine(message);
Console.ResetColor();
}
}
}
BOM is just a sequence of characters ($EF $BB $BF for UTF-8), so just remove them using scripts or configure the editor so it's not added.
From Removing BOM from UTF-8:
#!/usr/bin/perl
@file=<>;
$file[0] =~ s/^\xEF\xBB\xBF//;
print(@file);
I am sure it translates to PHP easily.
Updated Answer
Updating because I noticed it's an active answer, however Flexbox would be the correct approach now.
Vertical and horizontal alignment.
#wrapper {
display: flex;
align-items: center;
justify-content: center;
}
Just horizontal (as long as the main flex axis is horizontal which is default)
#wrapper {
display: flex;
justify-content: center;
}
Original Answer using a fixed width and no flexbox
If the original poster wants vertical and center alignment its quite easy for fixed width and height of the button, try the following
CSS
button{
height:20px;
width:100px;
margin: -20px -50px;
position:relative;
top:50%;
left:50%;
}
for just horizontal alignment use either
button{
margin: 0 auto;
}
or
div{
text-align:center;
}
After trying everything else here with no luck, what finally fixed this issue for me was removing the will-change: transform;
property. For some reason it caused horribly blurry looking scaling in Chrome, but not Firefox.
I think the question is a little bit fuzzy - for example, it can be interpreted as a question about best practices in programming loops with if
inside. So, I'll try to answer this question with this particular interpretation.
If you have if
inside a loop, then in most cases you'd like to know how the loop has ended - was it "broken" by the if
or was it ended "naturally"? So, your sample code can be modified in this way:
bool intMaxFound = false;
for (size = 0; size < HAY_MAX; size++)
{
// wait for hay until EOF
printf("\nhaystack[%d] = ", size);
int straw = GetInt();
if (straw == INT_MAX)
{intMaxFound = true; break;}
// add hay to stack
haystack[size] = straw;
}
if (intMaxFound)
{
// ... broken
}
else
{
// ... ended naturally
}
The problem with this code is that the if
statement is buried inside the loop body, and it takes some effort to locate it and understand what it does. A more clear (even without the break
statement) variant will be:
bool intMaxFound = false;
for (size = 0; size < HAY_MAX && !intMaxFound; size++)
{
// wait for hay until EOF
printf("\nhaystack[%d] = ", size);
int straw = GetInt();
if (straw == INT_MAX)
{intMaxFound = true; continue;}
// add hay to stack
haystack[size] = straw;
}
if (intMaxFound)
{
// ... broken
}
else
{
// ... ended naturally
}
In this case you can clearly see (just looking at the loop "header") that this loop can end prematurely. If the loop body is a multi-page text, written by somebody else, then you'd thank its author for saving your time.
UPDATE:
Thanks to SO - it has just suggested the already answered question about crash of the AT&T phone network in 1990. It's about a risky decision of C creators to use a single reserved word break
to exit from both loops and switch
.
Anyway this interpretation doesn't follow from the sample code in the original question, so I'm leaving my answer as it is.
@echo off
rem Get start time:
for /F "tokens=1-4 delims=:.," %%a in ("%time%") do (
set /A "start=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)
rem Any process here...
rem Get end time:
for /F "tokens=1-4 delims=:.," %%a in ("%time%") do (
set /A "end=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)
rem Get elapsed time:
set /A elapsed=end-start
rem Show elapsed time:
set /A hh=elapsed/(60*60*100), rest=elapsed%%(60*60*100), mm=rest/(60*100), rest%%=60*100, ss=rest/100, cc=rest%%100
if %mm% lss 10 set mm=0%mm%
if %ss% lss 10 set ss=0%ss%
if %cc% lss 10 set cc=0%cc%
echo %hh%:%mm%:%ss%,%cc%
EDIT 2017-05-09: Shorter method added
I developed a shorter method to get the same result, so I couldn't resist to post it here. The two for
commands used to separate time parts and the three if
commands used to insert leading zeros in the result are replaced by two long arithmetic expressions, that could even be combined into a single longer line.
The method consists in directly convert a variable with a time in "HH:MM:SS.CC" format into the formula needed to convert the time to centiseconds, accordingly to the mapping scheme given below:
HH : MM : SS . CC
(((10 HH %%100)*60+1 MM %%100)*60+1 SS %%100)*100+1 CC %%100
That is, insert (((10
at beginning, replace the colons by %%100)*60+1
, replace the point by %%100)*100+1
and insert %%100
at end; finally, evaluate the resulting string as an arithmetic expression. In the time variable there are two different substrings that needs to be replaced, so the conversion must be completed in two lines. To get an elapsed time, use (endTime)-(startTime)
expression and replace both time strings in the same line.
EDIT 2017/06/14: Locale independent adjustment added
EDIT 2020/06/05: Pass-over-midnight adjustment added
@echo off
setlocal EnableDelayedExpansion
set "startTime=%time: =0%"
set /P "=Any process here..."
set "endTime=%time: =0%"
rem Get elapsed time:
set "end=!endTime:%time:~8,1%=%%100)*100+1!" & set "start=!startTime:%time:~8,1%=%%100)*100+1!"
set /A "elap=((((10!end:%time:~2,1%=%%100)*60+1!%%100)-((((10!start:%time:~2,1%=%%100)*60+1!%%100), elap-=(elap>>31)*24*60*60*100"
rem Convert elapsed time to HH:MM:SS:CC format:
set /A "cc=elap%%100+100,elap/=100,ss=elap%%60+100,elap/=60,mm=elap%%60+100,hh=elap/60+100"
echo Start: %startTime%
echo End: %endTime%
echo Elapsed: %hh:~1%%time:~2,1%%mm:~1%%time:~2,1%%ss:~1%%time:~8,1%%cc:~1%
You may review a detailed explanation of this method at this answer.
You want this
document.body.insertAdjacentHTML( 'afterbegin', '<div id="myID">...</div>' );
Group Selector
body {font-size: 12px; }
body {font-family: arial, helvetica, sans-serif;}
th {font-size: 12px; font-family: arial, helvetica, sans-serif;}
td {font-size: 12px; font-family: arial, helvetica, sans-serif;}
Becomes this:
body, th, td {font-size: 12px; font-family: arial, helvetica, sans-serif;}
So in your case you have tried the group selector whereas its an intersection
$(".a, .b")
instead use this
$(".a.b")
Yes! you can do so without writing any Java/Kotlin code, only XML by using this small library I created, which does so at buildtime, so your app won't be affected by it: https://github.com/LikeTheSalad/android-string-reference
Usage
Your strings:
<resources>
<string name="app_name">My App Name</string>
<string name="template_welcome_message">Welcome to ${app_name}</string>
</resources>
The generated string after building:
<!--resolved.xml-->
<resources>
<string name="welcome_message">Welcome to My App Name</string>
</resources>
.shadow {
-moz-box-shadow: 3px 3px 5px 6px #ccc;
-webkit-box-shadow: 3px 3px 5px 6px #ccc;
box-shadow: 3px 3px 5px 6px #ccc;
}
if you're sure that your pom.xml is pretty good, then you have just to update the poject. right click on the project - Maven - update project. or simply alt+F5.
The below code in file "Locomotive.java" will compile and run successfully, with the execution results showing
2<SPACE>
As mentioned in above post, the overload rules still work for the main method. However, the entry point is the famous psvm (public static void main(String[] args))
public class Locomotive {
Locomotive() { main("hi");}
public static void main(String[] args) {
System.out.print("2 ");
}
public static void main(String args) {
System.out.print("3 " + args);
}
}
Since scripts are executed sequentially, the currently executed script tag is always the last script tag on the page until then. So, to get the script tag, you can do:
var scripts = document.getElementsByTagName( 'script' );
var thisScriptTag = scripts[ scripts.length - 1 ];
Try setting "Integrated Security=False" in the connection string.
<add name="YourContext" connectionString="Data Source=<IPAddressOfDBServer>;Initial Catalog=<DBName>;USER ID=<youruserid>;Password=<yourpassword>;Integrated Security=False;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>
As pointed out in a few other answers, you can iterate over all elements in a matrix A
(of any dimension) using a linear index from 1
to numel(A)
in a single for loop. There are also a couple of functions you can use: arrayfun
and cellfun
.
Let's first assume you have a function that you want to apply to each element of A
(called my_func
). You first create a function handle to this function:
fcn = @my_func;
If A
is a matrix (of type double, single, etc.) of arbitrary dimension, you can use arrayfun
to apply my_func
to each element:
outArgs = arrayfun(fcn, A);
If A
is a cell array of arbitrary dimension, you can use cellfun
to apply my_func
to each cell:
outArgs = cellfun(fcn, A);
The function my_func
has to accept A
as an input. If there are any outputs from my_func
, these are placed in outArgs
, which will be the same size/dimension as A
.
One caveat on outputs... if my_func
returns outputs of different sizes and types when it operates on different elements of A
, then outArgs
will have to be made into a cell array. This is done by calling either arrayfun
or cellfun
with an additional parameter/value pair:
outArgs = arrayfun(fcn, A, 'UniformOutput', false);
outArgs = cellfun(fcn, A, 'UniformOutput', false);
So let's fully understand, Let's say you have a query which works in localhost but does not in production mode, This is because in MySQL 5.7 and above
they decided to activate the sql_mode=only_full_group_by
by default, basically it is a strict mode which prevents you to select non aggregated fields.
Here's the query (works in local but not in production mode) :
SELECT post.*, YEAR(created_at) as year
FROM post
GROUP BY year
SELECT post.id, YEAR(created_at) as year // This will generate an error since there are many ids
FROM post
GROUP BY year
To verify if the sql_mode=only_full_group_by
is activated for, you should execute the following query :
SELECT @@sql_mode; //localhost
Output : IGNORE_SPACE, STRICT_TRANS, ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
(If you don't see it, it means it is deactivated)
But if try in production mode, or somewhere where it gives you the error it should be activated:
SELECT @@sql_mode; //production
Output: ONLY_FULL_GROUP_BY, STRICT_TRANS_TABLES, NO_ZERO_IN_DATE, NO_ZERO...
And it's ONLY_FULL_GROUP_BY
we're looking for here.
Otherwise, if you are using phpMyAdmin then go to -> Variables
and search for sql_mode
Let's take our previous example and adapt it to it :
SELECT MIN(post.id), YEAR(created_at) as year //Here we are solving the problem with MIN()
FROM post
GROUP BY year
And the same for MAX()
And if we want all the IDs, we're going to need:
SELECT GROUP_CONCAT(post.id SEPARATOR ','), YEAR(created_at) as year
FROM post
GROUP BY year
or another newly added function:
SELECT ANY_VALUE(post.id), YEAR(created_at) as year
FROM post
GROUP BY year
?? ANY_VALUE does not exist for MariaDB
And If you want all the fields, then you could use the same:
SELECT ANY_VALUE(post.id), ANY_VALUE(post.slug), ANY_VALUE(post.content) YEAR(created_at) as year
FROM post
GROUP BY year
? To deactivate the sql_mode=only_full_group_by
then you'll need to execute this query:
SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', ''));
Sorry for the novel, hope it helps.
I was getting this error though there were no (obvious) brackets in my URL, and in my situation the --globoff command will not solve the issue.
For example (doing this on on mac in iTerm2):
for endpoint in $(grep some_string output.txt); do curl "http://1.2.3.4/api/v1/${endpoint}" ; done
I have grep aliased to "grep --color=always". As a result, the above command will result in this error, with some_string highlighted in whatever colour you have grep set to:
curl: (3) bad range in URL position 31:
http://1.2.3.4/api/v1/lalalasome_stringlalala
The terminal was transparently translating the [colour\codes]some_string[colour\codes] into the expected no-special-characters URL when viewed in terminal, but behind the scenes the colour codes were being sent in the URL passed to curl, resulting in brackets in your URL.
Solution is to not use match highlighting.
Strings are immutable objects so you can copy them just coping the reference to them, because the object referenced can't change ...
So you can copy as in your first example without any problem :
String s = "hello";
String backup_of_s = s;
s = "bye";
@AlexanderSavin's solution works great in WebKit
browsers for me.
I additionally had to use :target pseudo-class which applies style to the selected anchor to adjust padding in FF
, Opera
& IE9
:
a:target {
padding-top: 40px
}
Note that this style is not for Chrome
/ Safari
so you'll probably have to use css-hacks, conditional comments etc.
Also I'd like to notice that Alexander's solution works due to the fact that targeted element is inline
. If you don't want link you could simply change display
property:
<div id="myanchor" style="display: inline">
<h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</div>
You may want to look at Tibbo VSPDL for creating a linux virtual serial port using a Kernel driver -- it seems pretty new, and is available for download right now (beta version). Not sure about the license at this point, or whether they want to make it available commercially only in the future.
There are other commercial alternatives, such as http://www.ttyredirector.com/.
In Open Source, Remserial (GPL) may also do what you want, using Unix PTY's. It transmits the serial data in "raw form" to a network socket; STTY-like setup of terminal parameters must be done when creating the port, changing them later like described in RFC 2217 does not seem to be supported. You should be able to run two remserial instances to create a virtual nullmodem like com0com, except that you'll need to set up port speed etc in advance.
Socat (also GPL) is like an extended variant of Remserial with many many more options, including a "PTY" method for redirecting the PTY to something else, which can be another instance of Socat. For Unit tets, socat is likely nicer than remserial because you can directly cat files into the PTY. See the PTY example on the manpage. A patch exists under "contrib" to provide RFC2217 support for negotiating serial line settings.
This is the most simple example I can think of in this case and is not tested. Please consider that this uses some bad practices and does not go the way you normally would go with C++ (initialize lists, separation of declaration and definition, and so on). But that are topics I can't cover here.
#include <iostream>
using namespace std;
class LinkedList{
// Struct inside the class LinkedList
// This is one node which is not needed by the caller. It is just
// for internal work.
struct Node {
int x;
Node *next;
};
// public member
public:
// constructor
LinkedList(){
head = NULL; // set head to NULL
}
// destructor
~LinkedList(){
Node *next = head;
while(next) { // iterate over all elements
Node *deleteMe = next;
next = next->next; // save pointer to the next element
delete deleteMe; // delete the current entry
}
}
// This prepends a new value at the beginning of the list
void addValue(int val){
Node *n = new Node(); // create new Node
n->x = val; // set value
n->next = head; // make the node point to the next node.
// If the list is empty, this is NULL, so the end of the list --> OK
head = n; // last but not least, make the head point at the new node.
}
// returns the first element in the list and deletes the Node.
// caution, no error-checking here!
int popValue(){
Node *n = head;
int ret = n->x;
head = head->next;
delete n;
return ret;
}
// private member
private:
Node *head; // this is the private member variable. It is just a pointer to the first Node
};
int main() {
LinkedList list;
list.addValue(5);
list.addValue(10);
list.addValue(20);
cout << list.popValue() << endl;
cout << list.popValue() << endl;
cout << list.popValue() << endl;
// because there is no error checking in popValue(), the following
// is undefined behavior. Probably the program will crash, because
// there are no more values in the list.
// cout << list.popValue() << endl;
return 0;
}
I would strongly suggest you to read a little bit about C++ and Object oriented programming. A good starting point could be this: http://www.galileocomputing.de/1278?GPP=opoo
EDIT: added a pop function and some output. As you can see the program pushes 3 values 5, 10, 20 and afterwards pops them. The order is reversed afterwards because this list works in stack mode (LIFO, Last in First out)
Yes, I got the answer.. just simply edit the manifest
file as:
<activity android:name=".MainActivity"
android:label="@string/app_name"
android:windowSoftInputMode="stateAlwaysVisible" />
and set EditText.requestFocus()
in onCreate()
..
Thanks..
I think there is an error in the trigger code. As you want to delete all rows with the deleted patron ID, you have to use old.id (Otherwise it would delete other IDs)
Try this as the new trigger:
CREATE TRIGGER log_patron_delete AFTER DELETE on patrons
FOR EACH ROW
BEGIN
DELETE FROM patron_info
WHERE patron_info.pid = old.id;
END
Dont forget the ";" on the delete query. Also if you are entering the TRIGGER code in the console window, make use of the delimiters also.
This is the only one right answer on this whole page as people answered about "Visual Studio", not "Visual Studio Code":
To change color theme in "Visual Studio Code", use:
File -> Preferences -> Color Theme -> select any color theme you like
You can also download other custom themes as extensions. To do that, open extensions tab on sidebar and type "theme" into the search field to filter extensions only to themes related ones. Click any you like, click "download" and then "install". After installation and restarting VSC, you can find newly installed themes next to default themes in the same place:
File -> Preferences -> Color Theme -> select newly downloaded color theme
PS - Microsoft made bad naming decision by calling this new editor Visual Studio Code, it's terrible how many wrong links we have in google and stackoverflow. They should rename it to VSCode or something.
Thanks, i just need to use:
SETLOCAL EnableExtensions
And put a:
2^>nul
Into the REG QUERY called in the FOR command. Thanks a lot again! :)
This is a known issue with Chrome.
Here's the link in the bug tracker:
Here's an example of strtok
usage, keep in mind that strtok
is destructive of its input string (and therefore can't ever be used on a string constant
char *p = strtok(str, " ");
while(p != NULL) {
printf("%s\n", p);
p = strtok(NULL, " ");
}
Basically the thing to note is that passing a NULL
as the first parameter to strtok
tells it to get the next token from the string it was previously tokenizing.
Include the script from dhtmlgoodies and initialize like this:
<input type="text" name="myText" value="Norway"
selectBoxOptions="Canada;Denmark;Finland;Germany;Mexico">
createEditableSelect(document.forms[0].myText);
Here's a custom solution which combines a <select>
element and <input>
element, styles them, and toggles back and forth via JavaScript
<div style="position:relative;width:200px;height:25px;border:0;padding:0;margin:0;">
<select style="position:absolute;top:0px;left:0px;width:200px; height:25px;line-height:20px;margin:0;padding:0;"
onchange="document.getElementById('displayValue').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;">
<option></option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
<input type="text" name="displayValue" id="displayValue"
placeholder="add/select a value" onfocus="this.select()"
style="position:absolute;top:0px;left:0px;width:183px;width:180px\9;#width:180px;height:23px; height:21px\9;#height:18px;border:1px solid #556;" >
<input name="idValue" id="idValue" type="hidden">
</div>
So what does count_votes look like? Is it a script? Anything that you want to get back from an ajax call can be retrieved using a simple echo (of course you could use JSON or xml, but for this simple example you would just need to output something in count_votes.php like:
$id = $_POST['id'];
function getVotes($id){
// call your database here
$query = ("SELECT votes FROM poll WHERE ID = $id");
$result = @mysql_query($query);
$row = mysql_fetch_row($result);
return $row->votes;
}
$votes = getVotes($id);
echo $votes;
This is just pseudocode, but should give you the idea. What ever you echo from count_votes will be what is returned to "data" in your ajax call.
GET (multiple parameters):
curl -X GET "http://localhost:3000/action?result1=gh&result2=ghk"
or
curl --request GET "http://localhost:3000/action?result1=gh&result2=ghk"
or
curl "http://localhost:3000/action?result1=gh&result2=ghk"
or
curl -i -H "Application/json" -H "Content-type: application/json" "http://localhost:3000/action?result1=gh&result2=ghk"
Some IDEs highlight the code in heredoc strings automatically - which makes using heredoc for XML or HTML visually appealing.
I personally like it for longer parts of i.e. XML since I don't have to care about quoting quote characters and can simply paste the XML.
The Charset used in the POST will match that of the Charset specified in the HTML hosting the form. Hence if your form is sent using UTF-8 encoding that is the encoding used for the posted content. The URL encoding is applied after the values are converted to the set of octets for the character encoding.
Sometimes just setting canvas's tabindex to '1' (or '0') works. But sometimes - it doesn't, for some strange reason.
In my case (ReactJS app, dynamic canvas el creation and mount) I need to call canvasEl.focus() to fix it. Maybe this is somehow related to React (my old app based on KnockoutJS works without '..focus()' )
Web APi 2 and later versions support a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API. For example, you can easily create URIs that describe hierarchies of resources.
For example:
[Route("customers/{customerId}/orders")]
public IEnumerable<Order> GetOrdersByCustomer(int customerId) { ... }
Will perfect and you don't need any extra code for example in WebApiConfig.cs. Just you have to be sure web api routing is enabled or not in WebApiConfig.cs , if not you can activate like below:
// Web API routes
config.MapHttpAttributeRoutes();
You don't have to do something more or change something in WebApiConfig.cs. For more details you can have a look this article.
You can do it by solving the line equation for that line segment with the point coordinates you will know whether that point is on the line and then checking the bounds of the segment to know whether it is inside or outside of it. You can apply some threshold because well it is somewhere in space mostl likely defined by a floating point value and you must not hit the exact one. Example in php
function getLineDefinition($p1=array(0,0), $p2=array(0,0)){
$k = ($p1[1]-$p2[1])/($p1[0]-$p2[0]);
$q = $p1[1]-$k*$p1[0];
return array($k, $q);
}
function isPointOnLineSegment($line=array(array(0,0),array(0,0)), $pt=array(0,0)){
// GET THE LINE DEFINITION y = k.x + q AS array(k, q)
$def = getLineDefinition($line[0], $line[1]);
// use the line definition to find y for the x of your point
$y = $def[0]*$pt[0]+$def[1];
$yMin = min($line[0][1], $line[1][1]);
$yMax = max($line[0][1], $line[1][1]);
// exclude y values that are outside this segments bounds
if($y>$yMax || $y<$yMin) return false;
// calculate the difference of your points y value from the reference value calculated from lines definition
// in ideal cases this would equal 0 but we are dealing with floating point values so we need some threshold value not to lose results
// this is up to you to fine tune
$diff = abs($pt[1]-$y);
$thr = 0.000001;
return $diff<=$thr;
}
Swift 4
func writeImage(image: UIImage) {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.finishWriteImage), nil)
}
@objc private func finishWriteImage(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
if (error != nil) {
// Something wrong happened.
print("error occurred: \(String(describing: error))")
} else {
// Everything is alright.
print("saved success!")
}
}
Note:put this code in your javascript at the point you want the beep to occur. and remember to specify the directory or folder where the beep sound is stored(source).
<script>
//Appending HTML5 Audio Tag in HTML Body
$('<audio id="chatAudio"><source src="sound/notify.ogg" type="audio/ogg"><source src="sound/notify.mp3" type="audio/mpeg"><source src="sound/notify.wav" type="audio/wav"></audio>').appendTo('body');
$('#chatAudio')[0].play();
</script>
Reference:http://www.9lessons.info/2013/04/play-notification-sound-using-jquery.html.
I implemented this in a social media i am developing and it works find, a notification like that of facebook when chatting, notifying you that you have a new chat message
I had this issue too because I was filtering /src/main/resources and forgot I had added a keystore (*.jks) binary to this directory.
Add a "resource" block with exclusions for binary files and your problem may be resolved.
<build>
<finalName>somename</finalName>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>false</filtering>
</testResource>
</testResources>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>*.jks</exclude>
<exclude>*.png</exclude>
</excludes>
</resource>
</resources>
...
Always make sure that js file (angular.min.js) is referenced first in the HTML file. For example:
----------------- This reference will THROW error -------------------------
< script src="otherXYZ.js"></script>
< script src="angular.min.js"></script>
----------------- This reference will WORK as expected -------------------
< script src="angular.min.js"></script>
< script src="otherXYZ.js"></script>
Slightly off topic from the original question, but it builds off Antoine’s idea and I thought it might help someone.
You can also make computed properties optional for structs with protocol extensions.
You can make a property on the protocol optional
protocol SomeProtocol {
var required: String { get }
var optional: String? { get }
}
Implement the dummy computed property in the protocol extension
extension SomeProtocol {
var optional: String? { return nil }
}
And now you can use structs that do or don’t have the optional property implemented
struct ConformsWithoutOptional {
let required: String
}
struct ConformsWithOptional {
let required: String
let optional: String?
}
I’ve also written up how to do optional properties in Swift protocols on my blog, which I’ll keep updated in case things change through the Swift 2 releases.
First, Remember that this logfile can grow very large on a busy server.
For mysql < 5.1.29:
To enable the query log, put this in /etc/my.cnf
in the [mysqld]
section
log = /path/to/query.log #works for mysql < 5.1.29
Also, to enable it from MySQL console
SET general_log = 1;
See http://dev.mysql.com/doc/refman/5.1/en/query-log.html
For mysql 5.1.29+
With mysql 5.1.29+ , the log
option is deprecated. To specify the logfile and enable logging, use this in my.cnf in the [mysqld]
section:
general_log_file = /path/to/query.log
general_log = 1
Alternately, to turn on logging from MySQL console (must also specify log file location somehow, or find the default location):
SET global general_log = 1;
Also note that there are additional options to log only slow queries, or those which do not use indexes.
I think you can use typeahead.js
. There are typescript definitions for it. so it'll be easy to use it i guess if you are using typescript for development.
Your second way is correct.
def foo(opts: dict = {}):
pass
print(foo.__annotations__)
this outputs
{'opts': <class 'dict'>}
It's true that's it's not listed in PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section makes it clear that keyword arguments works with function annotations in this way.
I strongly advise against using mutable keyword arguments. More information here.
if you are removing all disabled attributes from input, then why not just do:
$("input").removeAttr('disabled');
Then after ajax success:
$("input[type='text']").attr('disabled', true);
Make sure you use remove the disabled attribute before submit, or it won't submit that data. If you need to submit it before changing, you need to use readonly instead.
Based on all the answers on this thread, I wrote the following code and it worked for me.
If you have only some input/textarea tags which requires an onunload event to be checked, you can assign HTML5 data-attributes as data-onunload="true"
for eg.
<input type="text" data-onunload="true" />
<textarea data-onunload="true"></textarea>
and the Javascript (jQuery) can look like this :
$(document).ready(function(){
window.onbeforeunload = function(e) {
var returnFlag = false;
$('textarea, input').each(function(){
if($(this).attr('data-onunload') == 'true' && $(this).val() != '')
returnFlag = true;
});
if(returnFlag)
return "Sure you want to leave?";
};
});
Leave you stuff there and Try the following as well:
Start > Right-click on My computer > Properties > Advanced system settings > Environment Variables > look for variable name called "Path" in the lower box
set path value value as: (you can just add it to the starting of line, don't forgot semi column in between )
c:\Program Files\java\jre7\bin
We're having a lot of race conditions with elementToBeClickable
. See https://github.com/angular/protractor/issues/2313. Something along these lines worked reasonably well even if a little brute force
Awaitility.await()
.atMost(timeout)
.ignoreException(NoSuchElementException.class)
.ignoreExceptionsMatching(
Matchers.allOf(
Matchers.instanceOf(WebDriverException.class),
Matchers.hasProperty(
"message",
Matchers.containsString("is not clickable at point")
)
)
).until(
() -> {
this.driver.findElement(locator).click();
return true;
},
Matchers.is(true)
);
Using pure JPA with Hibernate 5.0.2.Final as the actual provider the following seems to work with positional parameters as well:
Entity.java:
@Entity
@NamedQueries({
@NamedQuery(name = "byAttributes", query = "select e from Entity e where e.attribute in (?1)") })
public class Entity {
@Column(name = "attribute")
private String attribute;
}
Dao.java:
public class Dao {
public List<Entity> findByAttributes(Set<String> attributes) {
Query query = em.createNamedQuery("byAttributes");
query.setParameter(1, attributes);
List<Entity> entities = query.getResultList();
return entities;
}
}
Also $( "#container" ).find( "div.robotarm" );
is equal to: $( "div.robotarm", "#container" )