Primary key - we can put only one primary key on a table into a table and we can not left that column blank when we are entering the values into the table.
Unique Key - we can put more than one unique key on a table and we may left that column blank when we are entering the values into the table. column take unique values (not same) when we applied primary & unique key.
This worked for me:
String s = "string";
if (Pattern.matches("[a-zA-Z]+", s)) {
System.out.println("clear");
} else {
System.out.println("buzz");
}
You're attempting to free something that isn't a pointer to a "freeable" memory address. Just because something is an address doesn't mean that you need to or should free it.
There are two main types of memory you seem to be confusing - stack memory and heap memory.
Stack memory lives in the live span of the function. It's temporary space for things that shouldn't grow too big. When you call the function main
, it sets aside some memory for your variables you've declared (p
,token
, and so on).
Heap memory lives from when you malloc
it to when you free
it. You can use much more heap memory than you can stack memory. You also need to keep track of it - it's not easy like stack memory!
You have a few errors:
You're trying to free memory that's not heap memory. Don't do that.
You're trying to free the inside of a block of memory. When you have in fact allocated a block of memory, you can only free it from the pointer returned by malloc
. That is to say, only from the beginning of the block. You can't free a portion of the block from the inside.
For your bit of code here, you probably want to find a way to copy relevant portion of memory to somewhere else...say another block of memory you've set aside. Or you can modify the original string if you want (hint: char value 0 is the null terminator and tells functions like printf to stop reading the string).
EDIT: The malloc function does allocate heap memory*.
"9.9.1 The malloc and free Functions
The C standard library provides an explicit allocator known as the malloc package. Programs allocate blocks from the heap by calling the malloc function."
~Computer Systems : A Programmer's Perspective, 2nd Edition, Bryant & O'Hallaron, 2011
EDIT 2: * The C standard does not, in fact, specify anything about the heap or the stack. However, for anyone learning on a relevant desktop/laptop machine, the distinction is probably unnecessary and confusing if anything, especially if you're learning about how your program is stored and executed. When you find yourself working on something like an AVR microcontroller as H2CO3 has, it is definitely worthwhile to note all the differences, which from my own experience with embedded systems, extend well past memory allocation.
Assuming such a query would return a single row, you could use either
select @EmpId = Id from dbo.Employee
Or
set @EmpId = (select Id from dbo.Employee)
Maven dependency
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-security</artifactId>
</dependency>
<dependency>
<groupId>org.apache.ws.security</groupId>
<artifactId>wss4j</artifactId>
<version>1.6.19</version>
</dependency>
Configuration class
import org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor;
@Configuration
public class ConfigurationClass{
@Bean
public Wss4jSecurityInterceptor securityInterceptor() {
Wss4jSecurityInterceptor wss4jSecurityInterceptor = new Wss4jSecurityInterceptor();
wss4jSecurityInterceptor.setSecurementActions("UsernameToken");
wss4jSecurityInterceptor.setSecurementMustUnderstand(true);
wss4jSecurityInterceptor.setSecurementPasswordType("PasswordText");
wss4jSecurityInterceptor.setSecurementUsername("123456789011");
wss4jSecurityInterceptor.setSecurementPassword("TestPass123");
return wss4jSecurityInterceptor;
}
Result xml
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header>
<wsse:Security
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
SOAP-ENV:mustUnderstand="1">
<wsse:UsernameToken wsu:Id="UsernameToken-F57F40DC89CD6998E214700450735811">
<wsse:Username>123456789011</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">TestPass123</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
...
something
...
</SOAP-ENV:Body>
Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.
Discord supports Markdown and uses highlight.js to highlight code-blocks.
Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.
To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).
```language
message
```
Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).
Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.
Several good solutions here. If you're still on Win2K and can't install anything on the remote computer, this also works:
Open the Computer Management Console (right click My Computer, choose Manage; open from Administrative Tools in the Start Menu; or open from the MMC using the snap-in).
Right click on your computer name and choose "Connect to Remote Computer"
Put in the computer name and credentials and you have full access to many admin functions including the services control panel.
Case study: GitHub API
https://developer.github.com/v3/#client-errors
Maybe copying from well known APIs is a wise idea:
There are three possible types of client errors on API calls that receive request bodies:
Sending invalid JSON will result in a 400 Bad Request response.
HTTP/1.1 400 Bad Request Content-Length: 35 {"message":"Problems parsing JSON"}
Sending the wrong type of JSON values will result in a 400 Bad Request response.
HTTP/1.1 400 Bad Request Content-Length: 40 {"message":"Body should be a JSON object"}
Sending invalid fields will result in a 422 Unprocessable Entity response.
HTTP/1.1 422 Unprocessable Entity Content-Length: 149 { "message": "Validation Failed", "errors": [ { "resource": "Issue", "field": "title", "code": "missing_field" } ] }
>>> list1 = [1,2,3,4,5,6]
>>> list2 = [3, 5, 7, 9]
>>> list(set(list1).intersection(list2))
[3, 5]
If you know the class you are expecting but you still don't have an object you can even do this:
private string GetAcceptButtonText<T>() where T : BaseClass, new()
{
switch (new T())
{
case BaseClassReview _: return "Review";
case BaseClassValidate _: return "Validate";
case BaseClassAcknowledge _: return "Acknowledge";
default: return "Accept";
}
}
If you want to do something in the UI on regular time intervals very good option is to use CountDownTimer:
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
For those that are not overflowing but hiding by negative margin:
$('#element').height() + -parseInt($('#element').css("margin-top"));
(ugly but only one that works so far)
This is a guess at best, but perhaps your development team is building and deploying the application in debug mode, in stead of release mode. This will cause the occurrence of .pdb files. The implication of this is that your application will take up additional resources to collect system state and debugging information during the execution of your system, causing more processor utilization.
So, it would be simple enough to ensure that they are building and deploying in release mode.
Right click on the table in SQL Management Studio.
Select Script... Create to... New Query Window.
This will generate a script to recreate the table in a new query window.
Change the name of the table in the script to whatever you want the new table to be named.
Execute the script.
if A:
will prove false if A is 0, False, empty string, empty list or None, which can lead to undesired results.
ELXAN@DB1> create table cedvel(id integer,ad varchar2(15)); Table created. ELXAN@DB1> alter table cedvel add constraint pk_ad primary key(id); Table altered. ELXAN@DB1> create sequence test_seq start with 1 increment by 1; Sequence created. ELXAN@DB1> create or replace trigger ad_insert before insert on cedvel REFERENCING NEW AS NEW OLD AS OLD for each row begin select test_seq.nextval into :new.id from dual; end; / 2 3 4 5 6 7 8 Trigger created. ELXAN@DB1> insert into cedvel (ad) values ('nese'); 1 row created.
Create a git clone of that includes your Subversion trunk, tags, and branches with
git svn clone http://svn.example.com/project -T trunk -b branches -t tags
The --stdlayout
option is a nice shortcut if your Subversion repository uses the typical structure:
git svn clone http://svn.example.com/project --stdlayout
Make your git repository ignore everything the subversion repo does:
git svn show-ignore >> .git/info/exclude
You should now be able to see all the Subversion branches on the git side:
git branch -r
Say the name of the branch in Subversion is waldo
. On the git side, you'd run
git checkout -b waldo-svn remotes/waldo
The -svn suffix is to avoid warnings of the form
warning: refname 'waldo' is ambiguous.
To update the git branch waldo-svn
, run
git checkout waldo-svn git svn rebase
To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config
to contain
[svn-remote "svn-mybranch"] url = http://svn.example.com/project/branches/mybranch fetch = :refs/remotes/mybranch
You'll need to develop the habit of running
git svn fetch --fetch-all
to update all of what git svn
thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run
git checkout -b mybranch-svn remotes/mybranch
For the branches from which you intend to git svn dcommit
, keep their histories linear!
You may also be interested in reading an answer to a related question.
UPDATE:
Like @jack-marchetti stated in his comment, and @devantoine with the link: https://developers.facebook.com/x/bugs/357750474364812/
Facebook has changed how the sharer.php works, as Ibrahim Faour replies to the bug filed with Facebook.
The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post, from the url OG meta tags.
Try this (via Javascript in this example):
'http://www.facebook.com/sharer.php?s=100&p[title]='+encodeURIComponent('this is a title') + '&p[summary]=' + encodeURIComponent('description here') + '&p[url]=' + encodeURIComponent('http://www.nufc.com') + '&p[images][0]=' + encodeURIComponent('http://www.somedomain.com/image.jpg')
I tried this quickly without the image part and the sharer.php window appears pre-populated, so it looks like a solution.
I found this via this SO article:
Want custom title / image / description in facebook share link from a flash app
and this link contained in an answer from Lelis718:
so all credit to Lelis718 for this answer.
[EDIT 3rd May 2013] - seems like the original URL i had here no longer works for me without also including "s=100" in the query string - no idea why but have updated accordingly
You'll have problems creating lists without commas. It shouldn't be too hard to transform your data so that it uses commas as separating character.
Once you have commas in there, it's a relatively simple list creation operations:
array1 = [1,2,3]
array2 = [4,5,6]
array3 = [array1, array2]
array4 = [7,8,9]
array5 = [10,11,12]
array3 = [array3, [array4, array5]]
When testing we get:
print(array3)
[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
And if we test with indexing it works correctly reading the matrix as made up of 2 rows and 2 columns:
array3[0][1]
[4, 5, 6]
array3[1][1]
[10, 11, 12]
Hope that helps.
Actually asXML() converts the string into xml as it name says:
<id>5</id>
This will display normally on a web page but it will cause problems when you matching values with something else.
You may use strip_tags function to get real value of the field like:
$newString = strip_tags($xml->asXML());
PS: if you are working with integers or floating numbers, you need to convert it into integer with intval() or floatval().
$newNumber = intval(strip_tags($xml->asXML()));
sendmail
works for me on the mac (10.6.8)
echo "Hello" | sendmail -f [email protected] [email protected]
(Added 26 Sept. 2020)
On 24 Oct. 2009, as @pixelbeat first pointed out here, Bruno Haible empirically discovered the following default thread stack sizes for several systems. He said that in a multithreaded program, "the default thread stack size is:"
- glibc i386, x86_64 7.4 MB - Tru64 5.1 5.2 MB - Cygwin 1.8 MB - Solaris 7..10 1 MB - MacOS X 10.5 460 KB - AIX 5 98 KB - OpenBSD 4.0 64 KB - HP-UX 11 16 KB
Note that the above units are all in MB and KB (base 1000 numbers), NOT MiB and KiB (base 1024 numbers). I've proven this to myself by verifying the 7.4 MB case.
He also stated that:
32 KB is more than you can safely allocate on the stack in a multithreaded program
And he said:
And the default stack size for sigaltstack, SIGSTKSZ, is
- only 16 KB on some platforms: IRIX, OSF/1, Haiku.
- only 8 KB on some platforms: glibc, NetBSD, OpenBSD, HP-UX, Solaris.
- only 4 KB on some platforms: AIX.
Bruno
He wrote the following simple Linux C program to empirically determine the above values. You can run it on your system today to quickly see what your maximum thread stack size is, or you can run it online on GDBOnline here: https://onlinegdb.com/rkO9JnaHD.
Explanation: It simply creates a single new thread, so as to check the thread stack size and NOT the program stack size, in case they differ, then it has that thread repeatedly allocate 128 bytes of memory on the stack (NOT the heap), using the Linux alloca()
call, after which it writes a 0 to the first byte of this new memory block, and then it prints out how many total bytes it has allocated. It repeats this process, allocating 128 more bytes on the stack each time, until the program crashes with a Segmentation fault (core dumped)
error. The last value printed is the estimated maximum thread stack size allowed for your system.
Important note: alloca()
allocates on the stack: even though this looks like dynamic memory allocation onto the heap, similar to a malloc()
call, alloca()
does NOT dynamically allocate onto the heap. Rather, alloca()
is a specialized Linux function to "pseudo-dynamically" (I'm not sure what I'd call this, so that's the term I chose) allocate directly onto the stack as though it was statically-allocated memory. Stack memory used and returned by alloca()
is scoped at the function-level, and is therefore "automatically freed when the function that called alloca()
returns to its caller." That's why its static scope isn't exited and memory allocated by alloca()
is NOT freed each time a for
loop iteration is completed and the end of the for
loop scope is reached. See man 3 alloca
for details. Here's the pertinent quote (emphasis added):
DESCRIPTION
Thealloca()
function allocates size bytes of space in the stack frame of the caller. This temporary space is automatically freed when the function that calledalloca()
returns to its caller.RETURN VALUE
Thealloca()
function returns a pointer to the beginning of the allocated space. If the allocation causes stack overflow, program behavior is undefined.
Here is Bruno Haible's program from 24 Oct. 2009, copied directly from the GNU mailing list here:
Again, you can run it live online here.
// By Bruno Haible
// 24 Oct. 2009
// Source: https://lists.gnu.org/archive/html/bug-coreutils/2009-10/msg00262.html
// =============== Program for determining the default thread stack size =========
#include <alloca.h>
#include <pthread.h>
#include <stdio.h>
void* threadfunc (void*p) {
int n = 0;
for (;;) {
printf("Allocated %d bytes\n", n);
fflush(stdout);
n += 128;
*((volatile char *) alloca(128)) = 0;
}
}
int main()
{
pthread_t thread;
pthread_create(&thread, NULL, threadfunc, NULL);
for (;;) {}
}
When I run it on GDBOnline using the link above, I get the exact same results each time I run it, as both a C and a C++17 program. It takes about 10 seconds or so to run. Here are the last several lines of the output:
Allocated 7449856 bytes Allocated 7449984 bytes Allocated 7450112 bytes Allocated 7450240 bytes Allocated 7450368 bytes Allocated 7450496 bytes Allocated 7450624 bytes Allocated 7450752 bytes Allocated 7450880 bytes Segmentation fault (core dumped)
So, the thread stack size is ~7.45 MB for this system, as Bruno mentioned above (7.4 MB).
I've made a few changes to the program, mostly just for clarity, but also for efficiency, and a bit for learning.
Summary of my changes:
[learning] I passed in BYTES_TO_ALLOCATE_EACH_LOOP
as an argument to the threadfunc()
just for practice passing in and using generic void*
arguments in C.
[efficiency] I made the main thread sleep instead of wastefully spinning.
[clarity] I added more-verbose variable names, such as BYTES_TO_ALLOCATE_EACH_LOOP
and bytes_allocated
.
[clarity] I changed this:
*((volatile char *) alloca(128)) = 0;
to this:
volatile uint8_t * byte_buff =
(volatile uint8_t *)alloca(BYTES_TO_ALLOCATE_EACH_LOOP);
byte_buff[0] = 0;
Here is my modified test program, which does exactly the same thing as Bruno's, and even has the same results:
You can run it online here, or download it from my repo here. If you choose to run it locally from my repo, here's the build and run commands I used for testing:
Build and run it as a C program:
mkdir -p bin && \
gcc -Wall -Werror -g3 -O3 -std=c11 -pthread -o bin/tmp \
onlinegdb--empirically_determine_max_thread_stack_size_GS_version.c && \
time bin/tmp
Build and run it as a C++ program:
mkdir -p bin && \
g++ -Wall -Werror -g3 -O3 -std=c++17 -pthread -o bin/tmp \
onlinegdb--empirically_determine_max_thread_stack_size_GS_version.c && \
time bin/tmp
It takes < 0.5 seconds to run locally on a fast computer with a thread stack size of ~7.4 MB.
Here's the program:
// =============== Program for determining the default thread stack size =========
// Modified by Gabriel Staples, 26 Sept. 2020
// Originally by Bruno Haible
// 24 Oct. 2009
// Source: https://lists.gnu.org/archive/html/bug-coreutils/2009-10/msg00262.html
#include <alloca.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h> // sleep
/// Thread function to repeatedly allocate memory within a thread, printing
/// the total memory allocated each time, until the program crashes. The last
/// value printed before the crash indicates how big a thread's stack size is.
void* threadfunc(void* bytes_to_allocate_each_loop)
{
const uint32_t BYTES_TO_ALLOCATE_EACH_LOOP =
*(uint32_t*)bytes_to_allocate_each_loop;
uint32_t bytes_allocated = 0;
while (true)
{
printf("bytes_allocated = %u\n", bytes_allocated);
fflush(stdout);
// NB: it appears that you don't necessarily need `volatile` here,
// but you DO definitely need to actually use (ex: write to) the
// memory allocated by `alloca()`, as we do below, or else the
// `alloca()` call does seem to get optimized out on some systems,
// making this whole program just run infinitely forever without
// ever hitting the expected segmentation fault.
volatile uint8_t * byte_buff =
(volatile uint8_t *)alloca(BYTES_TO_ALLOCATE_EACH_LOOP);
byte_buff[0] = 0;
bytes_allocated += BYTES_TO_ALLOCATE_EACH_LOOP;
}
}
int main()
{
const uint32_t BYTES_TO_ALLOCATE_EACH_LOOP = 128;
pthread_t thread;
pthread_create(&thread, NULL, threadfunc,
(void*)(&BYTES_TO_ALLOCATE_EACH_LOOP));
while (true)
{
const unsigned int SLEEP_SEC = 10000;
sleep(SLEEP_SEC);
}
return 0;
}
Sample output (same results as Bruno Haible's original program):
bytes_allocated = 7450240 bytes_allocated = 7450368 bytes_allocated = 7450496 bytes_allocated = 7450624 bytes_allocated = 7450752 bytes_allocated = 7450880 Segmentation fault (core dumped)
var expanded = false;_x000D_
_x000D_
function showCheckboxes() {_x000D_
var checkboxes = document.getElementById("checkboxes");_x000D_
if (!expanded) {_x000D_
checkboxes.style.display = "block";_x000D_
expanded = true;_x000D_
} else {_x000D_
checkboxes.style.display = "none";_x000D_
expanded = false;_x000D_
}_x000D_
}
_x000D_
.multiselect {_x000D_
width: 200px;_x000D_
}_x000D_
_x000D_
.selectBox {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.selectBox select {_x000D_
width: 100%;_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
.overSelect {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
}_x000D_
_x000D_
#checkboxes {_x000D_
display: none;_x000D_
border: 1px #dadada solid;_x000D_
}_x000D_
_x000D_
#checkboxes label {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
#checkboxes label:hover {_x000D_
background-color: #1e90ff;_x000D_
}
_x000D_
<form>_x000D_
<div class="multiselect">_x000D_
<div class="selectBox" onclick="showCheckboxes()">_x000D_
<select>_x000D_
<option>Select an option</option>_x000D_
</select>_x000D_
<div class="overSelect"></div>_x000D_
</div>_x000D_
<div id="checkboxes">_x000D_
<label for="one">_x000D_
<input type="checkbox" id="one" />First checkbox</label>_x000D_
<label for="two">_x000D_
<input type="checkbox" id="two" />Second checkbox</label>_x000D_
<label for="three">_x000D_
<input type="checkbox" id="three" />Third checkbox</label>_x000D_
</div>_x000D_
</div>_x000D_
</form>
_x000D_
I have faced the same issue and resolved as follows (if you have a project in local folder then follow the steps):
This error also comes when you run the command
node filename.ts
and not
node filename.js
To simply put, with node command we will have to run the JavaScript file (filename.js) and not the TypeScript file unless we are using a package like ts-node
YourAdapter yourAdapter =
new YourAdapter (getActivity(),
R.layout.list_view_item,arrData);
yourAdapter .setDropDownViewResource(R.layout.list_view_item);
mySpinner.setAdapter(yourAdapter );
String strCompare = "Indonesia";
for (int i = 0; i < arrData.length ; i++){
if(arrData[i].getCode().equalsIgnoreCase(strCompare)){
int spinnerPosition = yourAdapter.getPosition(arrData[i]);
mySpinner.setSelection(spinnerPosition);
}
}
There is another way to install the pip3: just reinstall 3.6.
Using sindresorhus's fkill tool, you can do this:
$ fkill :3000
We have used messaging to generate online Quotes
See the query below (assumed @dt1 >= @dt2);
Declare @dt1 datetime = '2013-7-3'
Declare @dt2 datetime = '2013-5-2'
select abs(DATEDIFF(DD, @dt2, @dt1)) Days,
case when @dt1 >= @dt2
then case when DAY(@dt2)<=DAY(@dt1)
then Convert(varchar, DATEDIFF(MONTH, @dt2, @dt1)) + CONVERT(varchar, ' Month(s) ') + Convert(varchar, DAY(@dt1)-DAY(@dt2)) + CONVERT(varchar, 'Day(s).')
else Convert(varchar, DATEDIFF(MONTH, @dt2, @dt1)-1) + CONVERT(varchar, ' Month(s) ') + convert(varchar, abs(DATEDIFF(DD, @dt1, DateAdd(Month, -1, @dt1))) - (DAY(@dt2)-DAY(@dt1))) + CONVERT(varchar, 'Day(s).')
end
else 'See asumption: @dt1 must be >= @dt2'
end In_Months_Days
Returns:
Days | In_Months_Days
62 | 2 Month(s) 1Day(s).
The ActivityManager class is the appropriate tool to see which processes are running.
To run in the background, you typically want to use a Service.
If you need to do something on the front end you can respond to the onsubmit event of your form. If you are just posting to admin/start you can access post variables in your view through the request object. request.POST which is a dictionary of post variables
For Gradle look here: https://docs.gradle.org/current/dsl/org.gradle.api.tasks.SourceSetOutput.html. "For example: Java plugin will use those dirs in calculating class paths and for jarring the content; IDEA and Eclipse plugins will put those folders on relevant classpath."
So its depend on plugin build in configs unless you don't define them explicit in config file.
git for-each-ref --format='%(authorname) %09 -%(refname)' | sort
If you are using MinGW, the problem is that by default, MinGW uses the I/O resp. formatting functions from the Microsoft C runtime, which doesn't support 80 bit floating point numbers (long double
== double
in Microsoft land).
However, MinGW also comes with a set of alternative implementations that do properly support long doubles. To use them, prefix the function names with __mingw_
(e.g. __mingw_printf
). Depending on the nature of your project, you might also want to globally #define printf __mingw_printf
or use -D__USE_MINGW_ANSI_STDIO
(which enables the MinGW versions of all the printf
-family functions).
In my case, I had to add using System.Data.Entity;
The command uptime
gives you load averages for the past 1, 5, and 15 minutes.
your device older than minSDK
, edit minSdkVersion
in build.gradle
I found a solution for this in my case, try to update the NuGet Package Manager.
To do this:
This let me install packages without problem again.
Hope this helps!
Both console.log("story" + name + "story")
and console.log("story", name, "story")
works just fine as mentioned in earlier answers.
I will still suggest of having a habit of console.log("story", name, "story")
, because, if trying to print the object contents, like json object, having "story" + objectVariable + "story"
will convert it into string.
This will have output like : "story" [object Object] "story"
.
Just a good practice.
I always just use echo "<script> function(); </script>";
or something similar. you're not technically calling the function in PHP, but this as close as your going to get.
$(document).ready(function() {
$('#Button').click(function() {
$(this).addClass('active');
});
});
should do the trick. unless you're loading the button with ajax. In which case you could do:
$('#Button').live('click', function() {...
Also remember not to use the same id more than once in your html code.
You can use Reflection:
<?php
$array = ['name'=>'maria','age'=>33];
class Person {
public $name;
public $age;
public function __construct(string $name, string $age){
$this->name = $name;
$this->age = $age;
}
}
function arrayToObject(array $array, string $class_name){
$r = new ReflectionClass($class_name);
$object = $r->newInstanceWithoutConstructor();
$list = $r->getProperties();
foreach($list as $prop){
$prop->setAccessible(true);
if(isset($array[$prop->name]))
$prop->setValue($object, $array[$prop->name]);
}
return $object;
}
$pessoa1 = arrayToObject($array, 'Person');
var_dump($pessoa1);
You can update a Hive partition by, for example:
ALTER TABLE logs PARTITION(year = 2012, month = 12, day = 18)
SET LOCATION 'hdfs://user/darcy/logs/2012/12/18';
This command does not move the old data, nor does it delete the old data. It simply sets the partition to the new location.
To drop a partition, you can do
ALTER TABLE logs DROP IF EXISTS PARTITION(year = 2012, month = 12, day = 18);
Hope it helps!
select * from my_table where my_field Like '[a-z][a-z]%'
Aw, heck -- I'll toss in a simple library-less version. Feel free to improve on it[*]:
def frange(start=0, stop=1, jump=0.1):
nsteps = int((stop-start)/jump)
dy = stop-start
# f(i) goes from start to stop as i goes from 0 to nsteps
return [start + float(i)*dy/nsteps for i in range(nsteps)]
The core idea is that nsteps
is the number of steps to get you from start to stop and range(nsteps)
always emits integers so there's no loss of accuracy. The final step is to map [0..nsteps] linearly onto [start..stop].
If, like alancalvitti you'd like the series to have exact rational representation, you can always use Fractions:
from fractions import Fraction
def rrange(start=0, stop=1, jump=0.1):
nsteps = int((stop-start)/jump)
return [Fraction(i, nsteps) for i in range(nsteps)]
[*] In particular, frange()
returns a list, not a generator. But it sufficed for my needs.
The RareCpp library makes for fairly easy and intuitive reflection - all field/type information is designed to either be available in arrays or to feel like array access. It's written for C++17 and works with Visual Studios, g++, and Clang. The library is header only, meaning you need only copy "Reflect.h" into your project to use it.
Reflected structs or classes need the REFLECT macro, where you supply the name of the class you're reflecting and the names of the fields.
class FuelTank {
public:
float capacity;
float currentLevel;
float tickMarks[2];
REFLECT(FuelTank, capacity, currentLevel, tickMarks)
};
That's all there is, no additional code is needed to setup reflection. Optionally you can supply superclasses (in the parenthesis of the first argument) and field annotations (in the parenthesis preceeding the field you want to annotate) to be able to traverse superclasses or add additional compile-time information to a field (such as Json::Ignore).
Looping through fields can be as simple as...
for ( size_t i=0; i<FuelTank::Class::TotalFields; i++ )
std::cout << FuelTank::Class::Fields[i].name << std::endl;
You can loop through an object instance to access field values (which you can read or modify) and field type information...
FuelTank::Class::ForEachField(fuelTank, [&](auto & field, auto & value) {
using Type = typename std::remove_reference<decltype(value)>::type;
std::cout << TypeToStr<Type>() << " " << field.name << ": " << value << std::endl;
});
A JSON Library is built on top of RandomAccessReflection which auto identifies appropriate JSON output representations for reading or writing, and can recursively traverse any reflected fields, as well as arrays and STL containers.
struct MyOtherObject { int myOtherInt; REFLECT(MyOtherObject, myOtherInt) };
struct MyObject
{
int myInt;
std::string myString;
MyOtherObject myOtherObject;
std::vector<int> myIntCollection;
REFLECT(MyObject, myInt, myString, myOtherObject, myIntCollection)
};
int main()
{
MyObject myObject = {};
std::cout << "Enter MyObject:" << std::endl;
std::cin >> Json::in(myObject);
std::cout << std::endl << std::endl << "You entered:" << std::endl;
std::cout << Json::pretty(myObject);
}
The above could be ran like so...
Enter MyObject:
{
"myInt": 1337, "myString": "stringy", "myIntCollection": [2,4,6],
"myOtherObject": {
"myOtherInt": 9001
}
}
You entered:
{
"myInt": 1337,
"myString": "stringy",
"myOtherObject": {
"myOtherInt": 9001
},
"myIntCollection": [ 2, 4, 6 ]
}
See also...
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath);
After this you may use the below line to avoid error..(access denied etc.)
request.Proxy = null;
Take a look here in order to get started: http://instagram.com/developer/
and then in order to retrieve pictures by tag, look here: http://instagram.com/developer/endpoints/tags/
Getting tags from Instagram doesn't require OAuth, so you can make the calls via these URLs:
GET IMAGES
https://api.instagram.com/v1/tags/{tag-name}/media/recent?access_token={TOKEN}
SEARCH
https://api.instagram.com/v1/tags/search?q={tag-query}&access_token={TOKEN}
TAG INFO
https://api.instagram.com/v1/tags/{tag-name}?access_token={TOKEN}
If you attempt to commit, and if there are conflicts, then git will give you the list of the currently unresolved conflicts... but not as a plain list. This is usually what you want when working interactively because the list gets shorter as you fix the conflicts.
My solution handles quotes, overriding field and string separators, etc. It is short and sweet.
public static string[] CSVRowToStringArray(string r, char fieldSep = ',', char stringSep = '\"')
{
bool bolQuote = false;
StringBuilder bld = new StringBuilder();
List<string> retAry = new List<string>();
foreach (char c in r.ToCharArray())
if ((c == fieldSep && !bolQuote))
{
retAry.Add(bld.ToString());
bld.Clear();
}
else
if (c == stringSep)
bolQuote = !bolQuote;
else
bld.Append(c);
return retAry.ToArray();
}
<a href="#anchor">Click me!</a>
<div style="margin-top: -100px; padding-top: 100px;" id="anchor"></div>
<p>I should be 100px below where I currently am!</p>
<form>
syn<input type="checkbox" name="checkfield" id="g01-01" />
</form>
js:
$('#g01-01').on('change',function(){
var _val = $(this).is(':checked') ? 'checked' : 'unchecked';
alert(_val);
});
Create a zip file, then download the file, by setting the header, read the zip contents and output the file.
http://www.php.net/manual/en/function.ziparchive-addfile.php
Anyone coming here:
Remove all migrations Remove db.sqlite file
redo migrations
Right, printf
could be thought of as a more powerful version of puts
. printf
provides the ability to format variables for output using format specifiers such as %s
, %d
, %lf
, etc...
Here you can simply use:
SendKeys "{ENTER}"
at the end of code linked to the Username field.
And so you can skip pressing ENTER Key once (one time).
And as a result, the next button ("Log In" button here) will be activated. And when you press ENTER once (your desired outcome), It will run code which is linked with "Log In" button.
Okay, but you all know that the * is a wildcard and allows cross site scripting from every domain?
You would like to send multiple Access-Control-Allow-Origin
headers for every site that's allowed to - but unfortunately its officially not supported to send multiple Access-Control-Allow-Origin
headers, or to put in multiple origins.
You can solve this by checking the origin, and sending back that one in the header, if it is allowed:
$origin = $_SERVER['HTTP_ORIGIN'];
$allowed_domains = [
'http://mysite1.com',
'https://www.mysite2.com',
'http://www.mysite2.com',
];
if (in_array($origin, $allowed_domains)) {
header('Access-Control-Allow-Origin: ' . $origin);
}
Thats much safer. You might want to edit the matching and change it to a manual function with some regex, or something like that. At least this will only send back 1 header, and you will be sure its the one that the request came from. Please do note that all HTTP headers can be spoofed, but this header is for the client's protection. Don't protect your own data with those values. If you want to know more, read up a bit on CORS and CSRF.
Why is it safer?
Allowing access from other locations then your own trusted site allows for session highjacking. I'm going to go with a little example - image Facebook allows a wildcard origin - this means that you can make your own website somewhere, and make it fire AJAX calls (or open iframes) to facebook. This means you can grab the logged in info of the facebook of a visitor of your website. Even worse - you can script POST
requests and post data on someone's facebook - just while they are browsing your website.
Be very cautious when using the ACAO
headers!
For other shell newbies trying to fix the PATH variable
After following instructions in accepted answer, check and modify your PATH variable if necessary :
env | grep PATH
if you see "rvm" anywhere, you need to figure out where you are setting PATH and modify. I was setting it in 3 files - so check all the following files:
vim .bashrc
Delete the lines in the file referencing rvm using the dd command. :wq to save and exit.
source .bashrc
to "reload"
Repeat this process (starting with the vim command) for .profile and .bash_profile
$('#myForm').on('change', 'input[type=checkbox]', function() {
this.checked ? this.value = 'apple' : this.value = 'pineapple';
});
I've just seen this problem myself, Jboss AS7 with jdk1.5.0_09. Update System Property JAVA_HOME to jdk1.7+ to fix (I'm using jdk1.7.0_67).
This is a solution for Python based selenium, after going through the source code (here). I found this 3 steps as useful.
obj = driver.switch_to.alert
obj.send_keys(keysToSend="username\ue004password")
obj.accept()
Here \ue004 is the value for TAB which you can find in Keys class in the source code.
I guess the same approach can be used in JAVA as well but not sure.
I think this sample explains the difference between the styles:
james@bodacious-wired:~$cat test.py
#!/usr/bin/env python
class MyClass:
element1 = "Hello"
def __init__(self):
self.element2 = "World"
obj = MyClass()
print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello World
Hello
Traceback (most recent call last):
File "./test.py", line 17, in <module>
print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'
element1 is bound to the class, element2 is bound to an instance of the class.
Here's the link that gives me the answer and we use gmail:
Install the "fake sendmail for windows". If you are not using XAMPP you can download it here: http://glob.com.au/sendmail/sendmail.zip
Modify the php.ini file to use it (commented out the other lines):
For Win32 only.
SMTP = smtp.gmail.com
smtp_port = 25
For Win32 only.
sendmail_from = <e-mail username>@gmail.com
For Unix only.
You may supply arguments as well (default: sendmail -t -i
).
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
(ignore the "Unix only" bit, since we actually are using sendmail)
You then have to configure the "sendmail.ini" file in the directory where sendmail was installed:
smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
auth_username=<username>
auth_password=<password>
force_sender=<e-mail username>@gmail.com
Here is the difference:
Imperative:
... and so on and on ...
Declarative, whereof functional is a subcategory:
... and so on and on ...
Summary: In imperative languages you tell the computer how to change bits, bytes and words in it's memory and in what order. In functional ones, we tell the computer what things, actions etc. are. For example, we say that the factorial of 0 is 1, and the factorial of every other natural number is the product of that number and the factorial of its predecessor. We don't say: To compute the factorial of n, reserve a memory region and store 1 there, then multiply the number in that memory region with the numbers 2 to n and store the result at the same place, and at the end, the memory region will contain the factorial.
I had this problem: My Web API 2 project on .NET 4.7.2 was working as expected, then I changed the project properties to use a Specific Page path under the Web tab. When I ran it every time since, it was giving me a 404 error - it didn't even hit the controller.
Solution: I found the .vs hidden folder in my parent directory of my VS solution file (sometimes the same directory), and deleted it. When I opened my VS solution once more, cleaned it, and rebuilt it with the Rebuild option, it ran again. There was a problem with the cached files created by Visual Studio. When these were deleted, and the solution was rebuilt, the files were recreated.
If you don't mind adding a new library in your code you can generate characters with MockNeat (disclaimer: I am one of the authors).
MockNeat mock = MockNeat.threadLocal();
Character chr = mock.chars().val();
Character lowerLetter = mock.chars().lowerLetters().val();
Character upperLetter = mock.chars().upperLetters().val();
Character digit = mock.chars().digits().val();
Character hex = mock.chars().hex().val();
I posted a similar question about checking if byte[] is full of zeroes. (SIMD code was beaten so I removed it from this answer.) Here is fastest code from my comparisons:
static unsafe bool EqualBytesLongUnrolled (byte[] data1, byte[] data2)
{
if (data1 == data2)
return true;
if (data1.Length != data2.Length)
return false;
fixed (byte* bytes1 = data1, bytes2 = data2) {
int len = data1.Length;
int rem = len % (sizeof(long) * 16);
long* b1 = (long*)bytes1;
long* b2 = (long*)bytes2;
long* e1 = (long*)(bytes1 + len - rem);
while (b1 < e1) {
if (*(b1) != *(b2) || *(b1 + 1) != *(b2 + 1) ||
*(b1 + 2) != *(b2 + 2) || *(b1 + 3) != *(b2 + 3) ||
*(b1 + 4) != *(b2 + 4) || *(b1 + 5) != *(b2 + 5) ||
*(b1 + 6) != *(b2 + 6) || *(b1 + 7) != *(b2 + 7) ||
*(b1 + 8) != *(b2 + 8) || *(b1 + 9) != *(b2 + 9) ||
*(b1 + 10) != *(b2 + 10) || *(b1 + 11) != *(b2 + 11) ||
*(b1 + 12) != *(b2 + 12) || *(b1 + 13) != *(b2 + 13) ||
*(b1 + 14) != *(b2 + 14) || *(b1 + 15) != *(b2 + 15))
return false;
b1 += 16;
b2 += 16;
}
for (int i = 0; i < rem; i++)
if (data1 [len - 1 - i] != data2 [len - 1 - i])
return false;
return true;
}
}
Measured on two 256MB byte arrays:
UnsafeCompare : 86,8784 ms
EqualBytesSimd : 71,5125 ms
EqualBytesSimdUnrolled : 73,1917 ms
EqualBytesLongUnrolled : 39,8623 ms
This SQL Server User Defined Function resolves the problem efficiently.No recursion, no complex loops. It takes a very short time to generate.
ALTER FUNCTION [GA].[udf_GenerateCalendar]
(
@StartDate DATE -- StartDate
, @EndDate DATE -- EndDate
)
RETURNS @Results TABLE
(
Date DATE
)
AS
/**********************************************************
Purpose: Generate a sequence of dates based on StartDate and EndDate
***********************************************************/
BEGIN
DECLARE @counter INTEGER = 1
DECLARE @days table(
day INTEGER NOT NULL
)
DECLARE @months table(
month INTEGER NOT NULL
)
DECLARE @years table(
year INTEGER NOT NULL
)
DECLARE @calendar table(
Date DATE NOT NULL
)
-- Populate generic days
SET @counter = 1
WHILE @counter <= 31
BEGIN
INSERT INTO @days
SELECT @counter dia
SELECT @counter = @counter + 1
END
-- Populate generic months
SET @counter = 1
WHILE @counter <= 12
BEGIN
INSERT INTO @months
SELECT @counter month
SELECT @counter = @counter + 1
END
-- Populate generic years
SET @counter = YEAR(@StartDate)
WHILE @counter <= YEAR(@EndDate)
BEGIN
INSERT INTO @years
SELECT @counter year
SELECT @counter = @counter + 1
END
INSERT @calendar (Date)
SELECT Date
FROM (
SELECT
CONVERT(Date, [Date], 102) AS Date
FROM (
SELECT
CAST(
y.year * 10000
+ m.month * 100
+ d.day
AS VARCHAR(8)) AS Date
FROM @days d, @months m, @years y
WHERE
ISDATE(CAST(
y.year * 10000
+ m.month * 100
+ d.day
AS VARCHAR(8))
) = 1
) A
) A
INSERT @Results (Date)
SELECT Date
FROM @calendar
WHERE Date BETWEEN @StartDate AND @EndDate
RETURN
/*
DECLARE @StartDate DATE = '2015-08-01'
DECLARE @EndDate DATE = '2015-08-31'
select * from [GA].[udf_GenerateCalendar](@StartDate, @EndDate)
*/
END
Getting only the instance attributes is easy.
But getting also the class attributes without the functions is a bit more tricky.
If you only have to list instance attributes just use
for attribute, value in my_instance
.__dict__
.items()
>>> from __future__ import (absolute_import, division, print_function)
>>> class MyClass(object):
... def __init__(self):
... self.a = 2
... self.b = 3
... def print_instance_attributes(self):
... for attribute, value in self.__dict__.items():
... print(attribute, '=', value)
...
>>> my_instance = MyClass()
>>> my_instance.print_instance_attributes()
a = 2
b = 3
>>> for attribute, value in my_instance.__dict__.items():
... print(attribute, '=', value)
...
a = 2
b = 3
To get also the class attributes without the functions, the trick is to use callable()
.
But static methods are not always callable
!
Therefore, instead of using callable(value)
use
callable
(getattr
(MyClass, attribute))
from __future__ import (absolute_import, division, print_function)
class MyClass(object):
a = "12"
b = "34" # class attributes
def __init__(self, c, d):
self.c = c
self.d = d # instance attributes
@staticmethod
def mystatic(): # static method
return MyClass.b
def myfunc(self): # non-static method
return self.a
def print_instance_attributes(self):
print('[instance attributes]')
for attribute, value in self.__dict__.items():
print(attribute, '=', value)
def print_class_attributes(self):
print('[class attributes]')
for attribute in self.__dict__.keys():
if attribute[:2] != '__':
value = getattr(self, attribute)
if not callable(value):
print(attribute, '=', value)
v = MyClass(4,2)
v.print_class_attributes()
v.print_instance_attributes()
Note: print_class_attributes()
should be @staticmethod
but not in this stupid and simple example.
$ python2 ./print_attributes.py
[class attributes]
a = 12
b = 34
[instance attributes]
c = 4
d = 2
$ python3 ./print_attributes.py
[class attributes]
b = 34
a = 12
[instance attributes]
c = 4
d = 2
WebElement element = driver.findElement(locator);
Assert.assertNull(element);
The above assertion will pass if element is not present.
Just add this below one line code in the XML file of that corresponding activity:
android:background="@android:color/black"
it will help you for sure.
For dynamically center
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
/*link*/
$q.when(scope.regions).then(function(result) {
console.log(result);
});
var Regions = $resource('mocks/regions.json');
$scope.regions = Regions.query().$promise.then(function(response) {
return response;
});
Try this instead:
SUM(CASE WHEN ValueDate > @startMonthDate THEN cash ELSE 0 END)
Explanation
Your CASE expression has incorrect syntax. It seems you are confusing the simple CASE expression syntax with the searched CASE expression syntax. See the documentation for CASE:
The CASE expression has two formats:
- The simple CASE expression compares an expression to a set of simple expressions to determine the result.
- The searched CASE expression evaluates a set of Boolean expressions to determine the result.
You want the searched CASE expression syntax:
CASE
WHEN Boolean_expression THEN result_expression [ ...n ]
[ ELSE else_result_expression ]
END
As a side note, if performance is an issue you may find that this expression runs more quickly if you rewrite using a JOIN and GROUP BY instead of using a dependent subquery.
Actually you don't even need the block:
Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'
File.open(playlist_name, 'w').puts(music)
var fs = require('fs');
fs.writeFile(path + "\\message.txt", "Hello", function(err){
if (err) throw err;
console.log("success");
});
For example : read file and write to another file :
var fs = require('fs');
var path = process.cwd();
fs.readFile(path+"\\from.txt",function(err,data)
{
if(err)
console.log(err)
else
{
fs.writeFile(path+"\\to.text",function(erro){
if(erro)
console.log("error : "+erro);
else
console.log("success");
});
}
});
Yes obviously.
That’s because a locally installed composer will give first preference to composer.lock file over composer.json.
If lock file is not available in vcs the composer will point to composer.json file to install latest dependencies or versions.
The file composer.lock maintains dependency in more depth i.e it points to the actual commit of the version of the package we include in our software, hence this is one of the most important files which handles the dependency more finely.
When you read in the year month day hour minutes with something like nextInt()
it leaves rest of the line in the parser/buffer (even if it is blank) so when you call nextLine()
you are reading the rest of this first line.
I suggest you to use scan.next()
instead of scan.nextLine()
.
I'd prefer to use [:punct:]
for that. Also, a-zA-Z09-9
could be just [:alnum:]
:
[[ $TEST =~ ^[[:alnum:][:blank:][:punct:]]+$ ]]
in your shell script (or .bashrc
) you may use somthing like:
umask 022
umask
is a command that determines the settings of a mask that controls how file permissions are set for newly created files.
echo $PATH
and copy it's valueexport PATH=""
export PATH="/path/you/want/to/keep"
It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.
It is indeed possible to have PHP render partials and whole views, but I would not recommend it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.
I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.
Using PHP to render the view:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How the same problem can be solved with an API centric approach by outputting JSON like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
and in Angular you could do a get, and handle the response client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.
Omit the parenthesis:
ALTER TABLE User
ADD CONSTRAINT userProperties
FOREIGN KEY(properties)
REFERENCES Properties(ID)
Hello I can suggest you universal method. use recursion.
public static JSONObject function(JSONObject obj, String keyMain,String valueMain, String newValue) throws Exception {
// We need to know keys of Jsonobject
JSONObject json = new JSONObject()
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
// if object is just string we change value in key
if ((obj.optJSONArray(key)==null) && (obj.optJSONObject(key)==null)) {
if ((key.equals(keyMain)) && (obj.get(key).toString().equals(valueMain))) {
// put new value
obj.put(key, newValue);
return obj;
}
}
// if it's jsonobject
if (obj.optJSONObject(key) != null) {
function(obj.getJSONObject(key), keyMain, valueMain, newValue);
}
// if it's jsonarray
if (obj.optJSONArray(key) != null) {
JSONArray jArray = obj.getJSONArray(key);
for (int i=0;i<jArray.length();i++) {
function(jArray.getJSONObject(i), keyMain, valueMain, newValue);
}
}
}
return obj;
}
It should work. If you have questions, go ahead.. I'm ready.
Here's two options. I prefer the navigationAlt option since it involves less work in the end:
<html>_x000D_
_x000D_
<head>_x000D_
<style type="text/css">_x000D_
#navigation li {_x000D_
color: green;_x000D_
}_x000D_
#navigation li .navigationLevel2 {_x000D_
color: red;_x000D_
}_x000D_
#navigationAlt {_x000D_
color: green;_x000D_
}_x000D_
#navigationAlt ul {_x000D_
color: red;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<ul id="navigation">_x000D_
<li>Level 1 item_x000D_
<ul>_x000D_
<li class="navigationLevel2">Level 2 item</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
<ul id="navigationAlt">_x000D_
<li>Level 1 item_x000D_
<ul>_x000D_
<li>Level 2 item</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Chrome doesn't allow you to integrate two different localhost,that's why we are getting this error. You just have to include Microsoft Visual Studio Web Api Core package from nuget manager.And add the two lines of code in WebApi project's in your WebApiConfig.cs
file.
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
Then all done.
include() needs a full file path, relative to the file system's root directory.
This should work:
include_once("C:/xampp/htdocs/PoliticalForum/headerSite.php");
If you support IE, for versions of Internet Explorer 8 and above, this:
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7" />
Forces the browser to render as that particular version's standards. It is not supported for IE7 and below.
If you separate with semi-colon, it sets compatibility levels for different versions. For example:
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=9" />
Renders IE7 and IE8 as IE7, but IE9 as IE9. It allows for different levels of backwards compatibility. In real life, though, you should only chose one of the options:
<meta http-equiv="X-UA-Compatible" content="IE=8" />
This allows for much easier testing and maintenance. Although generally the more useful version of this is using Emulate:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
For this:
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
It forces the browser the render at whatever the most recent version's standards are.
For more information, there is plenty to read about on MSDN,
This function goes above and beyond other answers in two ways:
It attempts to generate colors as distinct as possible by finding which color out of 20 tries has the farthest Euclidean distance from the others in the HSV cone.
It allows you to restrict the hue, saturation, or value range, but it still attempts to pick colors as distinct as possible within that range.
It's not super efficient, but for reasonable values (who could even pick apart 100 colors easily?) It's fast enough.
/**
* Generates a random palette of HSV colors. Attempts to pick colors
* that are as distinct as possible within the desired HSV range.
*
* @param {number} [options.numColors=10] - the number of colors to generate
* @param {number[]} [options.hRange=[0,1]] - the maximum range for generated hue
* @param {number[]} [options.sRange=[0,1]] - the maximum range for generated saturation
* @param {number[]} [options.vRange=[0,1]] - the maximum range for generated value
* @param {number[][]}[options.exclude=[[0,0,0],[0,0,1]]] - colors to exclude
*
* @returns {number[][]} an array of HSV colors (each HSV color
* is a [hue, saturation, value] array)
*/
function randomHSVPalette(options) {
function random(min, max) {
return min + Math.random() * (max - min);
}
function HSVtoXYZ(hsv) {
var h = hsv[0];
var s = hsv[1];
var v = hsv[2];
var angle = h * Math.PI * 2;
return [Math.sin(angle) * s * v,
Math.cos(angle) * s * v,
v];
}
function distSq(a, b) {
var dx = a[0] - b[0];
var dy = a[1] - b[1];
var dz = a[2] - b[2];
return dx * dx + dy * dy + dz * dz;
}
if (!options) {
options = {};
}
var numColors = options.numColors || 10;
var hRange = options.hRange || [0, 1];
var sRange = options.sRange || [0, 1];
var vRange = options.vRange || [0, 1];
var exclude = options.exclude || [[0, 0, 0], [0, 0, 1]];
var points = exclude.map(HSVtoXYZ);
var result = [];
while (result.length < numColors) {
var bestHSV;
var bestXYZ;
var bestDist = 0;
for (var i = 0; i < 20; i++) {
var hsv = [random(hRange[0], hRange[1]), random(sRange[0], sRange[1]), random(vRange[0], vRange[1])];
var xyz = HSVtoXYZ(hsv);
var minDist = 10;
points.forEach(function(point) {
minDist = Math.min(minDist, distSq(xyz, point));
});
if (minDist > bestDist) {
bestHSV = hsv;
bestXYZ = xyz;
bestDist = minDist;
}
}
points.push(bestXYZ);
result.push(bestHSV);
}
return result;
}
function HSVtoRGB(hsv) {
var h = hsv[0];
var s = hsv[1];
var v = hsv[2];
var i = ~~(h * 6);
var f = h * 6 - i;
var p = v * (1 - s);
var q = v * (1 - f * s);
var t = v * (1 - (1 - f) * s);
v = ~~(255 * v);
p = ~~(255 * p);
q = ~~(255 * q);
t = ~~(255 * t);
switch (i % 6) {
case 0: return [v, t, p];
case 1: return [q, v, p];
case 2: return [p, v, t];
case 3: return [p, q, v];
case 4: return [t, p, v];
case 5: return [v, p, q];
}
}
function RGBtoCSS(rgb) {
var r = rgb[0];
var g = rgb[1];
var b = rgb[2];
var rgb = (r << 16) + (g << 8) + b;
return '#' + ('000000' + rgb.toString(16)).slice(-6);
}
ProjectionList pl = Projections.projectionList();
pl.add(Projections.property("id"));
pl.add(Projections.sqlProjection("abs(`pageNo`-" + pageNo + ") as diff", new String[] {"diff"}, types ), diff); ---- solution
crit.addOrder(Order.asc("diff"));
crit.setProjection(pl);
Here's a really quick trick: Let's say you wanna add p tag inside div tag.
<div>
<p><script>document.write(<variablename>)</script></p>
</div>
And that's it.
If you added JComponent
to already visible Container, then you have call
frame.getContentPane().validate();
frame.getContentPane().repaint();
for example
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(460, 500);
frame.setTitle("Circles generator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setVisible(true);
}
});
String input = JOptionPane.showInputDialog("Enter n:");
CustomComponents0 component = new CustomComponents0();
frame.add(component);
frame.getContentPane().validate();
frame.getContentPane().repaint();
}
static class CustomComponents0 extends JLabel {
private static final long serialVersionUID = 1L;
@Override
public Dimension getMinimumSize() {
return new Dimension(200, 100);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
@Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
}
}
}
Here is another simple way to do it
<a class="nav-link"
href='@Url.Action("Print1", "DeviceCertificates", new { Area = "Diagnostics"})\@Model.ID'>Print</a>
Where is @Model.ID
is a parameter
And here there is a second example.
<a class="nav-link"
href='@Url.Action("Print1", "DeviceCertificates", new { Area = "Diagnostics"})\@Model.ID?param2=ViewBag.P2¶m3=ViewBag.P3'>Print</a>
You can use the spool
command (SQL*Plus documentation, but one of many such commands SQL Developer also supports) to write results straight to disk. Each spool
can change the file that's being written to, so you can have several queries writing to different files just by putting spool
commands between them:
spool "\path\to\spool1.txt"
select /*csv*/ * from employees;
spool "\path\to\spool2.txt"
select /*csv*/ * from locations;
spool off;
You'd need to run this as a script (F5, or the second button on the command bar above the SQL Worksheet). You might also want to explore some of the formatting options and the set
command, though some of those do not translate to SQL Developer.
Since you mentioned CSV in the title I've included a SQL Developer-specific hint that does that formatting for you.
A downside though is that SQL Developer includes the query in the spool file, which you can avoid by having the commands and queries in a script file that you then run as a script.
There is now an import functionality on Android ICS 4.0.4.
First you must save your .vcf
file on a storage (USB storage, or SDcard).
Android will scan the selected storage to detect any .vcf
file and will import it on the selected address book.
The functionality is in the option menu of your contact list.
!Note: Be careful while doing this! Android will import EVERYTHING that is a .vcf
in your storage. It's all or nothing, and the consequence can be trashing your address book.
You may be interested in std::vector<bool>
(that is bit-packed) and std::bitset
It should be the simplest as requested.
#include <iostream>
#include <bitset>
using namespace std;
int main() {
bitset<8> bs = 5;
bitset<8> rev;
for(int ii=0; ii!= bs.size(); ++ii)
rev[bs.size()-ii-1] = bs[ii];
cerr << bs << " " << rev << endl;
}
Other options may be faster.
EDIT: I owe you a solution using std::vector<bool>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<bool> b{0,0,0,0,0,1,0,1};
reverse(b.begin(), b.end());
copy(b.begin(), b.end(), ostream_iterator<int>(cerr));
cerr << endl;
}
The second example requires c++0x extension (to initialize the array with {...}
). The advantage of using a bitset
or a std::vector<bool>
(or a boost::dynamic_bitset
) is that you are not limited to bytes or words but can reverse an arbitrary number of bits.
HTH
Here's full list of black dotlikes from unicode
● - ●
- Black Circle
⏺ - ⏺
- Black Circle for Record
⚫ - ⚫
- Medium Black Circle
⬤ - ⬤
- Black Large Circle
⧭ - ⧭
- Black Circle with Down Arrow
🞄 - 🞄
- Black Slightly Small Circle
• - •
- Bullet (also - •
- Message Waiting)
∙ - ∙
- Bullet Operator
⋅ - ⋅
- Dot Operator (also · - ·
- Middle Dot)
🌑 - 🌑
- New Moon Symbol
describe
may give you everything you want otherwise you can perform aggregations using groupby and pass a list of agg functions: http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once
In [43]:
df.describe()
Out[43]:
shopper_num is_martian number_of_items count_pineapples
count 14.0000 14 14.000000 14
mean 7.5000 0 3.357143 0
std 4.1833 0 6.452276 0
min 1.0000 False 0.000000 0
25% 4.2500 0 0.000000 0
50% 7.5000 0 0.000000 0
75% 10.7500 0 3.500000 0
max 14.0000 False 22.000000 0
[8 rows x 4 columns]
Note that some columns cannot be summarised as there is no logical way to summarise them, for instance columns containing string data
As you prefer you can transpose the result if you prefer:
In [47]:
df.describe().transpose()
Out[47]:
count mean std min 25% 50% 75% max
shopper_num 14 7.5 4.1833 1 4.25 7.5 10.75 14
is_martian 14 0 0 False 0 0 0 False
number_of_items 14 3.357143 6.452276 0 0 0 3.5 22
count_pineapples 14 0 0 0 0 0 0 0
[4 rows x 8 columns]
On windows 7, find
C:\Users\Simion\AppData\Roaming\Sublime Text 2\Packages\Color Scheme - Default
Find your color scheme file, open it, and find lineHighlight
.
Ex:
<key>lineHighlight</key>
<string>#ccc</string>
replace #ccc
with your preferred background color.
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate localDate = LocalDate.now();
System.out.println("Formatted Date: " + formatter.format(localDate));
Java 8 LocalDate
I guess you want to use Array.prototype.find Find will break itself when it finds your specific value in the array.
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries));
// { name: 'cherries', quantity: 5 }
I am not sure if intercepting function keys is possible, but I would avoid using function keys all together. Function keys are used by browsers to perform a variety of tasks, some of them quite common. For example, in Firefox on Linux, at least six or seven of the function keys are reserved for use by the browser:
The worst part is that different browsers on different operating systems use different keys for different things. That's a lot of differences to account for. You should stick to safer, less commonly used key combinations.
best and simple way to use native java Script which is one liner code.
document.querySelector('#id').click();
Just add 'id' to your html element like
<button id="myId1" ng-click="someFunction()"></button>
check condition in javascript code
if(condition) {
document.querySelector('#myId1').click();
}
class Student{
//instance variable or data members.
Map<Integer, List<Object>> mapp = new HashMap<Integer, List<Object>>();
Scanner s1 = new Scanner(System.in);
String name = s1.nextLine();
int regno ;
int mark1;
int mark2;
int total;
List<Object> list = new ArrayList<Object>();
mapp.put(regno,list); //what wrong in this part?
list.add(mark1);
list.add(mark2);**
//String mark2=mapp.get(regno)[2];
}
I got the same issue and after a lot of time spent on the search I found the solution
Just change your method especially // DownloadsProvider part
getpath()
to
@SuppressLint("NewApi") public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
// This is for checking Main Memory
if ("primary".equalsIgnoreCase(type)) {
if (split.length > 1) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
return Environment.getExternalStorageDirectory() + "/";
}
// This is for checking SD Card
} else {
return "storage" + "/" + docId.replace(":", "/");
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
String fileName = getFilePath(context, uri);
if (fileName != null) {
return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
}
String id = DocumentsContract.getDocumentId(uri);
if (id.startsWith("raw:")) {
id = id.replaceFirst("raw:", "");
File file = new File(id);
if (file.exists())
return id;
}
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
For more solution click on the link here
https://gist.github.com/HBiSoft/15899990b8cd0723c3a894c1636550a8
I hope will do the same for you!
RaYell's answer is good - it answers your question.
It seems to me though that you should really be creating an object keyed by labels with sub-objects as values:
var columns = {};
for (var i = 0; i < oFullResponse.results.length; i++) {
var key = oFullResponse.results[i].label;
columns[key] = {
sortable: true,
resizeable: true
};
}
// Now you can access column info like this.
columns['notes'].resizeable;
The above approach should be much faster and idiomatic than searching the entire object array for a key for each access.
As many said:
String phoneNumber = TelephonyManager.getDefault().getLine1Number();
The availability depends strictly on the carrier and the way the number is encoded on the SIM card. If it is hardcoded by the company that makes the SIMs or by the mobile carrier itself. This returns the same as in Settings->about phone.
AttendStar created a free add-on that suppresses the print dialog box and removes all headers and footers for most versions of Firefox.
https://addons.mozilla.org/en-US/firefox/addon/attendprint/
With that feature on you can use $('img').jqprint(); and jqprint for jquery will only print that image automatically called from your web application.
you don't need this code
<?php
function display()
{
echo "hello".$_POST["studentname"];
}
?>
Instead, you can check whether the form is submitted by checking the post variables using isset
.
here goes the code
if(isset($_POST)){
echo "hello ".$_POST['studentname'];
}
click here for the php manual for isset
This means the network is slow, and Chrome is replacing a web font (loaded with a @font-face
rule) with a local fallback.
By default, the text rendered with a web font is invisible until the font is downloaded (“flash of invisible text”). With this change, the user on a slow network could start reading right when the content is loaded instead of looking into the empty page for several seconds.
I did achieve this like so
form i {_x000D_
left: -25px;_x000D_
top: 23px;_x000D_
border: none;_x000D_
position: relative;_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
float: left;_x000D_
color: #29a038;_x000D_
}
_x000D_
<form>_x000D_
_x000D_
<i class="fa fa-link"></i>_x000D_
_x000D_
<div class="form-group string optional profile_website">_x000D_
<input class="string optional form-control" placeholder="http://your-website.com" type="text" name="profile[website]" id="profile_website">_x000D_
</div>_x000D_
_x000D_
<i class="fa fa-facebook"></i>_x000D_
<div class="form-group url optional profile_facebook_url">_x000D_
<input class="string url optional form-control" placeholder="http://facebook.com/your-account" type="url" name="profile[facebook_url]" id="profile_facebook_url">_x000D_
</div>_x000D_
_x000D_
<i class="fa fa-twitter"></i>_x000D_
<div class="form-group url optional profile_twitter_url">_x000D_
<input class="string url optional form-control" placeholder="http://twitter.com/your-account" type="url" name="profile[twitter_url]" id="profile_twitter_url">_x000D_
</div>_x000D_
_x000D_
<i class="fa fa-instagram"></i>_x000D_
<div class="form-group url optional profile_instagram_url">_x000D_
<input class="string url optional form-control" placeholder="http://instagram.com/your-account" type="url" name="profile[instagram_url]" id="profile_instagram_url">_x000D_
</div>_x000D_
_x000D_
<input type="submit" name="commit" value="Add profile">_x000D_
</form>
_x000D_
The result looks like this:
Please note that I am using Ruby on Rails so my resulting code looks a bit blown up. The view code in slim is actually very concise:
i.fa.fa-link
= f.input :website, label: false
i.fa.fa-facebook
= f.input :facebook_url, label: false
i.fa.fa-twitter
= f.input :twitter_url, label: false
i.fa.fa-instagram
= f.input :instagram_url, label: false
if there is no value inserted, the default value should be null,empty
In the table definition, make this datetime
column allows null, be not defining NOT NULL
:
...
DateTimeColumn DateTime,
...
I HAVE ALLOWED NULL VARIABLES THOUGH.
Then , just insert NULL
in this column:
INSERT INTO Table(name, datetimeColumn, ...)
VALUES('foo bar', NULL, ..);
Or, you can make use of the DEFAULT constaints:
...
DateTimeColumn DateTime DEFAULT NULL,
...
Then you can ignore it completely in the INSERT
statement and it will be inserted withe the NULL
value:
INSERT INTO Table(name, ...)
VALUES('foo bar', ..);
I would use two classes. Keep your test class and add a second class called testhover which you only add to those you want to hover - alongside the test class. This isn't directly what you asked but without more context it feels like the best solution and is possibly the cleanest and simplest way of doing it.
Example:
.test { border: 0px; }_x000D_
.testhover:hover { border: 1px solid red; }
_x000D_
<div class="test"> blah </div>_x000D_
<div class="test"> blah </div>_x000D_
<div class="test testhover"> blah </div>
_x000D_
I prefer this solution:
col = df.pop("Mid")
df.insert(0, col.name, col)
It's simpler to read and faster than other suggested answers.
def move_column_inplace(df, col, pos):
col = df.pop(col)
df.insert(pos, col.name, col)
Performance assessment:
For this test, the currently last column is moved to the front in each repetition. In-place methods generally perform better. While citynorman's solution can be made in-place, Ed Chum's method based on .loc
and sachinnm's method based on reindex
cannot.
While other methods are generic, citynorman's solution is limited to pos=0
. I didn't observe any performance difference between df.loc[cols]
and df[cols]
, which is why I didn't include some other suggestions.
I tested with python 3.6.8 and pandas 0.24.2 on a MacBook Pro (Mid 2015).
import numpy as np
import pandas as pd
n_cols = 11
df = pd.DataFrame(np.random.randn(200000, n_cols),
columns=range(n_cols))
def move_column_inplace(df, col, pos):
col = df.pop(col)
df.insert(pos, col.name, col)
def move_to_front_normanius_inplace(df, col):
move_column_inplace(df, col, 0)
return df
def move_to_front_chum(df, col):
cols = list(df)
cols.insert(0, cols.pop(cols.index(col)))
return df.loc[:, cols]
def move_to_front_chum_inplace(df, col):
col = df[col]
df.drop(col.name, axis=1, inplace=True)
df.insert(0, col.name, col)
return df
def move_to_front_elpastor(df, col):
cols = [col] + [ c for c in df.columns if c!=col ]
return df[cols] # or df.loc[cols]
def move_to_front_sachinmm(df, col):
cols = df.columns.tolist()
cols.insert(0, cols.pop(cols.index(col)))
df = df.reindex(columns=cols, copy=False)
return df
def move_to_front_citynorman_inplace(df, col):
# This approach exploits that reset_index() moves the index
# at the first position of the data frame.
df.set_index(col, inplace=True)
df.reset_index(inplace=True)
return df
def test(method, df):
col = np.random.randint(0, n_cols)
method(df, col)
col = np.random.randint(0, n_cols)
ret_mine = move_to_front_normanius_inplace(df.copy(), col)
ret_chum1 = move_to_front_chum(df.copy(), col)
ret_chum2 = move_to_front_chum_inplace(df.copy(), col)
ret_elpas = move_to_front_elpastor(df.copy(), col)
ret_sach = move_to_front_sachinmm(df.copy(), col)
ret_city = move_to_front_citynorman_inplace(df.copy(), col)
# Assert equivalence of solutions.
assert(ret_mine.equals(ret_chum1))
assert(ret_mine.equals(ret_chum2))
assert(ret_mine.equals(ret_elpas))
assert(ret_mine.equals(ret_sach))
assert(ret_mine.equals(ret_city))
Results:
# For n_cols = 11:
%timeit test(move_to_front_normanius_inplace, df)
# 1.05 ms ± 42.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit test(move_to_front_citynorman_inplace, df)
# 1.68 ms ± 46.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit test(move_to_front_sachinmm, df)
# 3.24 ms ± 96.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_chum, df)
# 3.84 ms ± 114 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_elpastor, df)
# 3.85 ms ± 58.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_chum_inplace, df)
# 9.67 ms ± 101 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# For n_cols = 31:
%timeit test(move_to_front_normanius_inplace, df)
# 1.26 ms ± 31.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_citynorman_inplace, df)
# 1.95 ms ± 260 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_sachinmm, df)
# 10.7 ms ± 348 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_chum, df)
# 11.5 ms ± 869 µs per loop (mean ± std. dev. of 7 runs, 100 loops each
%timeit test(move_to_front_elpastor, df)
# 11.4 ms ± 598 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_chum_inplace, df)
# 31.4 ms ± 1.89 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
As "@sarnold", aptly pointed out, any process can send signal to any other process, hence, one process can send SIGABORT to other process & in that case the receiving process is unable to distinguish whether its coming because of its own tweaking of memory etc, or someone else has "unicastly", send to it.
In one of the systems I worked there is one deadlock detector which actually detects if process is coming out of some task by giving heart beat or not. If not, then it declares the process is in deadlock state and sends SIGABORT to it.
I just wanted to share this prospective with reference to question asked.
If you are getting the output Optional(5) when trying to print the value of 5 in an optional Int or String, you should unwrap the value first:
if value != nil
{ print(value)
}
or you can use this:
if let value = text {
print(value)
}
or in simple just 1 line answer:
print(value ?? "")
The last line will check if variable 'value' has any value assigned to it, if not it will print empty string
Let us say your jsfunctions.js file has a function "display" and this file is stored in C:/Scripts/Jsfunctions.js
jsfunctions.js
var display = function(name) {
print("Hello, I am a Javascript display function",name);
return "display function return"
}
Now, in your java code, I would recommend you to use Java8 Nashorn. In your java class,
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
class Test {
public void runDisplay() {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try {
engine.eval(new FileReader("C:/Scripts/Jsfunctions.js"));
Invocable invocable = (Invocable) engine;
Object result;
result = invocable.invokeFunction("display", helloWorld);
System.out.println(result);
System.out.println(result.getClass());
} catch (FileNotFoundException | NoSuchMethodException | ScriptException e) {
e.printStackTrace();
}
}
}
Note: Get the absolute path of your javascript file and replace in FileReader() and run the java code. It should work.
It's not quite what you asked for, but
git log --graph --simplify-by-decoration --pretty=format:'%d' --all
does a pretty good job. It shows tags and remote branches as well. This may not be desirable for everyone, but I find it useful. --simplifiy-by-decoration
is the big trick here for limiting the refs shown.
I use a similar command to view my log. I've been able to completely replace my gitk
usage with it:
git log --graph --oneline --decorate --all
I use it by including these aliases in my ~/.gitconfig file:
[alias]
l = log --graph --oneline --decorate
ll = log --graph --oneline --decorate --branches --tags
lll = log --graph --oneline --decorate --all
Edit: Updated suggested log command/aliases to use simpler option flags.
In my opinion cherry-picking should be reserved for rare situations where it is required, for example if you did some fix on directly on 'master' branch (trunk, main development branch) and then realized that it should be applied also to 'maint'. You should base workflow either on merge, or on rebase (or "git pull --rebase").
Please remember that cherry-picked or rebased commit is different from the point of view of Git (has different SHA-1 identifier) than the original, so it is different than the commit in remote repository. (Rebase can usually deal with this, as it checks patch id i.e. the changes, not a commit id).
Also in git you can merge many branches at once: so called octopus merge. Note that octopus merge has to succeed without conflicts. Nevertheless it might be useful.
HTH.
There is now, two years after the question, an 'out-of-core' pandas equivalent: dask. It is excellent! Though it does not support all of pandas functionality, you can get really far with it. Update: in the past two years it has been consistently maintained and there is substantial user community working with Dask.
And now, four years after the question, there is another high-performance 'out-of-core' pandas equivalent in Vaex. It "uses memory mapping, zero memory copy policy and lazy computations for best performance (no memory wasted)." It can handle data sets of billions of rows and does not store them into memory (making it even possible to do analysis on suboptimal hardware).
An optional way if you want to use pure Python:
ElementTree is good for most cases, but it can't CData and pretty print.
So, if you need CData and pretty print you should use minidom:
minidom_example.py:
from xml.dom import minidom
doc = minidom.Document()
root = doc.createElement('root')
doc.appendChild(root)
leaf = doc.createElement('leaf')
text = doc.createTextNode('Text element with attributes')
leaf.appendChild(text)
leaf.setAttribute('color', 'white')
root.appendChild(leaf)
leaf_cdata = doc.createElement('leaf_cdata')
cdata = doc.createCDATASection('<em>CData</em> can contain <strong>HTML tags</strong> without encoding')
leaf_cdata.appendChild(cdata)
root.appendChild(leaf_cdata)
branch = doc.createElement('branch')
branch.appendChild(leaf.cloneNode(True))
root.appendChild(branch)
mixed = doc.createElement('mixed')
mixed_leaf = leaf.cloneNode(True)
mixed_leaf.setAttribute('color', 'black')
mixed_leaf.setAttribute('state', 'modified')
mixed.appendChild(mixed_leaf)
mixed_text = doc.createTextNode('Do not use mixed elements if it possible.')
mixed.appendChild(mixed_text)
root.appendChild(mixed)
xml_str = doc.toprettyxml(indent=" ")
with open("minidom_example.xml", "w") as f:
f.write(xml_str)
minidom_example.xml:
<?xml version="1.0" ?>
<root>
<leaf color="white">Text element with attributes</leaf>
<leaf_cdata>
<![CDATA[<em>CData</em> can contain <strong>HTML tags</strong> without encoding]]> </leaf_cdata>
<branch>
<leaf color="white">Text element with attributes</leaf>
</branch>
<mixed>
<leaf color="black" state="modified">Text element with attributes</leaf>
Do not use mixed elements if it possible.
</mixed>
</root>
In summary: I would be careful as to what code you copy. It is possible you are copying code which happens to work, rather than well chosen code.
In intnumber, parseInt is used and in floatnumber valueOf is used why so?
There is no good reason I can see. It's an inconsistent use of the APIs as you suspect.
Java is case sensitive, and there isn't any Readline()
method. Perhaps you mean readLine().
DataInputStream.readLine() is deprecated in favour of using BufferedReader.readLine();
However, for your case, I would use the Scanner class.
Scanner sc = new Scanner(System.in);
int intNum = sc.nextInt();
float floatNum = sc.nextFloat();
If you want to know what a class does I suggest you have a quick look at the Javadoc.
For MySQL 5.7.11
Step-1: First get the Unique Key
Use this query to get it:
1.1) SHOW CREATE TABLE User;
In the last, it will be like this:
.....
.....
UNIQUE KEY UK_8bv559q1gobqoulqpitq0gvr6
(phoneNum
)
.....
....
Step-2: Remove the Unique key by this query.
ALTER TABLE User DROP INDEX UK_8bv559q1gobqoulqpitq0gvr6;
Step-3: Check the table info, by this query:
DESC User;
This should show that the index is removed
Thats All.
Here is a solution with requests Response class. It is cleaner IMHO.
from unittest.mock import patch
from requests.models import Response
def mocked_request_get(*args, **kwargs):
response_content = None
request_url = kwargs.get('url', None)
if request_url == 'aurl':
response_content = json.dumps('a response')
elif request_url == 'burl':
response_content = json.dumps('b response')
elif request_url == 'curl':
response_content = json.dumps('c response')
response = Response()
response.status_code = 200
response._content = str.encode(response_content)
return response
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_fetch(self, mock_get):
response = call_your_view()
assert ...
try out this if you want to assign value to object and it is showing this error in angular..
crate object in construtor
this.modelObj = new Model();
//<---------- after declaring object above
The accepted answer works but can got complicated when I wanted to try adding Accept headers. This is what I ended up with. It seems simpler to me so I think I'll stick with it in the future:
client.DefaultRequestHeaders.Add("Accept", "application/*+xml;version=5.1");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + authstring);
(~~a == a)
where a
is the string.
It's pretty crazy town that the only way to make checked false is to omit any values. With Angular 1.x, you can do this:
<input type="radio" ng-checked="false">
which is a lot more sane, if you need to make it unchecked.
In the example a string is executed as code using the exec function.
import sys
import StringIO
# create file-like string to capture output
codeOut = StringIO.StringIO()
codeErr = StringIO.StringIO()
code = """
def f(x):
x = x + 1
return x
print 'This is my output.'
"""
# capture output and errors
sys.stdout = codeOut
sys.stderr = codeErr
exec code
# restore stdout and stderr
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
print f(4)
s = codeErr.getvalue()
print "error:\n%s\n" % s
s = codeOut.getvalue()
print "output:\n%s" % s
codeOut.close()
codeErr.close()
You can do this :
df <- data.frame("a" = c(1,2,3,4), "b" = c(4,3,2,1), "x_ind" = c(1,0,1,1), "y_ind" = c(0,0,1,1), "z_ind" = c(0,1,1,1) )
df %>% mutate( bi = ifelse((df$x_ind + df$y_ind +df$z_ind)== 3, 1,0 ))
A late answer, but here is an alternative to the SCOPE_IDENTITY()
answers that we ended up using: OUTPUT INSERTED
Return only ID of inserted object:
It allows you to get all or some attributes of the inserted row:
string insertUserSql = @"INSERT INTO dbo.[User](Username, Phone, Email)
OUTPUT INSERTED.[Id]
VALUES(@Username, @Phone, @Email);";
int newUserId = conn.QuerySingle<int>(
insertUserSql,
new
{
Username = "lorem ipsum",
Phone = "555-123",
Email = "lorem ipsum"
},
tran);
Return inserted object with ID:
If you wanted you could get Phone
and Email
or even the whole inserted row:
string insertUserSql = @"INSERT INTO dbo.[User](Username, Phone, Email)
OUTPUT INSERTED.*
VALUES(@Username, @Phone, @Email);";
User newUser = conn.QuerySingle<User>(
insertUserSql,
new
{
Username = "lorem ipsum",
Phone = "555-123",
Email = "lorem ipsum"
},
tran);
Also, with this you can return data of deleted or updated rows. Just be careful if you are using triggers because (from link mentioned before):
Columns returned from OUTPUT reflect the data as it is after the INSERT, UPDATE, or DELETE statement has completed but before triggers are executed.
For INSTEAD OF triggers, the returned results are generated as if the INSERT, UPDATE, or DELETE had actually occurred, even if no modifications take place as the result of the trigger operation. If a statement that includes an OUTPUT clause is used inside the body of a trigger, table aliases must be used to reference the trigger inserted and deleted tables to avoid duplicating column references with the INSERTED and DELETED tables associated with OUTPUT.
More on it in the docs: link
Although this is not exactly what OP meant as this is not super simple, however, when running scripts from Notepad++ the os.getcwd()
method doesn't work as expected. This is what I would do:
import os
# get real current directory (determined by the file location)
curDir, _ = os.path.split(os.path.abspath(__file__))
print(curDir) # print current directory
Define a function like this:
def dir_up(path,n): # here 'path' is your path, 'n' is number of dirs up you want to go
for _ in range(n):
path = dir_up(path.rpartition("\\")[0], 0) # second argument equal '0' ensures that
# the function iterates proper number of times
return(path)
The use of this function is fairly simple - all you need is your path and number of directories up.
print(dir_up(curDir,3)) # print 3 directories above the current one
The only minus is that it doesn't stop on drive letter, it just will show you empty string.
Yes you can increase or decrease the spacing(padding) between two cell by creating one base view on content view in cell.Set clear colour for content view background and you can adjust the height of the base view to create space between cells.
You can use $(":disabled")
to select all disabled items in the current context.
To determine whether a single item is disabled you can use $("#textbox1").is(":disabled")
.
I think you can create a simple SQL query:
$sql="select username from user where id in (select id from idtables)";
$query=$this->db->query($sql);
and then you can use it normally.
If you want to send email from your application, the above code is the only way to do it unless you code your own mail client (SMTP) inside your app, or have a server send the mail for you.
For example, you could code your app to invoke a URL on your server which would send the mail for you. Then you simply call the URL from your code.
Note that with the above code you can't attach anything to the email, which the SMTP client method would allow you to do, as well as the server-side method.
Call this in the project:
svn diff -r REVNO:HEAD --summarize
REVNO
is the start revision number and HEAD
is the end revision number. If HEAD is equal to the last revision number, it can skip it.
The command returns a list with all files that are changed/added/deleted in this revision period.
The command can be called with the URL revision parameter to check changes like this:
svn diff -r REVNO:HEAD --summarize SVN_URL
Here is some C code that produces the above mentioned error:
int main(int argc, char **argv) {
exit(1);
}
Compiled like this on Fedora 17 Linux 64 bit with gcc:
el@defiant ~/foo2 $ gcc -o n n2.c
n2.c: In function ‘main’:
n2.c:2:3: warning: incompatible implicit declaration of built-in
function ‘exit’ [enabled by default]
el@defiant ~/foo2 $ ./n
el@defiant ~/foo2 $
To make the warning go away, add this declaration to the top of the file:
#include <stdlib.h>
the similar problem (and no way Dockerfile alone could fix it) brought me to this page.
stage 0: for all, hoping Dockerfile could fix it: until --dns and --dns-search will appear in Dockerfile support - there is no way to integrate intranet based resources into.
stage 1:
after building image using Dockerfile (by the way it's a serious glitch Dockerfile must be in the current folder), having an image to deploy what's intranet based, by running docker run script. example:
docker run -d \
--dns=${DNSLOCAL} \
--dns=${DNSGLOBAL} \
--dns-search=intranet \
-t pack/bsp \
--name packbsp-cont \
bash -c " \
wget -r --no-parent http://intranet/intranet-content.tar.gz \
tar -xvf intranet-content.tar.gz \
sudo -u ${USERNAME} bash --norc"
stage 2: applying docker run script in daemon mode providing local dns records to have ability to download and deploy local stuff.
important point: run script should be ending with something like /usr/bin/sudo -u ${USERNAME} bash --norc
to keep container running even after the installation scripts finishes.
no, it's not possible to run container in interactive mode for the full automation matter as it will remain inside internal shall command prompt until CTRL-p CTRL-q being pressed.
no, if interacting bash will not be executed at the end of the installation script, the container will terminate immediately after finishes script execution, loosing all installation results.
stage 3:
container is still running in background but it's unclear whether container has ended installation procedure or not yet. using following block to determine execution procedure finishes:
while ! docker container top ${CONTNAME} | grep "00[[:space:]]\{12\}bash \--norc" -
do
echo "."
sleep 5
done
the script will proceed further only after completed installation. and this is the right moment to call: commit, providing current container id as well as destination image name (it may be the same as on the build/run procedure but appended with the local installation purposes tag. example: docker commit containerID pack/bsp:toolchained
.
see this link on how to get proper containerID
stage 4: container has been updated with the local installs as well as it has been committed into newly assigned image (the one having purposes tag added). it's safe now to stop container running. example: docker stop packbsp-cont
stage5: any moment the container with local installs require to run, start it with the image previously saved.
example: docker run -d -t pack/bsp:toolchained
None of these fixes worked for my develop platform targeting SDK 16, Release 4.1.2, so I found a workaround.
My app stores data on server using "http://www.example.com/page.php?data=somedata"
Recently page.php was moved to "https://www.secure-example.com/page.php" and I keep getting "javax.net.ssl.SSLException: Not trusted server certificate".
Instead of accepting all certificates for only a single page, starting with this guide I solved my problem writing my own page.php published on "http://www.example.com/page.php"
<?php
caronte ("https://www.secure-example.com/page.php");
function caronte($url) {
// build curl request
$ch = curl_init();
foreach ($_POST as $a => $b) {
$post[htmlentities($a)]=htmlentities($b);
}
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($post));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
echo $server_output;
}
?>
Here is another choice: Chaosreader
So I need to debug an application which posts xml to a 3rd party application. I found a brilliant little perl script which does all the hard work – you just chuck it a tcpdump output file, and it does all the manipulation and outputs everything you need...
The script is called chaosreader0.94. See http://www.darknet.org.uk/2007/11/chaosreader-trace-tcpudp-sessions-from-tcpdump/
It worked like a treat, I did the following:
tcpdump host www.blah.com -s 9000 -w outputfile; perl chaosreader0.94 outputfile
I had the same issue. My problem was that my header type wasn't set properly.
I just added this before my json echo
header('Content-type: application/json');
Before Starting your Intent:
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(AlbumListActivity.this);
startActivity(intent, options.toBundle());
This gives Default Animation to your Activity Transition.
Try this (see a working example of this code in jsfiddle: http://jsfiddle.net/periklis/7ATLS/1/)
<input type = "button" id = "clickme" value="Click me!"/>
<div id = "alert_placeholder"></div>
<script>
bootstrap_alert = function() {}
bootstrap_alert.warning = function(message) {
$('#alert_placeholder').html('<div class="alert"><a class="close" data-dismiss="alert">×</a><span>'+message+'</span></div>')
}
$('#clickme').on('click', function() {
bootstrap_alert.warning('Your text goes here');
});
</script>?
EDIT: There are now libraries that simplify and streamline this process, such as bootbox.js
If your C compiler supports blocks then you can write the following:
#include <stdio.h>
void ten(void (^b)(void)) { b();b();b();b();b();b();b();b();b();b(); }
int main() {
__block int i = 0;
ten(^{
ten(^{
ten(^{
printf("%d\n", ++i);
});
});
});
return 0;
}
Don't know if you solved the problem but if anyone has this problem in future.
$python
>>import numpy
>>print(numpy)
Go to the location printed and delete the numpy
installation found there. You can then use pip
or easy_install
import { FormsModule } from '@angular/forms';
//<<<< import it here
BrowserModule, FormsModule
//<<<< and here
So simply looks for app.module.ts
or another module file and make sure you have FormsModule
imported in...
ANT_HOME
is not being resolved. Change %ANT_HOME%\bin
in the Path system environment variable to c:\apache-ant\apache-ant-1.8.2\bin
.
To add to Jason's answer:
You can speed the process up (which might be helpful for very large exponents) using the binary expansion of the exponent. First calculate 5, 5^2, 5^4, 5^8 mod 221 - you do this by repeated squaring:
5^1 = 5(mod 221)
5^2 = 5^2 (mod 221) = 25(mod 221)
5^4 = (5^2)^2 = 25^2(mod 221) = 625 (mod 221) = 183(mod221)
5^8 = (5^4)^2 = 183^2(mod 221) = 33489 (mod 221) = 118(mod 221)
5^16 = (5^8)^2 = 118^2(mod 221) = 13924 (mod 221) = 1(mod 221)
5^32 = (5^16)^2 = 1^2(mod 221) = 1(mod 221)
Now we can write
55 = 1 + 2 + 4 + 16 + 32
so 5^55 = 5^1 * 5^2 * 5^4 * 5^16 * 5^32
= 5 * 25 * 625 * 1 * 1 (mod 221)
= 125 * 625 (mod 221)
= 125 * 183 (mod 183) - because 625 = 183 (mod 221)
= 22875 ( mod 221)
= 112 (mod 221)
You can see how for very large exponents this will be much faster (I believe it's log as opposed to linear in b, but not certain.)
You have to use br when using echo , like this :
echo "Thanks for your email" ."<br>". "Your orders details are below:"
and it will work properly
The align-items
, or respectively align-content
attribute controls this behaviour.
align-items
defines the items' positioning perpendicularly to flex-direction
.
The default flex-direction
is row
, therfore vertical placement can be controlled with align-items
.
There is also the align-self
attribute to control the alignment on a per item basis.
#a {_x000D_
display:flex;_x000D_
_x000D_
align-items:flex-start;_x000D_
align-content:flex-start;_x000D_
}_x000D_
_x000D_
#a > div {_x000D_
_x000D_
background-color:red;_x000D_
padding:5px;_x000D_
margin:2px;_x000D_
}_x000D_
#a > #c {_x000D_
align-self:stretch;_x000D_
}
_x000D_
<div id="a">_x000D_
_x000D_
<div id="b">left</div>_x000D_
<div id="c">middle</div>_x000D_
<div>right<br>right<br>right<br>right<br>right<br></div>_x000D_
_x000D_
</div>
_x000D_
css-tricks has an excellent article on the topic. I recommend reading it a couple of times.
Use plt.show(block=False)
, and at the end of your script call plt.show()
.
This will ensure that the window won't be closed when the script is finished.
I faced problems with ubuntu 18.04 and mysql 5.7, this is the solution
Try restart mysql-server before execution the comands
sudo service mysql restart
MYSQL-SERVER >= 5.7
sudo mysql -uroot -p
USE mysql;
UPDATE user SET authentication_string=PASSWORD('YOUR_PASSWORD') WHERE User='root';
UPDATE user SET plugin="mysql_native_password";
FLUSH PRIVILEGES;
quit;
MYSQL-SERVER < 5.7
sudo mysql -uroot -p
USE mysql;
UPDATE user SET password=PASSWORD('YOUR_PASSWORD') WHERE User='root';
UPDATE user SET plugin="mysql_native_password";
FLUSH PRIVILEGES;
quit;
In general, i agree with above answers that recommend to add maven dependency, but i prefer following solution.
Add a dependency with API classes for full JavaEE profile:
<properties>
<javaee-api.version>7.0</javaee-api.version>
<hibernate-entitymanager.version>5.1.3.Final</hibernate-entitymanager.version>
</properties>
<depencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javaee-api.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
Also add dependency with particular JPA provider like antonycc suggested:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-entitymanager.version}</version>
</dependency>
Note <scope>provided</scope>
in API dependency section: this means that corresponding jar will not be exported into artifact's lib/
, but will be provided by application server. Make sure your application server implements specified version of JavaEE API.
The -u flag is specifying that you want to link your local branch to the upstream branch. This will also create an upstream branch if one does not exist. None of these answers cover how i do it (in complete form) so here it is:
git push -u origin <your-local-branch-name>
So if your local branch name is coffee
git push -u origin coffee
swift 4 way:
extension UIColor {
static let system = UIView().tintColor!
}
Calling close
and shutdown
have two different effects on the underlying socket.
The first thing to point out is that the socket is a resource in the underlying OS and multiple processes can have a handle for the same underlying socket.
When you call close
it decrements the handle count by one and if the handle count has reached zero then the socket and associated connection goes through the normal close procedure (effectively sending a FIN / EOF to the peer) and the socket is deallocated.
The thing to pay attention to here is that if the handle count does not reach zero because another process still has a handle to the socket then the connection is not closed and the socket is not deallocated.
On the other hand calling shutdown
for reading and writing closes the underlying connection and sends a FIN / EOF to the peer regardless of how many processes have handles to the socket. However, it does not deallocate the socket and you still need to call close afterward.
The solution you are looking for is in Angular's official tutorial. In this tutorial Phones are loaded from a JSON file using Angulars $http service . In the code below we use $http.get to load a phones.json file saved in the phones directory:
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
});
We then iterate over the phones:
<table>
<tbody ng-repeat="i in phones">
<tr><td>{{i.name}}</td><td>{{$index}}</td></tr>
<tr ng-repeat="e in i.details">
<td>{{$index}}</td>
<td>{{e.foo}}</td>
<td>{{e.bar}}</td></tr>
</tbody>
</table>
It's not an exact duplicate (so far as I can find), but this is a common problem.
display:block
is what you need. but you should read the spec to understand why.
You have pylab.ylim
:
pylab.ylim([0,1000])
Note: The command has to be executed after the plot!
Update 2021
Since the use of pylab is now strongly discouraged by matplotlib, you should instead use pyplot:
from matplotlib import pyplot as plt
plt.ylim(0, 100)
#corresponding function for the x-axis
plt.xlim(1, 1000)
It works for me if I tick the box 'Prompt for workspace on startup', which you find in Window > Preferences > General > Startup and Shutdown > Workspaces.
HTH
If you are using Java 8 and don't want to manipulate CompletableFuture
s, I have written a tool to retrieve results for a List<Future<T>>
using streaming. The key is that you are forbidden to map(Future::get)
as it throws.
public final class Futures
{
private Futures()
{}
public static <E> Collector<Future<E>, Collection<E>, List<E>> present()
{
return new FutureCollector<>();
}
private static class FutureCollector<T> implements Collector<Future<T>, Collection<T>, List<T>>
{
private final List<Throwable> exceptions = new LinkedList<>();
@Override
public Supplier<Collection<T>> supplier()
{
return LinkedList::new;
}
@Override
public BiConsumer<Collection<T>, Future<T>> accumulator()
{
return (r, f) -> {
try
{
r.add(f.get());
}
catch (InterruptedException e)
{}
catch (ExecutionException e)
{
exceptions.add(e.getCause());
}
};
}
@Override
public BinaryOperator<Collection<T>> combiner()
{
return (l1, l2) -> {
l1.addAll(l2);
return l1;
};
}
@Override
public Function<Collection<T>, List<T>> finisher()
{
return l -> {
List<T> ret = new ArrayList<>(l);
if (!exceptions.isEmpty())
throw new AggregateException(exceptions, ret);
return ret;
};
}
@Override
public Set<java.util.stream.Collector.Characteristics> characteristics()
{
return java.util.Collections.emptySet();
}
}
This needs an AggregateException
that works like C#'s
public class AggregateException extends RuntimeException
{
/**
*
*/
private static final long serialVersionUID = -4477649337710077094L;
private final List<Throwable> causes;
private List<?> successfulElements;
public AggregateException(List<Throwable> causes, List<?> l)
{
this.causes = causes;
successfulElements = l;
}
public AggregateException(List<Throwable> causes)
{
this.causes = causes;
}
@Override
public synchronized Throwable getCause()
{
return this;
}
public List<Throwable> getCauses()
{
return causes;
}
public List<?> getSuccessfulElements()
{
return successfulElements;
}
public void setSuccessfulElements(List<?> successfulElements)
{
this.successfulElements = successfulElements;
}
}
This component acts exactly as C#'s Task.WaitAll. I am working on a variant that does the same as CompletableFuture.allOf
(equivalento to Task.WhenAll
)
The reason why I did this is that I am using Spring's ListenableFuture
and don't want to port to CompletableFuture
despite it is a more standard way
To Remove an Item
$("select#mySelect option[value='option1']").remove();
To Add an item
$("#mySelect").append('<option value="option1">Option</option>');
To Check for an option
$('#yourSelect option[value=yourValue]').length > 0;
To remove a selected option
$('#mySelect :selected').remove();
I tried all the above codes and none of them fixed my issues. Here is what worked for me. I used input-group-addon.
<div class = "input-group">
<span class = "input-group-addon">Go</span>
<input type = "text" class = "form-control" placeholder="you are the man!">
</div>
You are mixing the 2 different CASE
syntaxes inappropriately.
Use this style (Searched)
CASE
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Or this style (Simple)
CASE u.nnmu
WHEN '0' THEN mu.naziv_mesta
WHEN '1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Not This (Simple but with boolean search predicates)
CASE u.nnmu
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
In MySQL this will end up testing whether u.nnmu
is equal to the value of the boolean expression u.nnmu ='0'
itself. Regardless of whether u.nnmu
is 1
or 0
the result of the case expression itself will be 1
For example if nmu = '0'
then (nnmu ='0'
) evaluates as true
(1) and (nnmu ='1'
) evaluates as false
(0). Substituting these into the case expression gives
SELECT CASE '0'
WHEN 1 THEN '0'
WHEN 0 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
if nmu = '1'
then (nnmu ='0'
) evaluates as false
(0) and (nnmu ='1'
) evaluates as true
(1). Substituting these into the case expression gives
SELECT CASE '1'
WHEN 0 THEN '0'
WHEN 1 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
The error shows that com.bd.service.ArticleService
is not a registered bean. Add the packages in which you have beans that will be autowired in your application context:
<context:component-scan base-package="com.bd.service"/>
<context:component-scan base-package="com.bd.controleur"/>
Alternatively, if you want to include all subpackages in com.bd
:
<context:component-scan base-package="com.bd">
<context:include-filter type="aspectj" expression="com.bd.*" />
</context:component-scan>
As a side note, if you're using Spring 3.1 or later, you can take advantage of the @ComponentScan
annotation, so that you don't have to use any xml configuration regarding component-scan. Use it in conjunction with @Configuration
.
@Controller
@RequestMapping("/Article/GererArticle")
@Configuration
@ComponentScan("com.bd.service") // No need to include component-scan in xml
public class ArticleControleur {
@Autowired
ArticleService articleService;
...
}
You might find this Spring in depth section on Autowiring useful.
This worked for me.
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
List<String> listing = getObjectNamesForBucket(bucket, s3Client);
Log.e(TAG, "listing "+ listing);
}
catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Exception found while listing "+ e);
}
}
});
thread.start();
private List<String> getObjectNamesForBucket(String bucket, AmazonS3 s3Client) {
ObjectListing objects=s3Client.listObjects(bucket);
List<String> objectNames=new ArrayList<String>(objects.getObjectSummaries().size());
Iterator<S3ObjectSummary> oIter=objects.getObjectSummaries().iterator();
while (oIter.hasNext()) {
objectNames.add(oIter.next().getKey());
}
while (objects.isTruncated()) {
objects=s3Client.listNextBatchOfObjects(objects);
oIter=objects.getObjectSummaries().iterator();
while (oIter.hasNext()) {
objectNames.add(oIter.next().getKey());
}
}
return objectNames;
}
SELECT Id, 'TRUE' AS NewFiled FROM TABEL1
INTERSECT
SELECT Id, 'TRUE' AS NewFiled FROM TABEL2
UNION
SELECT Id, 'FALSE' AS NewFiled FROM TABEL1
EXCEPT
SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;
public FileContentResult GetImage(int productId) {
Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productId);
if (prod != null) {
return File(prod.ImageData, prod.ImageMimeType);
} else {
return null;
}
}
Just for an additional reference.
All of the above answers will work in case of a data frame. But if you are using lambda while creating / modify a column this won't work, Because there it is considered as a int attribute instead of pandas series. You have to use str( target_attribute ) to make it as a string. Please refer the below example.
def add_zero_in_prefix(df):
if(df['Hour']<10):
return '0' + str(df['Hour'])
data['str_hr'] = data.apply(add_zero_in_prefix, axis=1)
Try:
CREATE TABLE foo SELECT * FROM bar LIMIT 0
Or:
CREATE TABLE foo SELECT * FROM bar WHERE 1=0
echo
adds spaces between the arguments passed to it. $text
is subject to variable expansion and word splitting, so your echo
command is equivalent to:
echo -e "this" "is" "line" "one\n" "this" "is" "line" "two\n" ...
You can see that a space will be added before "this". You can either remove the newline characters, and quote $text
to preserve the newlines:
text="this is line one
this is line two
this is line three"
echo "$text" > filename
Or you could use printf
, which is more robust and portable than echo
:
printf "%s\n" "this is line one" "this is line two" "this is line three" > filename
In bash
, which supports brace expansion, you could even do:
printf "%s\n" "this is line "{one,two,three} > filename
I used this to check if all the text boxes had numeric values:
if(!$.isNumeric($('input:text').val())) {
alert("All the text boxes must have numeric values!");
return false;
}
or for one:
$.isNumeric($("txtBox").val());
Available with jQuery 1.7.
Nobody has mentioned the index order to access the elements of the initialized array. My example code will give an illustrative example to it.
#include <iostream>
void PrintArray(int a[3][3])
{
std::cout << "a11 = " << a[0][0] << "\t\t" << "a12 = " << a[0][1] << "\t\t" << "a13 = " << a[0][2] << std::endl;
std::cout << "a21 = " << a[1][0] << "\t\t" << "a22 = " << a[1][1] << "\t\t" << "a23 = " << a[1][2] << std::endl;
std::cout << "a31 = " << a[2][0] << "\t\t" << "a32 = " << a[2][1] << "\t\t" << "a33 = " << a[2][2] << std::endl;
std::cout << std::endl;
}
int wmain(int argc, wchar_t * argv[])
{
int a1[3][3] = { 11, 12, 13, // The most
21, 22, 23, // basic
31, 32, 33 }; // format.
int a2[][3] = { 11, 12, 13, // The first (outer) dimension
21, 22, 23, // may be omitted. The compiler
31, 32, 33 }; // will automatically deduce it.
int a3[3][3] = { {11, 12, 13}, // The elements of each
{21, 22, 23}, // second (inner) dimension
{31, 32, 33} }; // can be grouped together.
int a4[][3] = { {11, 12, 13}, // Again, the first dimension
{21, 22, 23}, // can be omitted when the
{31, 32, 33} }; // inner elements are grouped.
PrintArray(a1);
PrintArray(a2);
PrintArray(a3);
PrintArray(a4);
// This part shows in which order the elements are stored in the memory.
int * b = (int *) a1; // The output is the same for the all four arrays.
for (int i=0; i<9; i++)
{
std::cout << b[i] << '\t';
}
return 0;
}
The output is:
a11 = 11 a12 = 12 a13 = 13
a21 = 21 a22 = 22 a23 = 23
a31 = 31 a32 = 32 a33 = 33
a11 = 11 a12 = 12 a13 = 13
a21 = 21 a22 = 22 a23 = 23
a31 = 31 a32 = 32 a33 = 33
a11 = 11 a12 = 12 a13 = 13
a21 = 21 a22 = 22 a23 = 23
a31 = 31 a32 = 32 a33 = 33
a11 = 11 a12 = 12 a13 = 13
a21 = 21 a22 = 22 a23 = 23
a31 = 31 a32 = 32 a33 = 33
11 12 13 21 22 23 31 32 33
The short version is that you cannot use variable-width patterns in lookbehinds using Python's re
module. There is no way to change this:
>>> import re
>>> re.sub("(?<=foo)bar(?=baz)", "quux", "foobarbaz")
'fooquuxbaz'
>>> re.sub("(?<=fo+)bar(?=baz)", "quux", "foobarbaz")
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
re.sub("(?<=fo+)bar(?=baz)", "quux", string)
File "C:\Development\Python25\lib\re.py", line 150, in sub
return _compile(pattern, 0).sub(repl, string, count)
File "C:\Development\Python25\lib\re.py", line 241, in _compile
raise error, v # invalid expression
error: look-behind requires fixed-width pattern
This means that you'll need to work around it, the simplest solution being very similar to what you're doing now:
>>> re.sub("(fo+)bar(?=baz)", "\\1quux", "foobarbaz")
'fooquuxbaz'
>>>
>>> # If you need to turn this into a callable function:
>>> def replace(start, replace, end, replacement, search):
return re.sub("(" + re.escape(start) + ")" + re.escape(replace) + "(?=" + re.escape + ")", "\\1" + re.escape(replacement), search)
This doesn't have the elegance of the lookbehind solution, but it's still a very clear, straightforward one-liner. And if you look at what an expert has to say on the matter (he's talking about JavaScript, which lacks lookbehinds entirely, but many of the principles are the same), you'll see that his simplest solution looks a lot like this one.
You can find a comprehensive set of solutions on this in UNIX & Linux's answer to How do you move all files (including hidden) from one directory to another?. It shows solutions in Bash, zsh, ksh93, standard (POSIX) sh, etc.
You can use these two commands together:
mv /path/subfolder/* /path/ # your current approach
mv /path/subfolder/.* /path/ # this one for hidden files
Or all together (thanks pfnuesel):
mv /path/subfolder/{.,}* /path/
Which expands to:
mv /path/subfolder/* /path/subfolder/.* /path/
(example: echo a{.,}b
expands to a.b ab
)
Note this will show a couple of warnings:
mv: cannot move ‘/path/subfolder/.’ to /path/.’: Device or resource busy
mv: cannot remove /path/subfolder/..’: Is a directory
Just ignore them: this happens because /path/subfolder/{.,}*
also expands to /path/subfolder/.
and /path/subfolder/..
, which are the directory and the parent directory (See What do “.” and “..” mean when in a folder?).
If you want to just copy, you can use a mere:
cp -r /path/subfolder/. /path/
# ^
# note the dot!
This will copy all files, both normal and hidden ones, since /path/subfolder/.
expands to "everything from this directory" (Source: How to copy with cp to include hidden files and hidden directories and their contents?)
There could be many reasons for Index not being used. Even after you specify hints, there are chances Oracle optimizer thinks otherwise and decide not to use Index. You need to go through the EXPLAIN PLAN part and see what is the cost of the statement with INDEX and without INDEX.
Assuming the Oracle uses CBO. Most often, if the optimizer thinks the cost is high with INDEX, even though you specify it in hints, the optimizer will ignore and continue for full table scan. Your first action should be checking DBA_INDEXES to know when the statistics are LAST_ANALYZED. If not analyzed, you can set table, index for analyze.
begin
DBMS_STATS.GATHER_INDEX_STATS ( OWNNAME=>user
, INDNAME=>IndexName);
end;
For table.
begin
DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME=>user
, TABNAME=>TableName);
end;
In extreme cases, you can try setting up the statistics on your own.
The S parameter does not do anything on its own.
/S Modifies the treatment of string after /C or /K (see below)
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
Try something like this instead
Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)
You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.
Shell("perl a.pl c:\temp")
-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn
First of all, you don't need to use a layout inflater to create a simple Button. You can just use:
button = new Button(context);
If you want to style the button you have 2 choices: the simplest one is to just specify all the elements in code, like many of the other answers suggest:
button.setTextColor(Color.RED);
button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
The other option is to define the style in XML, and apply it to the button. In the general case, you can use a ContextThemeWrapper
for this:
ContextThemeWrapper newContext = new ContextThemeWrapper(baseContext, R.style.MyStyle);
button = new Button(newContext);
To change the text-related attributes on a TextView (or its subclasses like Button) there is a special method:
button.setTextAppearance(R.style.MyTextStyle);
Or, if you need to support devices pre API-23 (Android 6.0)
button.setTextAppearance(context, R.style.MyTextStyle);
This method cannot be used to change all attributes; for example to change padding you need to use a ContextThemeWrapper
. But for text color, size, etc. you can use setTextAppearance
.
Try this:
$(".ui-widget-overlay").click(function () {
$(".ui-icon.ui-icon-closethick").trigger("click");
});
$query= $this->m_general->get('users' , array('id'=> $id ));
echo $query[''];
is ok ;)
I had the same problem when I deployed my application to test PC. The problem was development PC had msvcp110d.dll
and msvcr110d.dll
but not the test PC.
I added "Visual Studio C++ 11.0 DebugCRT (x86)" merge module in InstalledSheild and it worked. Hope this will be helpful for someone else.
use the following file prefix, this will add to your perl script eTRUE and eFALSE, it will actually be REAL(!) true and false (just like java)
#!/usr/bin/perl
use strict;
use warnings;
use constant { #real true false, compatible with encode_json decode_json for later (we don't want field:false... will be field:0...)
eTRUE => bless( do{\(my $o = 1)}, 'JSON::PP::Boolean' ),
eFALSE => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' )
};
There are, actually, few reasons why you should use that.
My reason is that working with JSON, I've got 0 and 1 as values to keys, but this hack will make sure correct values are kept along your script.
Technically, you don't need a framework. If you're making a really really simple site (think of the web back in 1992), you can just do it all with hard-coded HTML and some CSS.
And if you want to make a modern webapp, you don't actually need to use a framework for that, either.
You can instead choose to write all of the logic you need yourself, every time. You can write your own data-persistence/storage layer, or - if you're too busy - just write custom SQL for every single database access. You can write your own authentication and session handling layers. And your own template rending logic. And your own exception-handling logic. And your own security functions. And your own unit test framework to make sure it all works fine. And your own... [goes on for quite a long time]
Then again, if you do use a framework, you'll be able to benefit from the good, usually peer-reviewed and very well tested work of dozens if not hundreds of other developers, who may well be better than you. You'll get to build what you want rapidly, without having to spend time building or worrying too much about the infrastructure items listed above.
You can get more done in less time, and know that the framework code you're using or extending is very likely to be done better than you doing it all yourself.
And the cost of this? Investing some time learning the framework. But - as virtually every web dev out there will attest - it's definitely worth the time spent learning to get massive (really, massive) benefits from using whatever framework you choose.
Be careful with invalid values for keys "directories" and "files" in package.json
If you start with a new application, and you want to start completely blank, you have to either start in a complete empty folder or have a valid package.json file in it.
If you do not want to create a package.json file first, just type: npm i some_package
Package with name "some_package" should be installed correctly in a new sub folder "node_modules".
If you create a package.json file first, type: npm init
Keep all the defaults (by just clicking ENTER), you should end up with a valid file.
It should look like this:
{
"name": "yourfoldername",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Note that the following keys are missing: "directories", "repository" and "files". It looks like if you use incorrect values for "directories" and/or "files", you are not able to install the package. Leaving these keys out, solved the issue for me.
Also note key "main". This one is present, but it does contain an invalid value. No file "index.js" exists (yet). You can safely remove it.
Now type: npm i some_package
and package with name "some_package" should be installed correctly in a new sub folder "node_modules".
When you talked about "Hash Table will place a new entry into the 'next available' bucket if the new Key entry collides with another.", you are talking about the Open addressing strategy of Collision resolution of hash table.
There are several strategies for hash table to resolve collision.
First kind of big method require that the keys (or pointers to them) be stored in the table, together with the associated values, which further includes:
Another important method to handle collision is by Dynamic resizing, which further has several ways:
EDIT: the above are borrowed from wiki_hash_table, where you should go to have a look to get more info.
public EditText editField;
public Button clear = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_layout);
this. editField = (EditText)findViewById(R.id.userName);
this.clear = (Button) findViewById(R.id.clear_button);
this.editField.setOnClickListener(this);
this.clear.setOnClickListener(this);
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.clear_button){
//setText will remove all text that is written by someone
editField.setText("");
}
}
You can't. You need to create another php script to return the image data, e.g. getImage.php. Change catalog.php to:
<body>
<img src="getImage.php?id=1" width="175" height="200" />
</body>
Then getImage.php is
<?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$link = mysql_connect("localhost", "root", "");
mysql_select_db("dvddb");
$sql = "SELECT dvdimage FROM dvd WHERE id=$id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['dvdimage'];
?>
The :&&
command repeats the last substitution with the same flags. You can supply the additional range(s) to it (and concatenate as many as you like):
:6,10s/<search_string>/<replace_string>/g | 14,18&&
If you have many ranges though, I'd rather use a loop:
:for range in split('6,10 14,18')| exe range 's/<search_string>/<replace_string>/g' | endfor
It does work in Firefox (including 2.0.0.20
). See http://jsbin.com/akili (add /edit
to the url to edit):
<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>
The first click changes the id
to "two"
, the second click errors because the element with id="one"
now can't be found!
Perhaps you have another element already with id="two"
(FYI you can't have more than one element with the same id
).
You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession); CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);
let delta = Math.floor(Math.abs(start.getTime() - end.getTime()) / 1000);
let hours = Math.floor(delta / 3600);
delta -= hours * 3600;
let minutes = Math.floor(delta / 60);
delta -= minutes * 60;
let seconds = delta;
if (hours.toString().length === 1) {
hours = `0${hours}`;
}
if (minutes.toString().length === 1) {
minutes = `0${minutes}`;
}
if (seconds.toString().length === 1) {
seconds = `0${seconds}`;
}
const recordingTime = `${hours}:${minutes}:${seconds}`;
For windows, @shoaly parameters didn't completely work for me. I was getting this error:
NCAT DEBUG: Proxy returned status code 501.
Ncat: Proxy returned status code 501.
ssh_exchange_identification: Connection closed by remote host
I wanted to ssh to a REMOTESERVER and the SSH port had been closed in my network. I found two solutions but the second is better.
To solve the problem using Ncat:
ncat.exe
into the current directory.SSH using Ncat as ProxyCommand in Git Bash with addition --proxy-type socks4
parameter:
ssh -o "ProxyCommand=./ncat --proxy-type socks4 --proxy 127.0.0.1:9150 %h %p" USERNAME@REMOTESERVER
Note that this implementation of Ncat does not support socks5.
THE BETTER SOLUTION:
SSH using connect.c as ProxyCommand in Git Bash:
ssh -o "ProxyCommand=connect -a none -S 127.0.0.1:9150 %h %p"
Note that connect.c supports socks version 4/4a/5.
To use the proxy in git
commands using ssh (for example while using GitHub) -- assuming you installed Git Bash in C:\Program Files\Git\
-- open ~/.ssh/config
and add this entry:
host github.com
user git
hostname github.com
port 22
proxycommand "/c/Program Files/Git/mingw64/bin/connect.exe" -a none -S 127.0.0.1:9150 %h %p
@thamme-gowda's solution works for images too!
| |
|:----------------------------------------------------------------------------:|
| ![](https://gravatar.com/avatar/4cc702785290b4934c531c56f6061e5e "Tonejito") |
You can check this out on a gist I made for that. Here is a render of the table hack on GitHub and GitLab:
I had a case where I was entering text into a field after which the text would be removed automatically. Turned out it was due to some site functionality where you had to press the enter key after entering the text into the field. So, after sending your barcode text with sendKeys method, send 'enter' directly after it. Note that you will have to import the selenium Keys class. See my code below.
import org.openqa.selenium.Keys;
String barcode="0000000047166";
WebElement element_enter = driver.findElement(By.xpath("//*[@id='div-barcode']"));
element_enter.findElement(By.xpath("your xpath")).sendKeys(barcode);
element_enter.sendKeys(Keys.RETURN); // this will result in the return key being pressed upon the text field
I hope it helps..
QRGen is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake.
Python3. Use inspect to capture the calling local namespace then use ideas presented here. Can return more than one answer as has been pointed out.
def varname(var):
import inspect
frame = inspect.currentframe()
var_id = id(var)
for name in frame.f_back.f_locals.keys():
try:
if id(eval(name)) == var_id:
return(name)
except:
pass
In my case, I forgot to set database env for deployment. you can set env by this command (I'm using mLab for MongoDB server)
heroku config:set MONGO_URI='mongodb://address'