First things first, you have to install Maven on your workstation. You need also to install M2E, what you obviously did. Not all distributions of Juno have it pre-installed.
Then configure your Eclipse so it can find your Maven install. In the menu Window -> Preferences, then open the Maven section. In your right panel, you have a list of the Maven installations Eclipse knows. Add your installation and select it instead of the embedded Maven provided with M2E. Don't forget to set the "Global settings from installation directory" field with the path to the settings.xml of your Maven installation.
Which leads us to the settings.xml. If the above doesn't solve your problem, you will have to configure your Maven. More infos here.
Depending on your application (I wanted to generate passwords), you could use
$string = base64_encode(openssl_random_pseudo_bytes(30));
Being base64, they may contain =
or -
as well as the requested characters. You could generate a longer string, then filter and trim it to remove those.
openssl_random_pseudo_bytes
seems to be the recommended way way to generate a proper random number in php. Why rand
doesn't use /dev/random
I don't know.
You can also try using apply
with get
method of dictionary
, seems to be little faster than replace
:
data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)
Testing with timeit
:
%%timeit
data['sex'].replace([0,1],['Female','Male'],inplace=True)
Result:
The slowest run took 5.83 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 510 µs per loop
Using apply
:
%%timeit
data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)
Result:
The slowest run took 5.92 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 331 µs per loop
Note: apply
with dictionary should be used if all the possible values of the columns in the dataframe are defined in the dictionary else, it will have empty for those not defined in dictionary.
You have already found NSDateFormatter
, just read the documentation on it.
NSDateFormatter Class Reference
For format character definitions
See: ICU Formatting Dates and Times
Also: Date Field SymbolTable..
Yes there is:
std::vector<int> vec(SIZE, 0);
Use a vector instead of a dynamically allocated array. Benefits include not having to bother with explicitely deleting the array (it is deleted when the vector goes out of scope) and also that the memory is automatically deleted even if there is an exception thrown.
Edit: To avoid further drive-by downvotes from people that do not bother to read the comments below, I should make it more clear that this answer does not say that vector is always the right answer. But it sure is a more C++ way than "manually" making sure to delete an array.
Now with C++11, there is also std::array that models a constant size array (vs vector that is able to grow). There is also std::unique_ptr that manages a dynamically allocated array (that can be combined with initialization as answered in other answers to this question). Any of those are a more C++ way than manually handling the pointer to the array, IMHO.
The following worked for me:
$(':input').val('');
However, it is submitting the form, so it might not be what you are looking for.
Using Maria-DB and DB-Navigator tool inside IntelliJ, MODIFY Column worked for me instead of Alter Column
To synthesize the excellent original answers from @adardesign, @adswebwork and @AnkitVishwakarma, and comments from @Bdoserror, @Retsam, @seanf, and @torek, with additional documentation links and concise aliases...
Basic Commands
To reset a file that is assume-unchanged back to normal:
git update-index --no-assume-unchanged <file>
To list all files that are assume-unchanged:
git ls-files -v | grep '^[a-z]' | cut -c3-
To reset all assume-unchanged files back to normal:
git ls-files -v | grep '^[a-z]' | cut -c3- | xargs git update-index --no-assume-unchanged --
Note: This command which has been listed elsewhere does not appear to reset all assume-unchanged files any longer (I believe it used to and previously listed it as a solution):
git update-index --really-refresh
Shortcuts
To make these common tasks easy to execute in git, add/update the following alias section to .gitconfig
for your user (e.g. ~/.gitconfig
on a *nix or macOS system):
[alias]
hide = update-index --assume-unchanged
unhide = update-index --no-assume-unchanged
unhide-all = ! git ls-files -v | grep '^[a-z]' | cut -c3- | xargs git unhide --
hidden = ! git ls-files -v | grep '^[a-z]' | cut -c3-
EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245
To see exactly what is happening, use nc -l
and an user agent like a browser or cURL.
Save the form to an .html
file:
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text" value="text default">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><button type="submit">Submit</button>
</form>
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
Run:
nc -l localhost 8000
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received. Firefox sent:
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"
text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------9051914041544843365972754266--
Aternativelly, cURL should send the same POST request as your a browser form:
nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000
You can do multiple tests with:
while true; do printf '' | nc -l localhost 8000; done
You can also set a max execution time in your .htaccess
file:
php_value max_execution_time 180
Perhaps what you are looking for is something like this:
x=np.array(0)
In this way you can create an array without any element. It similar than:
x=[]
This way you will be able to append new elements to your array in advance.
<link rel="shortcut icon" href="{% static 'favicon/favicon.ico' %}"/>
Just add that in ur base file like first answer but ico extension and add it to the static folder
No you cannot force a file that is already committed in the repo to be removed just because it is added to the .gitignore
You have to git rm --cached
to remove the files that you don't want in the repo. ( --cached since you probably want to keep the local copy but remove from the repo. ) So if you want to remove all the exe's from your repo do
git rm --cached /\*.exe
(Note that the asterisk * is quoted from the shell - this lets git, and not the shell, expand the pathnames of files and subdirectories)
Use the in
keyword.
if 'apples' in d:
if d['apples'] == 20:
print('20 apples')
else:
print('Not 20 apples')
If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get
function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None
instead):
if d.get('apples', 0) == 20:
print('20 apples.')
else:
print('Not 20 apples.')
head -1000 input > output && sed -i '1,+999d' input
For example:
$ cat input
1
2
3
4
5
6
$ head -3 input > output && sed -i '1,+2d' input
$ cat input
4
5
6
$ cat output
1
2
3
You need to change your code as below:
<html>
<body>
<span id="span_Id">Click the button to display the content.</span>
<button onclick="displayDate()">Click Me</button>
<script>
function displayDate() {
var span_Text = document.getElementById("span_Id").innerText;
alert (span_Text);
}
</script>
</body>
</html>
SELECT CAST(FLOOR(CAST(getdate() AS FLOAT)) AS DATETIME)
...is not a good solution, per the comments below.
I would delete this answer, but I'll leave it here as a counter-example since I think the commenters' explanation of why it's not a good idea is still useful.
Press Shift + 4 ("$") on the first line, then Shift + j ("J").
And if you want help, go into vi, and then press F1.
I'm surprised that a lot of you seem to want to save files on the server. Solution to keep everything in memory is as follows:
[HttpPost("api/upload")]
public async Task<IHttpActionResult> Upload()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var file in provider.Contents)
{
var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
var buffer = await file.ReadAsByteArrayAsync();
//Do whatever you want with filename and its binary data.
}
return Ok();
}
They are the same.
Both mean that when coming in to the load balancer, the request will be directed to the server that served the first request (and has the session).
As @Nakilon said, their is a comparing tool built in github if that's what you use.
To use it, append the url of the repo with "/compare".
The following should work. The lambda function filter out the duplicated words.
inputs=[]
input = raw_input("Word: ").strip()
while input:
inputs.append(input)
input = raw_input("Word: ").strip()
uniques=reduce(lambda x,y: ((y in x) and x) or x+[y], inputs, [])
print 'There are', len(uniques), 'unique words'
Here's my solution to this type of problem:
Create a new class in CSS and position off screen. Then put your alt text in HTML right before the property that calls your background image. Can be any tag, H1
, H2
, p
, etc.
CSS
<style type="text/css">
.offleft {
margin-left: -9000px;
position: absolute;
}
</style>
HTML
<h1 class="offleft">put your alt text here</h1>
<div class or id that calls your bg image> </div>
I have developed an answer inspired by Jamie Hutber's.
It's a promise based function where you can set:
10
;100 ms
.Therefore, by default, it will wait 1 second until the element appears on the DOM.
If it does not show up it will return a promise.reject
with null
so you can handle the error as per your wish.
Code
function waitForElement(selector, delay = 1000, tries = 10) {
const element = document.querySelector(selector);
// creates a local variable w/ the name of the selector to keep track of all tries
if (!window[`__${selector}`]) {
window[`__${selector}`] = 0;
}
function _search() {
return new Promise((resolve) => {
window[`__${selector}`]++;
console.log(window[`__${selector}`]);
setTimeout(resolve, delay);
});
}
//element not found, retry
if (element === null) {
if (window[`__${selector}`] >= tries) {
window[`__${selector}`] = 0;
return Promise.reject(null);
}
return _search().then(() => waitForElement(selector));
} else {
return Promise.resolve(element);
}
}
Usage:
async function wait(){
try{
const $el = await waitForElement(".llama");
console.log($el);
} catch(err){
console.error("Timeout - couldn't find element.")
}
}
wait();
In the example above it will wait for the selector .llama
. You can add a greater delay and test it here on the console of StackoverFlow.
Just add the class llama
to any element on the DOM.
I received the same error message. To resolve this I just replaced the Oracle.ManagedDataAccess
assembly with the older Oracle.DataAccess
assembly. This solution may not work if you require new features found in the new assembly. In my case I have many more higher priority issues then trying to configure the new Oracle
assembly.
.contextmenu method :-
Try as follows
<div id="wrap">Right click</div>
<script>
$('#wrap').contextmenu(function() {
alert("Right click");
});
</script>
.mousedown method:-
$('#wrap').mousedown(function(event) {
if(event.which == 3){
alert('Right Mouse button pressed.');
}
});
In my mind I have to consider that the foo
folder is a stand-alone library. I might want to consider moving it to the Lib\site-packages
folder within a python installation. I might want to consider adding a foo.pth
file there.
I know it's a library since the ./programs/my_python_program.py
contains the following line:
from foo.tasks import my_function
So it doesn't matter that ./programs
is a sibling folder to ./foo
. It's the fact that my_python_program.py
is run as a script like this:
python ./programs/my_python_program.py
You can use upstream headers (named starting with $http_) and additional custom headers. For example:
add_header X-Upstream-01 $http_x_upstream_01;
add_header X-Hdr-01 txt01;
next, go to console and make request with user's header:
curl -H "X-Upstream-01: HEADER1" -I http://localhost:11443/
the response contains X-Hdr-01, seted by server and X-Upstream-01, seted by client:
HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Mon, 30 Nov 2015 23:54:30 GMT
Content-Type: text/html;charset=UTF-8
Connection: keep-alive
X-Hdr-01: txt01
X-Upstream-01: HEADER1
The function fromJSON() in RJSONIO, rjson and jsonlite don't return a simple 2D data.frame for complex nested json objects.
To overcome this you can use tidyjson. It takes in a json and always returns a data.frame. It is currently not availble in CRAN, you can get it here: https://github.com/sailthru/tidyjson
Update: tidyjson is now available in cran, you can install it directly using install.packages("tidyjson")
There is no native boolean data type for SQLite. Per the Datatypes doc:
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).
Insert Name of Segue to unwind.
Then,- (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender.
with your segue identify.
One option would be:
SET SERVEROUTPUT ON
EXEC DBMS_OUTPUT.PUT_LINE(your_fn_name(your_fn_arguments));
I think this:
text.delete("1.0", tkinter.END)
Or if you did from tkinter import *
text.delete("1.0", END)
That should work
Here is a simpler solution to list all files in a directory and to download it.
In your index.php file
<?php
$dir = "./";
$allFiles = scandir($dir);
$files = array_diff($allFiles, array('.', '..')); // To remove . and ..
foreach($files as $file){
echo "<a href='download.php?file=".$file."'>".$file."</a><br>";
}
The scandir() function list all files and directories inside the specified path. It works with both PHP 5 and PHP 7.
Now in the download.php
<?php
$filename = basename($_GET['file']);
// Specify file path.
$path = ''; // '/uplods/'
$download_file = $path.$filename;
if(!empty($filename)){
// Check file is exists on given path.
if(file_exists($download_file))
{
header('Content-Disposition: attachment; filename=' . $filename);
readfile($download_file);
exit;
}
else
{
echo 'File does not exists on given path';
}
}
Distinct objects list can be found using:
List distinctPersons = persons.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person:: getName))),
ArrayList::new));
mod_rewrite can only rewrite/redirect requested URIs. So you would need to request /apple/…
to get it rewritten to a corresponding /folder1/…
.
Try this:
RewriteEngine on
RewriteRule ^apple/(.*) folder1/$1
This rule will rewrite every request that starts with the URI path /apple/…
internally to /folder1/…
.
Edit As you are actually looking for the other way round:
RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /apple/$1 [L,R=301]
This rule is designed to work together with the other rule above. Requests of /folder1/…
will be redirected externally to /apple/…
and requests of /apple/…
will then be rewritten internally back to /folder1/…
.
If you want you can just put what you had in a list comprehension:
names_list = [line for line in open("names.txt", "r").read().splitlines() if line]
or
all_lines = open("names.txt", "r").read().splitlines()
names_list = [name for name in all_lines if name]
splitlines() has already removed the line endings.
I don't think those are as clear as just looping explicitly though:
names_list = []
with open('names.txt', 'r') as _:
for line in _:
line = line.strip()
if line:
names_list.append(line)
Edit:
Although, filter looks quite readable and concise:
names_list = filter(None, open("names.txt", "r").read().splitlines())
use market://
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + my_packagename));
Old question but I had similar issue and I solved it by adding
extern void* memset(void*, int, size_t);
or just
extern void* memset();
at the top of translation unit ( *.c file ).
After reviewing all the other answers, I ended up with this:
function oldSchoolMakeBuild(cb) {
var makeProcess = exec('make -C ./oldSchoolMakeBuild',
function (error, stdout, stderr) {
stderr && console.error(stderr);
cb(error);
});
makeProcess.stdout.on('data', function(data) {
process.stdout.write('oldSchoolMakeBuild: '+ data);
});
}
Sometimes data
will be multiple lines, so the oldSchoolMakeBuild
header will appear once for multiple lines. But this didn't bother me enough to change it.
I had this problem when using java 9+ modules. I had to open
the module in order for the com.fasterxml.jackson.databind
to access the objects with reflection. Alternatively you could only open the package where the models are located if you have one.
First App ID
make sure your ID push notification enable in production side
as appear in picture
Second Certificate
from production section create two certificate with your id (push notification enabled)
App Store and Ad Hoc certificate
Apple Push Notification service SSL (Sandbox) certificate
Third Provisioning Profiles
From Distribution section create App Store profile with your id
Finally
while you upload your bin , you must check what provisioning profile used and have many entitlements
this all cases cause this problem hope this be helpful with you
If you really want them to have ALL rights:
use YourDatabase
go
exec sp_addrolemember 'db_owner', 'UserName'
go
You could have just changed your query to:
SELECT ename, empno, (SELECT ename FROM EMP WHERE empno = e.mgr)AS MANAGER, mgr
from emp e
order by empno;
This would tell the engine that for the inner emp table, empno should be matched with mgr column from the outer table.
Well, you're going to have to check for null somewhere. You could do something like this:
from item in db.vw_Dropship_OrderItems
where (listStatus == null || listStatus.Contains(item.StatusCode))
&& (listMerchants == null || listMerchants.Contains(item.MerchantId))
select item;
Basic difference between add()
and replace()
can be described as:
add()
is used for simply adding a fragment to some root element.replace()
behaves similarly but at first it removes previous fragments and then adds next fragment.We can see the exact difference when we use addToBackStack()
together with add()
or replace()
.
When we press back button after in case of add()
... onCreateView is never called, but in case of replace()
, when we press back button ... oncreateView is called every time.
$ export MY_ENV_VAR=congratulation
$MY_ENV_VAR
You can also use all other ENV variables defined by your system like (in linux) $TERM, $SHELL, $HOME...
$ envsubst "`printf '${%s} ' $(sh -c "env|cut -d'=' -f1")`" < in.txt > out.txt
$ cat out.txt
and you should see "congratulation".
phpMyAdmin can handle CSV import. Here are the steps:
Prepare the CSV file to have the fields in the same order as the MySQL table fields.
Remove the header row from the CSV (if any), so that only the data is in the file.
Go to the phpMyAdmin interface.
Select the table in the left menu.
Click the import button at the top.
Browse to the CSV file.
Select the option "CSV using LOAD DATA".
Enter "," in the "fields terminated by".
Enter the column names in the same order as they are in the database table.
Click the go button and you are done.
This is a note that I prepared for my future use, and sharing here if someone else can benefit.
alter user hr identified by hr account unlock;
Give connection name as HR_ORCL Username: hr Password: hr Connection Type: Basic Role: default Hostname: localhost Port: 1521 SID: xe
Click on test and Connect
This should work :
MyInstace.GetType().GetInterfaces();
But nice too :
if (obj is IMyInterface)
Or even (not very elegant) :
if (obj.GetType() == typeof(IMyInterface))
The CodePage of Greek (ISO) can do it
The information about this codepage is into System.Text.Encoding.GetEncodings()
. Learn about in: https://msdn.microsoft.com/pt-br/library/system.text.encodinginfo.getencoding(v=vs.110).aspx
Greek (ISO) has codepage 28597 and name iso-8859-7.
Go to the code... \o/
string text = "Você está numa situação lamentável";
string textEncode = System.Web.HttpUtility.UrlEncode(text, Encoding.GetEncoding("iso-8859-7"));
//result: "Voce+esta+numa+situacao+lamentavel"
string textDecode = System.Web.HttpUtility.UrlDecode(textEncode);
//result: "Voce esta numa situacao lamentavel"
So, write this function...
public string RemoveAcentuation(string text)
{
return
System.Web.HttpUtility.UrlDecode(
System.Web.HttpUtility.UrlEncode(
text, Encoding.GetEncoding("iso-8859-7")));
}
Note that... Encoding.GetEncoding("iso-8859-7")
is equivalent to Encoding.GetEncoding(28597)
because first is the name, and second the codepage of Encoding.
You can try with this code (Same case)
chaine1 + chaine2;
I suggest you also (I prefer this) the string.concat method
All modules in Python have to have a certain directory structure. You can find details here.
Create an empty file called __init__.py
under the model
directory, such that your directory structure would look something like that:
.
+-- project
+-- src
+-- hello-world.py
+-- model
+-- __init__.py
+-- order.py
Also in your hello-world.py
file change the import statement to the following:
from model.order import SellOrder
That should fix it
P.S.: If you are placing your model
directory in some other location (not in the same directory branch), you will have to modify the python path using sys.path
.
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
CSS3 has a new filter attribute which will only work in webkit browsers supported in webkit browsers and in Firefox. It does not have support in IE or Opera mini:
img {_x000D_
-webkit-filter: invert(1);_x000D_
filter: invert(1);_x000D_
}
_x000D_
<img src="http://i.imgur.com/1H91A5Y.png">
_x000D_
The ONESHELL directive allows to write multiple line recipes to be executed in the same shell invocation.
all: foo
SOURCE_FILES = $(shell find . -name '*.c')
.ONESHELL:
foo: ${SOURCE_FILES}
FILES=()
for F in $^; do
FILES+=($${F})
done
gcc "$${FILES[@]}" -o $@
There is a drawback though : special prefix characters (‘@’, ‘-’, and ‘+’) are interpreted differently.
https://www.gnu.org/software/make/manual/html_node/One-Shell.html
For Chrome, Safari and Firefox, just use this:
form.append("blob", blob, filename);
(see MDN documentation)
If you are using terminal just type the following:
locate my.cnf
If you want be sure you need to check both
SomeProperty == null || SomeProperty == Guid.Empty
Because it can be null 'Nullable' and it can be an empty GUID something like this {00000000-0000-0000-0000-000000000000}
As explain by the JLS, integer operation are quite simple.
If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).
Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.
So to make it short, an operation would always result in a int
at the only exception that there is a long
value in it.
int = int + int
long = int + long
int = short + short
Note that the priority of the operator is important, so if you have
long = int * int + long
the int * int
operation would result in an int
, it would be promote into a long
during the operation int + long
For the record to go back and forth in basic python3:
a = 10
bin(a)
# '0b1010'
int(bin(a), 2)
# 10
eval(bin(a))
# 10
I've done something like this:
class Cow extends React.Component {
constructor (props) {
super(props);
this.state = {text: 'hello'};
}
componentDidMount () {
if (this.props.onMounted) {
this.props.onMounted({
say: text => this.say(text)
});
}
}
render () {
return (
<pre>
___________________
< {this.state.text} >
-------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
</pre>
);
}
say (text) {
this.setState({text: text});
}
}
And then somewhere else:
class Pasture extends React.Component {
render () {
return (
<div>
<Cow onMounted={callbacks => this.cowMounted(callbacks)} />
<button onClick={() => this.changeCow()} />
</div>
);
}
cowMounted (callbacks) {
this.cowCallbacks = callbacks;
}
changeCow () {
this.cowCallbacks.say('moo');
}
}
I haven't tested this exact code, but this is along the lines of what I did in a project of mine and it works nicely :). Of course this is a bad example, you should just use props for this, but in my case the sub-component did an API call which I wanted to keep inside that component. In such a case this is a nice solution.
Here's a really nice one-liner to print all the Gems along with their version, homepage, and description:
Gem::Specification.sort{|a,b| a.name <=> b.name}.map {|a| puts "#{a.name} (#{a.version})"; puts "-" * 50; puts a.homepage; puts a.description; puts "\n\n"};nil
w=open(file.txt, 'r')
print ('first line is : ',w.readline())
for line in w:
x= line
print ('last line is : ',x)
w.close()
The for
loop runs through the lines and x
gets the last line on the final iteration.
If have a solution without jQuery. A link where you can see a working example: http://www.letmaier.com/_selectbox/select_general_code.html (styled with more css)
The style-section of my solution:
<style>
#container { margin: 10px; padding: 5px; background: #E7E7E7; width: 300px; background: #ededed); }
#ul1 { display: none; list-style-type: none; list-style-position: outside; margin: 0px; padding: 0px; }
#container a { color: #333333; text-decoration: none; }
#container ul li { padding: 3px; padding-left: 0px; border-bottom: 1px solid #aaa; font-size: 0.8em; cursor: pointer; }
#container ul li:hover { background: #f5f4f4; }
</style>
Now the HTML-code inside the body-tag:
<form>
<div id="container" onMouseOver="document.getElementById('ul1').style.display = 'block';" onMouseOut="document.getElementById('ul1').style.display = 'none';">
Select one entry: <input name="entrytext" type="text" disabled readonly>
<ul id="ul1">
<li onClick="document.forms[0].elements['entrytext'].value='Entry 1'; document.getElementById('ul1').style.display = 'none';"><a href="#">Entry 1</a></li>
<li onClick="document.forms[0].elements['entrytext'].value='Entry 2'; document.getElementById('ul1').style.display = 'none';"><a href="#">Entry 2</a></li>
<li onClick="document.forms[0].elements['entrytext'].value='Entry 3'; document.getElementById('ul1').style.display = 'none';"><a href="#">Entry 3</a></li>
</ul>
</div>
</form>
I have been working on both solr and elastic search for .Net applications. The major difference what i have faced is
Elastic search :
Solr :
The default key binding for this is Ctrl+Shift+Space.
The underlying Visual Studio command is Edit.ParameterInfo
.
If the standard keybinding doesn't work for you (possible in some profiles) then you can change it via the keyboard options page
Global variables are not extern
nor static
by default on C and C++.
When you declare a variable as static
, you are restricting it to the current source file. If you declare it as extern
, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern
keyword) you will get a link error (symbol not found).
Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal
. If you declare it as static
, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal
.
What you can do in C++, that you can't in C, is to declare the variable as const
on the header, like this:
const int varGlobal = 7;
And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define
for constants.
If you need a global variable visible on multiple sources and not const
, declare it as extern
on the header, and then define it, this time without the extern keyword, on a source file:
Header included by multiple files:
extern int varGlobal;
In one of your source files:
int varGlobal = 7;
400 Bad request Error will be thrown due to incorrect authentication entries.
Note: Mostly due to Incorrect authentication entries due to spell changes will occur 400 Bad request.
This is because your device, on which you are running your application is not selected with your provisioning profile.
So just go through Certificates, Identifiers & Profiles select your iOS Provisioning Profiles
click on edit then select your Device
Maybe use reflection?
dynamic myVar = GetDataThatLooksVerySimilarButNotTheSame();
Type typeOfDynamic = myVar.GetType();
bool exist = typeOfDynamic.GetProperties().Where(p => p.Name.Equals("PropertyName")).Any();
I think a better way is using the static method fromString to avoid those regular expressions.
id = UUID.randomUUID();
UUID uuid = UUID.fromString(id.toString());
Assert.assertEquals(id.toString(), uuid.toString());
On the other hand
UUID uuidFalse = UUID.fromString("x");
throws java.lang.IllegalArgumentException: Invalid UUID string: x
For either the os.rename or shutil.move you will need to import the module. No * character is necessary to get all the files moved.
We have a folder at /opt/awesome called source with one file named awesome.txt.
in /opt/awesome
? ? ls
source
? ? ls source
awesome.txt
python
>>> source = '/opt/awesome/source'
>>> destination = '/opt/awesome/destination'
>>> import os
>>> os.rename(source, destination)
>>> os.listdir('/opt/awesome')
['destination']
We used os.listdir to see that the folder name in fact changed. Here's the shutil moving the destination back to source.
>>> import shutil
>>> shutil.move(destination, source)
>>> os.listdir('/opt/awesome/source')
['awesome.txt']
This time I checked inside the source folder to be sure the awesome.txt file I created exists. It is there :)
Now we have moved a folder and its files from a source to a destination and back again.
If you use Bootstrap, try to assign margin-bottom 0 to the paragraph and after assign the property align-items-center to container, for example, like this:
<div class="row align-items-center">
<p class="col-sm-1 mb-0">
....
</p>
</div>
Bootstrap by default assign a calculate margin bottom, so mb-0 disabled this.
I hope it helps
In my case the culprit was the lone opening <?php
tag in the last line of the file. Apparently it works on some configurations with no problems but causes problems on others.
Example using StringTokenizer class :
String st = " hello all students";
String st1;
char f;
String fs="";
StringTokenizer a= new StringTokenizer(st);
while(a.hasMoreTokens()){
st1=a.nextToken();
f=Character.toUpperCase(st1.charAt(0));
fs+=f+ st1.substring(1);
System.out.println(fs);
}
tl;dr: You don't have to remove the slashes, you have nested JSON, and hence have to decode the JSON twice: DEMO (note I used double slashes in the example, because the JSON is inside a JS string literal).
I assume that your actual JSON looks like
{"data":"{\n \"taskNames\" : [\n \"01 Jan\",\n \"02 Jan\",\n \"03 Jan\",\n \"04 Jan\",\n \"05 Jan\",\n \"06 Jan\",\n \"07 Jan\",\n \"08 Jan\",\n \"09 Jan\",\n \"10 Jan\",\n \"11 Jan\",\n \"12 Jan\",\n \"13 Jan\",\n \"14 Jan\",\n \"15 Jan\",\n \"16 Jan\",\n \"17 Jan\",\n \"18 Jan\",\n \"19 Jan\",\n \"20 Jan\",\n \"21 Jan\",\n \"22 Jan\",\n \"23 Jan\",\n \"24 Jan\",\n \"25 Jan\",\n \"26 Jan\",\n \"27 Jan\"]}"}
I.e. you have a top level object with one key, data
. The value of that key is a string containing JSON itself. This is usually because the server side code didn't properly create the JSON. That's why you see the \"
inside the string. This lets the parser know that "
is to be treated literally and doesn't terminate the string.
So you can either fix the server side code, so that you don't double encode the data, or you have to decode the JSON twice, e.g.
var data = JSON.parse(JSON.parse(json).data));
itertools
provides the chain function for that:
From http://docs.python.org/library/itertools.html#recipes:
def flatten(listOfLists):
"Flatten one level of nesting"
return chain.from_iterable(listOfLists)
Note that the result is an iterable, so you may need list(flatten(...))
.
Add to .icons div {width:160px; height:130px;}
will work out very nicely
Hope it will help
If you have pandas
installed, you can convert the ordered dict to a pandas Series
. This will allow random access to the dictionary elements.
>>> import collections
>>> import pandas as pd
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'
>>> s = pd.Series(d)
>>> s['bar']
spam
>>> s.iloc[1]
spam
>>> s.index[1]
bar
You can use a plugin available here..
https://plugins.jquery.com/cookie/
and then to write a cookie do
$.cookie("test", 1);
to access the set cookie do
$.cookie("test");
Update: Installing latest version of gcc 9: (gcc 9.3.0) - released March 12, 2020:
Same method can be applied to gcc 10 (gcc 10.1.0) - released May 7, 2020
Download file: gcc-9.3.0.tar.gz or gcc-10.1.0.tar.gz
Compile and install:
//required libraries: (some may already have been installed)
dnf install libmpc-devel mpfr-devel gmp-devel
//if dnf install libmpc-devel is not working try:
dnf --enablerepo=PowerTools install libmpc-devel
//install zlib
dnf install zlib-devel*
./configure --with-system-zlib --disable-multilib --enable-languages=c,c++
make -j 8 <== this may take around an hour or more to finish
(depending on your cpu speed)
make install
Tested under CentOS 7.8.2003 for gcc 9.3 and gcc 10.1
Tested under CentOS 8.1.1911 for gcc 10.1 (may take more time to compile)
Results: gcc/g++ 9.3.0/10.1.0
Installing gcc 7.4 (gcc 7.4.0) - released December 6, 2018:
Download file: https://ftp.gnu.org/gnu/gcc/gcc-7.4.0/gcc-7.4.0.tar.gz
Compile and install:
//required libraries:
yum install libmpc-devel mpfr-devel gmp-devel
./configure --with-system-zlib --disable-multilib --enable-languages=c,c++
make -j 8 <== this may take around 50 minutes or less to finish with 8 threads
(depending on your cpu speed)
make install
Result:
Notes:
1. This Stack Overflow answer will help to see how to verify the downloaded source file.
2. Use the option --prefix
to install gcc to another directory other than the default one. The toplevel installation directory defaults to /usr/local. Read about gcc installation options
app-routing.module.ts
const routes: Routes = [
{ path: 'products', component: ProductsComponent },
{ path: 'product/:id', component: ProductDetailsComponent },
{ path: '', redirectTo: '/products', pathMatch: 'full' },
];
In controller you can navigate like this,
this.router.navigate(['/products', productId]);
It will land you to path like this: http://localhost:4200/products/product-id
A good place to look at is the man page of bash. Here's an online version. Look for "INVOCATION" section.
These appear to be seconds since epoch.
In [20]: df = DataFrame(data['values'])
In [21]: df.columns = ["date","price"]
In [22]: df
Out[22]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 358 entries, 0 to 357
Data columns (total 2 columns):
date 358 non-null values
price 358 non-null values
dtypes: float64(1), int64(1)
In [23]: df.head()
Out[23]:
date price
0 1349720105 12.08
1 1349806505 12.35
2 1349892905 12.15
3 1349979305 12.19
4 1350065705 12.15
In [25]: df['date'] = pd.to_datetime(df['date'],unit='s')
In [26]: df.head()
Out[26]:
date price
0 2012-10-08 18:15:05 12.08
1 2012-10-09 18:15:05 12.35
2 2012-10-10 18:15:05 12.15
3 2012-10-11 18:15:05 12.19
4 2012-10-12 18:15:05 12.15
In [27]: df.dtypes
Out[27]:
date datetime64[ns]
price float64
dtype: object
sys.path
might include items that aren't specifically in your PYTHONPATH
environment variable. To query the variable directly, use:
import os
try:
user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
except KeyError:
user_paths = []
CHAR(5)
or
MEDIUMINT (5) UNSIGNED ZEROFILL
The first takes 5 bytes per zip code.
The second takes only 3 bytes per zip code. The ZEROFILL option is necessary for zip codes with leading zeros.
you can try
$(function()
{
$(window).bind('load', function()
{
// INSERT YOUR CODE THAT WILL BE EXECUTED AFTER THE PAGE COMPLETELY LOADED...
});
});
i had the same problem and this code worked for me. how it works for you too!
Indexes of two types can be added: when you define a primary key, MySQL will take it as index by default.
Explanation
Primary key as index
Consider you have a tbl_student
table and you want student_id
as primary key:
ALTER TABLE `tbl_student` ADD PRIMARY KEY (`student_id`)
Above statement adds a primary key, which means that indexed values must be unique and cannot be NULL.
Specify index name
ALTER TABLE `tbl_student` ADD INDEX student_index (`student_id`)
Above statement will create an ordinary index with student_index
name.
Create unique index
ALTER TABLE `tbl_student` ADD UNIQUE student_unique_index (`student_id`)
Here, student_unique_index
is the index name assigned to student_id and creates an index for which values must be unique (here null can be accepted).
Fulltext option
ALTER TABLE `tbl_student` ADD FULLTEXT student_fulltext_index (`student_id`)
Above statement will create the Fulltext index name with student_fulltext_index
, for which you need MyISAM Mysql Engine.
How to remove indexes ?
DROP INDEX `student_index` ON `tbl_student`
How to check available indexes?
SHOW INDEX FROM `tbl_student`
You can try this
$query = mysql_query("SELECT * FROM $this_table") or die (mysql_error());
or this
$query = mysql_query("SELECT * FROM $this_table") or die ("Table does not exists!");
or this
$query = mysql_query("SELECT * FROM $this_table");
if(!$query)
echo "The ".$this_table." does not exists";
Hope it helps!
This is plain Javascript and has nothing to do with the jQuery library.
You simply escape the apostrophe with a backslash:
theAnchorText = 'I\'m home';
Another alternative is to use quotation marks around the string, then you don't have to escape apostrophes:
theAnchorText = "I'm home";
Sorry, not Swift, just a proof of concept in the closest language at hand.
// JavaScript POC. Output:
// Matches: ["GOODBYE","CRUEL","WORLD","IM","LEAVING","U","TODAY"]
let str = `GOODBYE,CRUEL,WORLD,IM,LEAVING,U,TODAY`
let matches = [];
function recurse(str, matches) {
let regex = /^((,?([A-Z]+))+)$/gm
let m
while ((m = regex.exec(str)) !== null) {
matches.unshift(m[3])
return str.replace(m[2], '')
}
return "bzzt!"
}
while ((str = recurse(str, matches)) != "bzzt!") ;
console.log("Matches: ", JSON.stringify(matches))
Note: If you were really going to use this, you would use the position of the match as given by the regex match function, not a string replace.
If you just need sampling without replacement:
>>> import random
>>> random.sample(range(1, 100), 3)
[77, 52, 45]
random.sample takes a population and a sample size k
and returns k
random members of the population.
If you have to control for the case where k
is larger than len(population)
, you need to be prepared to catch a ValueError
:
>>> try:
... random.sample(range(1, 2), 3)
... except ValueError:
... print('Sample size exceeded population size.')
...
Sample size exceeded population size
According to SQL standard you cannot use non-aggregate columns in select list. MySQL allows such usage (uless ONLY_FULL_GROUP_BY mode used) but result is not predictable.
You should first select fromEmail, MIN(read), and then, with second query (or subquery) - Subject.
A simple and clean way to do this is to use the open source library Prime.
As delnan pointed out, the match
keyword in Scala has nothing to do with regexes. To find out whether a string matches a regex, you can use the String.matches
method. To find out whether a string starts with an a, b or c in lower or upper case, the regex would look like this:
word.matches("[a-cA-C].*")
You can read this regex as "one of the characters a, b, c, A, B or C followed by anything" (.
means "any character" and *
means "zero or more times", so ".*" is any string).
Yet another solution if Object.entries
won't work for you.
const obj = {_x000D_
'1': 29,_x000D_
'2': 42_x000D_
};_x000D_
const arr = Array.from(Object.keys(obj), k=>[`${k}`, obj[k]]);_x000D_
console.log(arr);
_x000D_
It's almost the same in MySQL, but you have to use the table alias right after the word "DELETE":
DELETE a
FROM TableA AS a
INNER JOIN TableB AS b
ON a.BId = b.BId
WHERE [filter condition]
Solved this using sudo chown -R _mysql:_mysql /usr/local/var/mysql
Thanks to Matteo Alessani
you can use zscore to analyze the data in column C and D for outliers, where zscore is the series - series.mean / series.std(). Use apply too create a user defined function for difference between C and D creating a new resulting dataframe. Apply uses the group result set.
from scipy.stats import zscore
columns = ['A', 'B', 'C', 'D']
records = [
['foo', 'one', 0.162003, 0.087469],
['bar', 'one', -1.156319, -1.5262719999999999],
['foo', 'two', 0.833892, -1.666304],
['bar', 'three', -2.026673, -0.32205700000000004],
['foo', 'two', 0.41145200000000004, -0.9543709999999999],
['bar', 'two', 0.765878, -0.095968],
['foo', 'one', -0.65489, 0.678091],
['foo', 'three', -1.789842, -1.130922]
]
df = pd.DataFrame.from_records(records, columns=columns)
print(df)
standardize=df.groupby('A')['C','D'].transform(zscore)
print(standardize)
outliersC= (standardize['C'] <-1.1) | (standardize['C']>1.1)
outliersD= (standardize['D'] <-1.1) | (standardize['D']>1.1)
results=df[outliersC | outliersD]
print(results)
#Dataframe results
A B C D
0 foo one 0.162003 0.087469
1 bar one -1.156319 -1.526272
2 foo two 0.833892 -1.666304
3 bar three -2.026673 -0.322057
4 foo two 0.411452 -0.954371
5 bar two 0.765878 -0.095968
6 foo one -0.654890 0.678091
7 foo three -1.789842 -1.130922
#C and D transformed Z score
C D
0 0.398046 0.801292
1 -0.300518 -1.398845
2 1.121882 -1.251188
3 -1.046514 0.519353
4 0.666781 -0.417997
5 1.347032 0.879491
6 -0.482004 1.492511
7 -1.704704 -0.624618
#filtering using arbitrary ranges -1 and 1 for the z-score
A B C D
1 bar one -1.156319 -1.526272
2 foo two 0.833892 -1.666304
5 bar two 0.765878 -0.095968
6 foo one -0.654890 0.678091
7 foo three -1.789842 -1.130922
>>>>>>>>>>>>> Part 2
splitting = df.groupby('A')
#look at how the data is grouped
for group_name, group in splitting:
print(group_name)
def column_difference(gr):
return gr['C']-gr['D']
grouped=splitting.apply(column_difference)
print(grouped)
A
bar 1 0.369953
3 -1.704616
5 0.861846
foo 0 0.074534
2 2.500196
4 1.365823
6 -1.332981
7 -0.658920
The basic difference between Linear Regression and Logistic Regression is : Linear Regression is used to predict a continuous or numerical value but when we are looking for predicting a value that is categorical Logistic Regression come into picture.
Logistic Regression is used for binary classification.
In my case, it was just because there were no source file in the target. All of my library was template with source code in the header. Adding an empty file.cpp solved the problem.
Thank you for inspiration.
I had the same problem and instead of just copy-pasting some function from the Internet, I wrote an open source tool for it. Feel free to use it or provide feedback!
https://github.com/BrandEmbassy/php-memory
Just install it using Composer and then you get the current PHP memory limit like this:
$configuration = new \BrandEmbassy\Memory\MemoryConfiguration();
$limitProvider = new \BrandEmbassy\Memory\MemoryLimitProvider($configuration);
$limitInBytes = $memoryLimitProvider->getLimitInBytes();
Here's another solution for people who don't want to use html, body, .blah { height: 100% }
.
.app {_x000D_
position: fixed;_x000D_
left: 0;_x000D_
right: 0;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
overflow-y: auto;_x000D_
}_x000D_
_x000D_
.full-height {_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.test {_x000D_
width: 10px;_x000D_
background: red;_x000D_
}
_x000D_
<div class="app">_x000D_
<div class="full-height test">_x000D_
</div>_x000D_
Scroll works too_x000D_
</div>
_x000D_
To Hide the Action Bar add the below code in Values/Styles
<style name="CustomActivityThemeNoActionBar" parent="@android:style/Theme.Holo.Light">
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
</style>
Then in your AndroidManifest.xml file add the below code in the required activity
<activity
android:name="com.newbelievers.android.NBMenu"
android:label="@string/title_activity_nbmenu"
android:theme="@style/CustomActivityThemeNoActionBar">
</activity>
Because growthRates is a sequence (you're even iterating it!) and you multiply it by (1 + 0.01), which is obviously a float (1.01). I guess you mean for growthRate in growthRates: ... * growthrate
?
My answer is similar to this one on ServerFault.com.
If you want to be more conservative than granting "all privileges", you might want to try something more like these.
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO some_user_;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO some_user_;
The use of public
there refers to the name of the default schema created for every new database/catalog. Replace with your own name if you created a schema.
To access a schema at all, for any action, the user must be granted "usage" rights. Before a user can select, insert, update, or delete, a user must first be granted "usage" to a schema.
You will not notice this requirement when first using Postgres. By default every database has a first schema named public
. And every user by default has been automatically been granted "usage" rights to that particular schema. When adding additional schema, then you must explicitly grant usage rights.
GRANT USAGE ON SCHEMA some_schema_ TO some_user_ ;
Excerpt from the Postgres doc:
For schemas, allows access to objects contained in the specified schema (assuming that the objects' own privilege requirements are also met). Essentially this allows the grantee to "look up" objects within the schema. Without this permission, it is still possible to see the object names, e.g. by querying the system tables. Also, after revoking this permission, existing backends might have statements that have previously performed this lookup, so this is not a completely secure way to prevent object access.
For more discussion see the Question, What GRANT USAGE ON SCHEMA exactly do?. Pay special attention to the Answer by Postgres expert Craig Ringer.
These commands only affect existing objects. Tables and such you create in the future get default privileges until you re-execute those lines above. See the other answer by Erwin Brandstetter to change the defaults thereby affecting future objects.
Use the new viewWillTransitionToSize(_:withTransitionCoordinator:)
You are incorrectly using the super
and this
keyword. Here is an example of how they work:
class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
move(meters: number) {
console.log(this.name + " moved " + meters + "m.");
}
}
class Horse extends Animal {
move() {
console.log(super.name + " is Galloping...");
console.log(this.name + " is Galloping...");
super.move(45);
}
}
var tom: Animal = new Horse("Tommy the Palomino");
Animal.prototype.name = 'horseee';
tom.move(34);
// Outputs:
// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.
Explanation:
super.name
, this refers to the prototype chain of the object tom
, not the object tom
self. Because we have added a name property on the Animal.prototype
, horseee will be outputted.this.name
, the this
keyword refers to the the tom object itself. move
method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);
. Using the super
keyword in this context will look for a move
method on the prototype chain which is found on the Animal prototype.Remember TS still uses prototypes under the hood and the class
and extends
keywords are just syntactic sugar over prototypical inheritance.
Here's the real solution (with other cool CSS3 stuff):
#fixed-square {
position: fixed;
top: 0;
right: 0;
z-index: 9500;
cursor: pointer;
width: 24px;
padding: 18px 18px 14px;
opacity: 0.618;
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
transform: rotate(-90deg);
-webkit-transition: all 0.145s ease-out;
-moz-transition: all 0.145s ease-out;
-ms-transition: all 0.145s ease-out;
transition: all 0.145s ease-out;
}
Note the top:0 and right:0. That's what did it for me.
first, create a class to hold your parameters:
public class PkRk {
public int pk { get; set; }
public int rk { get; set; }
}
then, use the Html.Action
passing the parameters:
Html.Action("PkRkAction", new { pkrk = new PkRk { pk=400, rk=500} })
and use in Controller:
public ActionResult PkRkAction(PkRk pkrk) {
return PartialView(pkrk);
}
You can achieve this using dynamic TSQL (remember to use QUOTENAME to avoid SQL injection attacks):
Pivots with Dynamic Columns in SQL Server 2005
SQL Server - Dynamic PIVOT Table - SQL Injection
Obligatory reference to The Curse and Blessings of Dynamic SQL
var yesterday = DateTime.Now.AddDays(-1);
Here's another option...
events = {}
for line in csv.reader(open(os.path.join(path, 'events.txt'), "rb")):
if line[0][0] == "#":
continue
events[line[0]] = line[1] if len(line) == 2 else line[1:]
To bring the existing answers together with an important clarification:
As stated, the problem with NAME=sam echo "$NAME"
is that $NAME
gets expanded by the current shell before assignment NAME=sam
takes effect.
Solutions that preserve the original semantics (of the (ineffective) solution attempt NAME=sam echo "$NAME"
):
Use either eval
[1]
(as in the question itself), or printenv
(as added by Aaron McDaid to heemayl's answer), or bash -c
(from Ljm Dullaart's answer), in descending order of efficiency:
NAME=sam eval 'echo "$NAME"' # use `eval` only if you fully control the command string
NAME=sam printenv NAME
NAME=sam bash -c 'echo "$NAME"'
printenv
is not a POSIX utility, but it is available on both Linux and macOS/BSD.
What this style of invocation (<var>=<name> cmd ...
) does is to define NAME
:
In other words: NAME
only exists for the command being invoked, and has no effect on the current shell (if no variable named NAME
existed before, there will be none after; a preexisting NAME
variable remains unchanged).
POSIX defines the rules for this kind of invocation in its Command Search and Execution chapter.
The following solutions work very differently (from heemayl's answer):
NAME=sam; echo "$NAME"
NAME=sam && echo "$NAME"
While they produce the same output, they instead define:
NAME
(only) rather than an environment variable
echo
were a command that relied on environment variable NAME
, it wouldn't be defined (or potentially defined differently from earlier).Note that every environment variable is also exposed as a shell variable, but the inverse is not true: shell variables are only visible to the current shell and its subshells, but not to child processes, such as external utilities and (non-sourced) scripts (unless they're marked as environment variables with export
or declare -x
).
[1] Technically, bash
is in violation of POSIX here (as is zsh
): Since eval
is a special shell built-in, the preceding NAME=sam
assignment should cause the the variable $NAME
to remain in scope after the command finishes, but that's not what happens.
However, when you run bash
in POSIX compatibility mode, it is compliant.
dash
and ksh
are always compliant.
The exact rules are complicated, and some aspects are left up to the implementations to decide; again, see Command Search and Execution.
Also, the usual disclaimer applies: Use eval
only on input you fully control or implicitly trust.
By adding a few more headers I was able to get the data:
import urllib2,cookielib
site= "http://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/getHistoricalData.jsp?symbol=JPASSOCIAT&fromDate=1-JAN-2012&toDate=1-AUG-2012&datePeriod=unselected&hiddDwnld=true"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
req = urllib2.Request(site, headers=hdr)
try:
page = urllib2.urlopen(req)
except urllib2.HTTPError, e:
print e.fp.read()
content = page.read()
print content
Actually, it works with just this one additional header:
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
Below is the way we can do Multiple projection to perform Distinct
package org.hibernate.criterion;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.type.Type;
/**
* A count for style : count (distinct (a || b || c))
*/
public class MultipleCountProjection extends AggregateProjection {
private boolean distinct;
protected MultipleCountProjection(String prop) {
super("count", prop);
}
public String toString() {
if(distinct) {
return "distinct " + super.toString();
} else {
return super.toString();
}
}
public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery)
throws HibernateException {
return new Type[] { Hibernate.INTEGER };
}
public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery)
throws HibernateException {
StringBuffer buf = new StringBuffer();
buf.append("count(");
if (distinct) buf.append("distinct ");
String[] properties = propertyName.split(";");
for (int i = 0; i < properties.length; i++) {
buf.append( criteriaQuery.getColumn(criteria, properties[i]) );
if(i != properties.length - 1)
buf.append(" || ");
}
buf.append(") as y");
buf.append(position);
buf.append('_');
return buf.toString();
}
public MultipleCountProjection setDistinct() {
distinct = true;
return this;
}
}
ExtraProjections.java
package org.hibernate.criterion;
public final class ExtraProjections
{
public static MultipleCountProjection countMultipleDistinct(String propertyNames) {
return new MultipleCountProjection(propertyNames).setDistinct();
}
}
Sample Usage:
String propertyNames = "titleName;titleDescr;titleVersion"
criteria countCriteria = ....
countCriteria.setProjection(ExtraProjections.countMultipleDistinct(propertyNames);
Referenced from https://forum.hibernate.org/viewtopic.php?t=964506
We can also use logging to print data on the console.
Example:
import logging
from flask import Flask
app = Flask(__name__)
@app.route('/print')
def printMsg():
app.logger.warning('testing warning log')
app.logger.error('testing error log')
app.logger.info('testing info log')
return "Check your console"
if __name__ == '__main__':
app.run(debug=True)
Or you can use
<select [(ngModel)]="Answers[''+question.Name+'']" ng-options="option for option in question.Options">
</select>
If you're actually ony interested in the latest revision files of a directory, Github lets you download a repository as Zip file, which does not contain history. So downloading is very much faster.
Here's a different implementation of Jenny Lang's answer that works for Rails 5.
First create the migration file:
bundle exec be rails g migration DropEpisodes
Then populate the migration file as follows:
class DropEpisodes < ActiveRecord::Migration[5.1]
def change
drop_table :episodes
end
end
Running rails db:migrate
will drop the table. If you run rails db:rollback
, Rails will throw a ActiveRecord::IrreversibleMigration
error.
string countryName = "USA";
DataTable dt = new DataTable();
int id = (from DataRow dr in dt.Rows
where (string)dr["CountryName"] == countryName
select (int)dr["id"]).FirstOrDefault();
Your loop is wrong:
for (int i=0; i=((Main.size())-1); i++) {
Try this:
for (int i=0; i < Main.size(); i++) {
Also, a more idiomatic way of reading numbers into a vector and writing them to stdout is something along these lines:
#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
#include <algorithm> // for std::copy
int main()
{
std::ifstream is("numbers.txt");
std::istream_iterator<double> start(is), end;
std::vector<double> numbers(start, end);
std::cout << "Read " << numbers.size() << " numbers" << std::endl;
// print the numbers to stdout
std::cout << "numbers read in:\n";
std::copy(numbers.begin(), numbers.end(),
std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
}
although you should check the status of the ifstream
for read errors.
And if you didn't want to use strict equality, you could use exists:
myFunction(strings.exists { x => customPredicate(x) })
If I've understood your problem correctly, there are two possible problems here:
resultset
is null
- I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.resultset.getString(i++)
will get columns 1,2,3 and so on from each subsequent row.I think that the second point is probably your problem here.
Lets say you only had 1 row returned, as follows:
Col 1, Col 2, Col 3
A , B, C
Your code as it stands would only get A - it wouldn't get the rest of the columns.
I suggest you change your code as follows:
ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>();
while (resultset.next()) {
int i = 1;
while(i <= numberOfColumns) {
arrayList.add(resultset.getString(i++));
}
System.out.println(resultset.getString("Col 1"));
System.out.println(resultset.getString("Col 2"));
System.out.println(resultset.getString("Col 3"));
System.out.println(resultset.getString("Col n"));
}
Edit:
To get the number of columns:
ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();
There seems to be issues where Remove-Item -Force -Recurse
can intermittently fail on Windows because the underlying filesystem is asynchronous. This answer seems to address it. The user has also been actively involved with the Powershell team on GitHub.
The problem is that you do not have any of Certification Authority certificates installed on your system. And these certs cannot be installed with cygwin's setup.exe.
Update: Install Net/ca-certificates package in cygwin (thanks dirkjot)
There are two solutions:
Actually install root certificates. Curl guys extracted for you certificates from Mozilla.
cacert.pem
file is what you are looking for. This file contains > 250 CA certs (don't know how to trust this number of ppl). You need to download this file, split it to individual certificates put them to /usr/ssl/certs (your CApath) and index them.
Here is how to do it. With cygwin setup.exe install curl and openssl packages execute:
$ cd /usr/ssl/certs
$ curl http://curl.haxx.se/ca/cacert.pem |
awk '{print > "cert" (1+n) ".pem"} /-----END CERTIFICATE-----/ {n++}'
$ c_rehash
Important: In order to use c_rehash
you have to install openssl-perl
too.
Ignore SSL certificate verification.
WARNING: Disabling SSL certificate verification has security implications. Without verification of the authenticity of SSL/HTTPS connections, a malicious attacker can impersonate a trusted endpoint (such as GitHub or some other remote Git host), and you'll be vulnerable to a Man-in-the-Middle Attack. Be sure you fully understand the security issues and your threat model before using this as a solution.
$ env GIT_SSL_NO_VERIFY=true git clone https://github...
As @Veger said, you can make it final
so that the variable can be used in the inner class.
final ViewPager pager = (ViewPager) findViewById(R.id.fieldspager);
I called it pager
rather than mPager
because you are using it as a local variable in the onCreate
method. The m
prefix is cusomarily reserved for class member variables (i.e. variables that are declared at the beginning of the class and are available to all class methods).
If you actually do need a class member variable, it doesn't work to make it final because you can't use findViewById
to set its value until onCreate
. The solution is to not use an anonymous inner class. This way the mPager
variable doesn't need to be declared final and can be used throughout the class.
public class MainActivity extends AppCompatActivity {
private ViewPager mPager;
private Button mButton;
@Override
public void onCreate(Bundle savedInstanceState) {
// ...
mPager = (ViewPager) findViewById(R.id.fieldspager);
// ...
mButton.setOnClickListener(myButtonClickHandler);
}
View.OnClickListener myButtonClickHandler = new View.OnClickListener() {
@Override
public void onClick(View view) {
mPager.setCurrentItem(2, true);
}
};
}
On modern browsers you can try with the pointer-events css property (but it leads to the impossibility to detect mouse events on the parent node):
p {
position: relative;
background-color: blue;
color:#ffffff;
padding:0px 10px;
pointer-events:none;
}
p::before {
content: attr(data-before);
margin-left:-10px;
margin-right:10px;
position: relative;
background-color: red;
padding:0px 10px;
pointer-events:auto;
}
When the event target is your "p" element, you know it is your "p:before".
If you still need to detect mouse events on the main p, you may consider the possibility to modify your HTML structure. You can add a span tag and the following style:
p span {
background:#393;
padding:0px 10px;
pointer-events:auto;
}
The event targets are now both the "span" and the "p:before" elements.
Example without jquery: http://jsfiddle.net/2nsptvcu/
Example with jquery: http://jsfiddle.net/0vygmnnb/
Here is the list of browsers supporting pointer-events: http://caniuse.com/#feat=pointer-events
IMHO, the best way to use two different Python versions on macOS is via homebrew
. After installing homebrew on macOS, run the commands below on your terminal.
brew install python@2
brew install python
Now you can run Python 2.7 by invoking python2
or Python 3 by invoking python3
. In addition to this, you can use virtualenv
or pyenv to manage different versions of python
environments.
I have never personally used miniconda
but from the documentation, it looks like it is similar to using pip
and virtualenv
in combination.
Change the button to :
<button onclick="getElementById('hidden-div').style.display = 'block'; this.style.display = 'none'">Check Availability</button>
Or even better, use a proper event handler by identifying the button :
<button id="show_button">Check Availability</button>
and a script
<script type="text/javascript">
var button = document.getElementById('show_button')
button.addEventListener('click',hideshow,false);
function hideshow() {
document.getElementById('hidden-div').style.display = 'block';
this.style.display = 'none'
}
</script>
Rails 4.0.0 will look image defined with image-url
in same directory structure with your css file.
For example, if your css in assets/stylesheets/main.css.scss
, image-url('logo.png')
becomes url(/assets/logo.png)
.
If you move your css file to assets/stylesheets/cpanel/main.css.scss
, image-url('logo.png')
becomes /assets/cpanel/logo.png
.
If you want to use image directly under assets/images directory, you can use asset-url('logo.png')
How easy :)
date("F j, Y", strtotime( '-1 days' ) );
Example:
echo date("Y-m-j H:i:s", strtotime( '-1 days' ) ); // 2018-07-18 07:02:43
Output:
2018-07-17 07:02:43
It's an attribute wildcard selector. In the sample you've given, it looks for any child element under .show-grid
that has a class that CONTAINS span
.
So would select the <strong>
element in this example:
<div class="show-grid">
<strong class="span6">Blah blah</strong>
</div>
You can also do searches for 'begins with...'
div[class^="something"] { }
which would work on something like this:-
<div class="something-else-class"></div>
and 'ends with...'
div[class$="something"] { }
which would work on
<div class="you-are-something"></div>
Good references
Correct Answer here
Create class with name MyApp like below:
public class MyApp implements Application.ActivityLifecycleCallbacks, ComponentCallbacks2 {
private Context context;
public void setContext(Context context)
{
this.context = context;
}
private boolean isInBackground = false;
@Override
public void onTrimMemory(final int level) {
if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
isInBackground = true;
Log.d("status = ","we are out");
}
}
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
if(isInBackground){
isInBackground = false;
Log.d("status = ","we are in");
}
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
@Override
public void onConfigurationChanged(Configuration configuration) {
}
@Override
public void onLowMemory() {
}
}
Then, everywhere you want (better first activity launched in app), add the code below:
MyApp myApp = new MyApp();
registerComponentCallbacks(myApp);
getApplication().registerActivityLifecycleCallbacks(myApp);
Done! Now when the app is in the background, we get log status : we are out
and when we go in app, we get log status : we are out
HashMap keyArrayList = new HashMap();
Iterator itr = yourJson.keys();
while (itr.hasNext())
{
String key = (String) itr.next();
keyArrayList.put(key, yourJson.get(key).toString());
}
Try with
c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -iru
When multiple versions of the .NET Framework are executing side-by-side on a single computer, the ASP.NET ISAPI version mapped to an ASP.NET application determines which version of the common language runtime (CLR) is used for the application.
Above command will Installs the version of ASP.NET that is associated with Aspnet_regiis.exe and only registers ASP.NET in IIS.
You can use like this:
public static String executeHttpPost1(String url,
HashMap<String, String> postParameters) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
HttpClient client = getNewHttpClient();
try{
request = new HttpPost(url);
}
catch(Exception e){
e.printStackTrace();
}
if(postParameters!=null && postParameters.isEmpty()==false){
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(postParameters.size());
String k, v;
Iterator<String> itKeys = postParameters.keySet().iterator();
while (itKeys.hasNext())
{
k = itKeys.next();
v = postParameters.get(k);
nameValuePairs.add(new BasicNameValuePair(k, v));
}
UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(nameValuePairs);
request.setEntity(urlEntity);
}
try {
Response = client.execute(request,localContext);
HttpEntity entity = Response.getEntity();
int statusCode = Response.getStatusLine().getStatusCode();
Log.i(TAG, ""+statusCode);
Log.i(TAG, "------------------------------------------------");
try{
InputStream in = (InputStream) entity.getContent();
//Header contentEncoding = Response.getFirstHeader("Content-Encoding");
/*if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
in = new GZIPInputStream(in);
}*/
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
response = str.toString();
Log.i(TAG, "response"+response);
}
catch(IllegalStateException exc){
exc.printStackTrace();
}
} catch(Exception e){
Log.e("log_tag", "Error in http connection "+response);
}
finally {
}
return response;
}
Make sure that
yourFile.js:
exports.yourFunction = function(a,b){
//your code
}
matches
app.js
var express = require('express');
var app = express();
var yourModule = require('yourFile');
app.get('/your_path', yourModule.yourFunction);
For me, I ran into this issue when copy pasting a module into another module for testing, needed to change the exports. xxxx at the top of the file
try
persons.GroupBy(x => x.PersonId).Select(x => x)
or
to check if any person is repeating in your list try
persons.GroupBy(x => x.PersonId).Where(x => x.Count() > 1).Any(x => x)
**just fire bootstrap modal close button click event**
var app = angular.module('myApp', []);
app.controller('myCtrl',function($scope,$http){
$('#btnClose').click();// this is bootstrap modal close button id that fire click event
})
--------------------------------------------------------------------------------
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" id="btnClose" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
just set modal 'close button' id as i set btnClose, for closing modal in angular you have to just fire that close button click event as i did $('#btnClose').click()
You can use jwt-decode, so then you could write:
import jwt_decode from 'jwt-decode';
var token = 'eyJ0eXAiO.../// jwt token';
var decoded = jwt_decode(token);
console.log(decoded);
/*{exp: 10012016 name: john doe, scope:['admin']}*/
Or you can use an arrow function to define it:
$(document).ready(() => {
$('#bfCaptchaEntry').click(()=>{
});
});
For better browser support:
$(document).ready(function() {
$('#bfCaptchaEntry').click(function (){
});
});
The following link explains filters in Angular extremely well. It shows how it is possible to define custom sort logic within an ng-repeat. http://toddmotto.com/everything-about-custom-filters-in-angular-js
For sorting object with properties, this is the code I have used: (Note that this sort is the standard JavaScript sort method and not specific to angular) Column Name is the name of the property on which sorting is to be performed.
self.myArray.sort(function(itemA, itemB) {
if (self.sortOrder === "ASC") {
return itemA[columnName] > itemB[columnName];
} else {
return itemA[columnName] < itemB[columnName];
}
});
So, something like
DECLARE @i AS FLOAT = 2
SELECT @i / 3
SELECT CAST(@i / 3 AS DECIMAL(18,2))
I would however recomend that this be done in the UI/Report layer, as this will cuase loss of precision.
This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.
Three javascript libraries are required, createCookie
, readCookie
and eraseCookie
. These libraries are not mine but I began using them about 5 years ago and don't know their origin.
createCookie = function(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
readCookie = function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
eraseCookie = function (name) {
createCookie(name, "", -1);
}
To call them you need to create a small PHP function, normally as part of your support library, as follows:
<?php
function createjavaScriptCookie($sessionVarible) {
$s = "<script>";
$s = $s.'createCookie('. '"'. $sessionVarible
.'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
$s = $s."</script>";
echo $s;
}
?>
So to use all you now have to include within your index.php file is
$_SESSION["video_dir"] = "/video_dir/";
createjavaScriptCookie("video_dir");
Now in your javascript library.js you can recover the cookie with the following code:
var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';
I hope this helps.
Answered my own question after reading your advice on the vertical-align CSS attribute. Thanks for the tip!
.pdf:before {
padding: 0 5px 0 0;
content: url(../img/icon/pdf_small.png);
vertical-align: -50%;
}
One of my first projects as a programmer was a gem called stagecoach that (among other things) allowed the automatic adding of a github issue number to every commit message on a branch, which is a part of the question that hasn't really been answered.
Essentially when creating a branch you'd use a custom command (something like stagecoach -b <branch_name> -g <issue_number>
), and the issue number would then be assigned to that branch in a yml file. There was then a commit hook that appended the issue number to the commit message automatically.
I wouldn't recommend it for production use as at the time I'd only been programming for a few months and I no longer maintain it, but it may be of interest to somebody.
The latter versions of Notepad++ do not apparently include the TextFX plugin at all. In order to use the plugin for sorting/eliminating duplicates, the plugin must be either downloaded and installed (more involved) or added using the plugin manager.
A) Easy way (as described here).
Plugins -> Plugin Manager -> Show Plugin Manager -> Available tab -> TextFX Characters -> Install
B) More involved way, if another version is needed or the easy way does not work.
Download the plugin from SourceForge:
Open the zip file and extract NppTextFX.dll
Place NppTextFX.dll in the Notepad++ plugins directory, such as:
C:\Program Files\Notepad++\plugins
Start Notepad++, and TextFX will be one of the file menu items (as seen in Answer #1 above by Colin Pickard)
After installing the TextFX plugin, follow the instructions in Answer #1 to sort and remove duplicates.
Also, consider setting up a keyboard shortcut using Settings > Shorcut mapper if you use this command frequently or want to replicate a keyboard shortcut, such as F9 in TextPad for sorting.
this seems to work, but not sure if it's optimized for performance or not.
$request->user()->get(['id'])->groupBy('id')->keys()->all();
output:
array:2 [
0 => 4
1 => 1
]
You do not need to activate the sheet (you'll take a huge performance hit for doing so, actually). Since you are declaring an object for the sheet, when you call the method starting with "wb." you are selecting that object. For example, you can jump in between workbooks without activating anything like here:
Sub Test()
Dim wb1 As Excel.Workbook
Set wb1 = Workbooks.Open("C:\Documents and Settings\xxxx\Desktop\test1.xls")
Dim wb2 As Excel.Workbook
Set wb2 = Workbooks.Open("C:\Documents and Settings\xxxx\Desktop\test2.xls")
wb1.Sheets("Sheet1").Cells(1, 1).Value = 24
wb2.Sheets("Sheet1").Cells(1, 1).Value = 24
wb1.Sheets("Sheet1").Cells(2, 1).Value = 54
End Sub
Try,
string[] files = new DirectoryInfo(dir).GetFiles().Select(o => o.Name).ToArray();
Above line may throw UnauthorizedAccessException. To handle this check out below link
I'm sure you have your reasons, but just in case... you should also consider using a "merge" query instead:
begin
merge into some_table st
using (select 'some' name, 'values' value from dual) v
on (st.name=v.name)
when matched then update set st.value=v.value
when not matched then insert (name, value) values (v.name, v.value);
end;
(modified the above to be in the begin/end block; obviously you can run it independantly of the procedure too).
As shown above, the problem is the margin preceding the <p>
tag in rendering time.
Not an elegant solution but effective would be to decrease the top margin.
p { margin-top: -20px; }
#Using a text file for the example
with open("yourFile.txt","r") as f:
text = f.readlines()
for line in text:
print line
If you want, for example, to check a specific line for a length greater than 10, work with what you already have available.
for line in text:
if len(line) > 10:
print line
(?ms)^((?:\d+(?!\.\*)\.)+)(\d+)?(\.\*)?$|^(\d+)\.\*$|^(\*|\d+)$
Does exactly match your 6 first examples, and rejects the 4 others
You can remove '(?ms)'
I used it to indicate to this regexp to be applied on multi-lines through QuickRex
To add my grain of sand here: if an element resides behind a fixed div it will be considered as not visible and you won't be able to click it; this happened to me recently and i solved it executing a script as recommended above, which does:
document.evaluate("<xpath locator for element to be clicked>", document, null, XPathResult.ANY_TYPE, null).iterateNext().click()", locator);
log4j.rootLogger=OFF
Try parseInt function:
var number = parseInt("10");
But there is a problem. If you try to convert "010" using parseInt function, it detects as octal number, and will return number 8. So, you need to specify a radix (from 2 to 36). In this case base 10.
parseInt(string, radix)
Example:
var result = parseInt("010", 10) == 10; // Returns true
var result = parseInt("010") == 10; // Returns false
Note that parseInt
ignores bad data after parsing anything valid.
This guid will parse as 51:
var result = parseInt('51e3daf6-b521-446a-9f5b-a1bb4d8bac36', 10) == 51; // Returns true
No, not exactly. But it can inherit from a class and implement one or more interfaces.
Clear terminology is important when discussing concepts like this. One of the things that you'll see mark out Jon Skeet's writing, for example, both here and in print, is that he is always precise in the way he decribes things.
The simplest way is
<li class="{{ Request::is('contacts/*') ? 'active' : '' }}">Dashboard</li>
This colud capture the contacts/, contacts/create, contacts/edit...
On windows use the name of the table in quotes:
TABLE "user";
or SELECT * FROM "user";
Beyond compare allows you to do that and much more.
It's one of those tools I can't live without.
Take a look here for a reference on the scripting options
If you are using data.table
then tstrsplit()
is a natural choice:
tstrsplit(string, ":")[[2]]
[1] "E001" "E002" "E003"
As of git 2.18 you can use git --list-cmds=alias
A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.
http://jaywcjlove.github.io/hotkeys/
hotkeys('ctrl+a,ctrl+b,r,f', function(event,handler){
switch(handler.key){
case "ctrl+a":alert('you pressed ctrl+a!');break;
case "ctrl+b":alert('you pressed ctrl+b!');break;
case "r":alert('you pressed r!');break;
case "f":alert('you pressed f!');break;
}
});
hotkeys understands the following modifiers: ?
, shift
, option
, ?
, alt
, ctrl
, control
, command
, and ?
.
The following special keys can be used for shortcuts: backspace
, tab
, clear
, enter
, return
, esc
, escape
, space
, up
, down
, left
, right
, home
, end
, pageup
, pagedown
, del
, delete
and f1
through f19
.
use jQuery's $.getJSON
$.getJSON('mydata.json', function(data) {
//do stuff with your data here
});
I don't know if VB.net in VS 2008 is any different, but none of the above worked for me. Double-clicking My Project in Solution Explorer brings up the window seen below. Select Application on the left, then browse for your icon using the combobox. After you build, it should show up on your exe file.
I was able to get this done following more complex instructions suggested by Valentino Vranken and rao , but here is a more simple approach , for a more simple report . This will put each table on a separate sheet and name them in Excel . It doesn't seem to have an effect on other exports like PDF and Word .
First in the Tablix Properties
of of your tables under General
, check either Add a page break before or after
, this separates the report into sheets .
Then in each table , click the table , then in the Grouping
view , on the Row Groups
side , select the parent group or the default row group and then in the Properties
view under Group -> PageBreak
set BreakLocation
to None
and PageName
to the sheet's name .
The quick and dirty way, you can view the available environment variables from the below link.
http://localhost:8080/env-vars.html/
Just replace localhost
with your Jenkins hostname, if its different
The "lsb_release" command provides certain Linux Standard Base and distribution-specific information. So using the below command we can get Operating system name and operating system version.
"lsb_release -a"
Use any of the following:
String str = String.valueOf('c');
String str = Character.toString('c');
String str = 'c' + "";
If using JDBC driver you may use function escape sequence like this:
select {fn MOD(5, 2)}
#Result 1
select mod(5, 2)
#SQL Error [195] [S00010]: 'mod' is not a recognized built-in function name.
The latter alternative is used for methods on mocks that return void
.
Please have a look, for example, here: How to make mock to void methods with mockito
As @high6 and @erik-p-hansen pointed out in the answer given by @high6, this can be overcome by importing the target for the module where the PrimeNumberModel class is, which is probably the same name as your project in a simple project.
While looking at this, I came across the article Write your first Unit Test in Swift on swiftcast.tv by Clayton McIlrath. It discusses access modifiers, shows an example of the same problem you are having (but for a ViewController rather than a model file) and shows how to both import the target and solve the access modifier problem by including the destination file in the target, meaning you don't have to make the class you are trying to test public unless you actually want to do so.
std::vector<unsigned char> intToBytes(int value)
{
std::vector<unsigned char> result;
result.push_back(value >> 24);
result.push_back(value >> 16);
result.push_back(value >> 8);
result.push_back(value );
return result;
}
Andy E is correct that there is no HTML-based way to do this*; but if you are willing to use Flash, you can do it. The following works reliably on systems that have Flash installed. If your app needs to work on iPhone, then of course you'll need a fallback HTML-based solution.
* (Update 4/22/2013: HTML does now support this, in HTML5. See the other answers.)
Flash uploading also has other advantages -- Flash gives you the ability to show a progress bar as the upload of a large file progresses. (I'm pretty sure that's how Gmail does it, by using Flash behind the scenes, although I may be wrong about that.)
Here is a sample Flex 4 app that allows the user to pick a file, and then displays it:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
creationComplete="init()">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:Button x="10" y="10" label="Choose file..." click="showFilePicker()" />
<mx:Image id="myImage" x="9" y="44"/>
<fx:Script>
<![CDATA[
private var fr:FileReference = new FileReference();
// Called when the app starts.
private function init():void
{
// Set up event handlers.
fr.addEventListener(Event.SELECT, onSelect);
fr.addEventListener(Event.COMPLETE, onComplete);
}
// Called when the user clicks "Choose file..."
private function showFilePicker():void
{
fr.browse();
}
// Called when fr.browse() dispatches Event.SELECT to indicate
// that the user has picked a file.
private function onSelect(e:Event):void
{
fr.load(); // start reading the file
}
// Called when fr.load() dispatches Event.COMPLETE to indicate
// that the file has finished loading.
private function onComplete(e:Event):void
{
myImage.data = fr.data; // load the file's data into the Image
}
]]>
</fx:Script>
</s:Application>
See the documentation on plt.axis()
. This:
plt.axis('equal')
doesn't work because it changes the limits of the axis to make circles appear circular. What you want is:
plt.axis('square')
This creates a square plot with equal axes.
strncpy
combats buffer overflow by requiring you to put a length in it. strcpy
depends on a trailing \0
, which may not always occur.
Secondly, why you chose to only copy 5 characters on 7 character string is beyond me, but it's producing expected behavior. It's only copying over the first n
characters, where n
is the third argument.
The n
functions are all used as defensive coding against buffer overflows. Please use them in lieu of older functions, such as strcpy
.
In case anyone was curious, I was able to figure this out based on all of your responses combined!
This is in the Facelet:
<h:form id="myform">
<h:inputSecret value="#{createNewPassword.newPassword1}" id="newPassword1" />
<h:message class="error" for="newPassword1" id="newPassword1Error" />
<h:inputSecret value="#{createNewPassword.newPassword2}" id="newPassword2" />
<h:message class="error" for="newPassword2" id="newPassword2Error" />
<h:commandButton value="Continue" action="#{createNewPassword.continueButton}" />
</h:form>
This is in the continueButton() method:
FacesContext.getCurrentInstance().addMessage("myForm:newPassword1", new FacesMessage(PASSWORDS_DONT_MATCH, PASSWORDS_DONT_MATCH));
And it works! Thanks for the help!
The main difference is that ChildA.__init__
will unconditionally call Base.__init__
whereas ChildB.__init__
will call __init__
in whatever class happens to be ChildB
ancestor in self
's line of ancestors
(which may differ from what you expect).
If you add a ClassC
that uses multiple inheritance:
class Mixin(Base):
def __init__(self):
print "Mixin stuff"
super(Mixin, self).__init__()
class ChildC(ChildB, Mixin): # Mixin is now between ChildB and Base
pass
ChildC()
help(ChildC) # shows that the Method Resolution Order is ChildC->ChildB->Mixin->Base
then Base
is no longer the parent of ChildB
for ChildC
instances. Now super(ChildB, self)
will point to Mixin
if self
is a ChildC
instance.
You have inserted Mixin
in between ChildB
and Base
. And you can take advantage of it with super()
So if you are designed your classes so that they can be used in a Cooperative Multiple Inheritance scenario, you use super
because you don't really know who is going to be the ancestor at runtime.
The super considered super post and pycon 2015 accompanying video explain this pretty well.
Looks array_filter will be suitable solution for this...
$userdb=Array
(
(0) => Array
(
(uid) => '100',
(name) => 'Sandra Shush',
(url) => 'urlof100'
),
(1) => Array
(
(uid) => '5465',
(name) => 'Stefanie Mcmohn',
(pic_square) => 'urlof100'
),
(2) => Array
(
(uid) => '40489',
(name) => 'Michael',
(pic_square) => 'urlof40489'
)
);
PHP Code
<?php
$search = 5465;
$found = array_filter($userdb,function($v,$k) use ($search){
return $v['uid'] == $search;
},ARRAY_FILTER_USE_BOTH) // With latest PHP third parameter is mandatory.. Available Values:- ARRAY_FILTER_USE_BOTH OR ARRAY_FILTER_USE_KEY
$values= print_r(array_values($found));
$keys = print_r(array_keys($found));
Well this one works...
double roundOff = Math.round(a * 100.0) / 100.0;
Output is
123.14
Or as @Rufein said
double roundOff = (double) Math.round(a * 100) / 100;
this will do it for you as well.
In Scala
def permutazione(n: List[Int]): List[List[Int]] = permutationeAcc(n, Nil)
def permutationeAcc(n: List[Int], acc: List[Int]): List[List[Int]] = {
var result: List[List[Int]] = Nil
for (i ? n if (!(acc contains (i))))
if (acc.size == n.size-1)
result = (i :: acc) :: result
else
result = result ::: permutationeAcc(n, i :: acc)
result
}
Try new_list = a[0:2] + [a[4]] + a[6:]
.
Or more generally, something like this:
from itertools import chain
new_list = list(chain(a[0:2], [a[4]], a[6:]))
This works with other sequences as well, and is likely to be faster.
Or you could do this:
def chain_elements_or_slices(*elements_or_slices):
new_list = []
for i in elements_or_slices:
if isinstance(i, list):
new_list.extend(i)
else:
new_list.append(i)
return new_list
new_list = chain_elements_or_slices(a[0:2], a[4], a[6:])
But beware, this would lead to problems if some of the elements in your list were themselves lists.
To solve this, either use one of the previous solutions, or replace a[4]
with a[4:5]
(or more generally a[n]
with a[n:n+1]
).
When you normalize a matrix using NORM_L1, you are dividing every pixel value by the sum of absolute values of all the pixels in the image. As a result, all pixel values become much less than 1 and you get a black image. Try NORM_MINMAX instead of NORM_L1.
the input does not have to be a list of records - it can be a single dictionary as well:
pd.DataFrame.from_records({'a':1,'b':2}, index=[0])
a b
0 1 2
Which seems to be equivalent to:
pd.DataFrame({'a':1,'b':2}, index=[0])
a b
0 1 2
Chr(Number) should work for you.
select 'Hello' || chr(10) ||' world' from dual
Remember different platforms expect different new line characters:
Sometimes this syntax wont work:
df[['col1','col2']] = df[['col1','col2']].fillna()
Use the following instead:
df['col1','col2']
strtol()
is your friend here. The third parameter is the numerical base that you are converting.
Example:
#include <stdio.h> /* printf */
#include <stdlib.h> /* strtol */
int main(int argc, char **argv)
{
long int num = 0;
long int num2 =0;
char * str. = "f00d";
char * str2 = "0xf00d";
num = strtol( str, 0, 16); //converts hexadecimal string to long.
num2 = strtol( str2, 0, 0); //conversion depends on the string passed in, 0x... Is hex, 0... Is octal and everything else is decimal.
printf( "%ld\n", num);
printf( "%ld\n", num);
}
I think functions should not return null, for the health of your code-base. I can think of a few reasons:
There will be a large quantity of guard clauses treating null reference if (f() != null)
.
What is null
, is it an accepted answer or a problem? Is null a valid state for a specific object? (imagine that you are a client for the code). I mean all reference types can be null, but should they?
Having null
hanging around will almost always give a few unexpected NullRef exceptions from time to time as your code-base grows.
There are some solutions, tester-doer pattern
or implementing the option type
from functional programming.
% Assuming that the dataset is ";"-delimited and each line ends with ";"
fid = fopen('sampledata.csv');
tline = fgetl(fid);
u=sprintf('%c',tline); c=length(u);
id=findstr(u,';'); n=length(id);
data=cell(1,n);
for I=1:n
if I==1
data{1,I}=u(1:id(I)-1);
else
data{1,I}=u(id(I-1)+1:id(I)-1);
end
end
ct=1;
while ischar(tline)
ct=ct+1;
tline = fgetl(fid);
u=sprintf('%c',tline);
id=findstr(u,';');
if~isempty(id)
for I=1:n
if I==1
data{ct,I}=u(1:id(I)-1);
else
data{ct,I}=u(id(I-1)+1:id(I)-1);
end
end
end
end
fclose(fid);
I'd like to write explicitly two methods which allow accomplishing this in pure JavaScript:
document.getElementsByClassName('realClasssName').length
Note 1: Argument of this method needs a string with the real class name, without the dot at the begin of this string.
document.querySelectorAll('.realClasssName').length
Note 2: Argument of this method needs a string with the real class name but with the dot at the begin of this string.
Note 3: This method works also with any other CSS selectors, not only with class selector. So it's more universal.
I also write one method, but using two name conventions to solve this problem using jQuery:
jQuery('.realClasssName').length
or
$('.realClasssName').length
Note 4: Here we also have to remember about the dot, before the class name, and we can also use other CSS selectors.
for any extra column if there is no mapping then map it to null like the following SQL query
Select Col1, Col2, Col3, Col4, Col5 from Table1
Union
Select Col1, Col2, Col3, Null as Col4, Null as Col5 from Table2````
There is a solution to this if you really need a static access to the current context. In Startup.Configure(….)
app.Use(async (httpContext, next) =>
{
CallContext.LogicalSetData("CurrentContextKey", httpContext);
try
{
await next();
}
finally
{
CallContext.FreeNamedDataSlot("CurrentContextKey");
}
});
And when you need it you can get it with :
HttpContext context = CallContext.LogicalGetData("CurrentContextKey") as HttpContext;
I hope that helps. Keep in mind this workaround is when you don’t have a choice. The best practice is to use de dependency injection.