You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
You cannot.
According to the XML Schema specification, a boolean is true
or false
. True
is not valid:
3.2.2.1 Lexical representation An instance of a datatype that is defined as ·boolean· can have the following legal literals {true, false, 1, 0}. 3.2.2.2 Canonical representation The canonical representation for boolean is the set of literals {true, false}.
If the tool you are using truly validates against the XML Schema standard, then you cannot convince it to accept True for a boolean.
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string extension = ".log";
filePath += @"\Error Log\" + extension;
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
You can write integer in xml file also..
have you seen [this]
http://developer.android.com/guide/topics/resources/more-resources.html#Integer ?
use as .
context.getResources().getInteger(R.integer.height_pop);
Basically in this case, System.Data.OracleClient need access to some of the oracle dll which are not part of .Net. Solutions:
.live was removed in 1.9, please see the upgrade guide: http://jquery.com/upgrade-guide/1.9/#live-removed
I used encoding filter which has solved my all encoding problem...
package com.dina.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
*
* @author DINANATH
*/
public class EncodingFilter implements Filter {
private String encoding = "utf-8";
public void doFilter(ServletRequest request,ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
// response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding(encoding);
filterChain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String encodingParam = filterConfig.getInitParameter("encoding");
if (encodingParam != null) {
encoding = encodingParam;
}
}
public void destroy() {
// nothing todo
}
}
in web.xml
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>
com.dina.filter.EncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
GO here http://validator.w3.org/ upload your html file and it will tell you what is valid and what is not.
"matt b" has it right, but to be specific, the "install" goal copies your built target to the local repository on your file system; useful for small changes across projects not currently meant for the full group.
The "deploy" goal uploads it to your shared repository for when your work is finished, and then can be shared by other people who require it for their project.
In your case, it seems that "install" is used to make the management of the deployment easier since CI's local repo is the shared repo. If CI was on another box, it would have to use the "deploy" goal.
I tried removing the dataType row and it didn't work for me. I got around the issue by using "complete" instead of "success" as the callback. The success callback still fails in IE, but since my script runs and completes anyway that's all I care about.
$.ajax({
type: 'POST',
url: 'somescript.php',
data: someData,
complete: function(jqXHR) {
if(jqXHR.readyState === 4) {
... run some code ...
}
}
});
in jQuery 1.5 you can also do it like this.
var ajax = $.ajax({
type: 'POST',
url: 'somescript.php',
data: 'someData'
});
ajax.complete(function(jqXHR){
if(jqXHR.readyState === 4) {
... run some code ...
}
});
The style attribute for the menu background is android:panelFullBackground
.
Despite what the documentation says, it needs to be a resource (e.g. @android:color/black
or @drawable/my_drawable
), it will crash if you use a color value directly.
This will also get rid of the item borders that I was unable to change or remove using primalpop's solution.
As for the text color, I haven't found any way to set it through styles in 2.2 and I'm sure I've tried everything (which is how I discovered the menu background attribute). You would need to use primalpop's solution for that.
You could also try posix_memalign()
(on POSIX platforms, of course).
https://www.npmjs.com/package/axios
Its Working
// "content-type": "application/x-www-form-urlencoded", // commit this
import axios from 'axios';
let requestData = {
username : "[email protected]",
password: "123456
};
const url = "Your Url Paste Here";
let options = {
method: "POST",
headers: {
'Content-type': 'application/json; charset=UTF-8',
Authorization: 'Bearer ' + "your token Paste Here",
},
data: JSON.stringify(requestData),
url
};
axios(options)
.then(response => {
console.log("K_____ res :- ", response);
console.log("K_____ res status:- ", response.status);
})
.catch(error => {
console.log("K_____ error :- ", error);
});
fetch request
fetch(url, {
method: 'POST',
body: JSON.stringify(requestPayload),
headers: {
'Content-type': 'application/json; charset=UTF-8',
Authorization: 'Bearer ' + token,
},
})
// .then((response) => response.json()) . // commit out this part if response body is empty
.then((json) => {
console.log("response :- ", json);
}).catch((error)=>{
console.log("Api call error ", error.message);
alert(error.message);
});
This worked for me
childView.centerXAnchor.constraint(equalTo: parentView.centerXAnchor).isActive = true
childView.centerYAnchor.constraint(equalTo: parentView.centerYAnchor).isActive = true
A void*
pointer is used when you want to indicate a pointer to a hunk of memory without specifying the type. C's malloc
returns such a pointer, expecting you to cast it to a particular type immediately. It really isn't useful until you cast it to another pointer type. You're expected to know which type to cast it to, the compiler has no reflection capability to know what the underlying type should be.
You could look into clearTimeout()
or pause depending on a global variable that is set when a certain condition is hit. Like a button is pressed.
<button onclick="myBool = true" > pauseTimeout </button>
<script>
var myBool = false;
var t = setTimeout(function() {if (!mybool) {dosomething()}}, 5000);
</script>
If you have the file locally, then use install.packages()
and set the repos=NULL
:
install.packages(path_to_file, repos = NULL, type="source")
Where path_to_file
would represent the full path and file name:
"C:\\RJSONIO_0.2-3.tar.gz"
."/home/blah/RJSONIO_0.2-3.tar.gz"
.Change the content type to ms-excel in the html and browser shall open the html in the Excel as xls. If you want control over the transformation of HTML to excel use POI libraries to do so.
I using Xcode 6+ and I just do:
*.xcodeproj or *.xcworkspace
Here is done, but name of window Xcode and *.xcodeproj or *.xcworkspace
still <old-name>
. Then I do:
pop install
<new name>.xcworkspace
We can check also in simple way as:
function isLetter(char){_x000D_
return ( (char >= 'A' && char <= 'Z') ||_x000D_
(char >= 'a' && char <= 'z') );_x000D_
}_x000D_
_x000D_
_x000D_
console.log(isLetter("a"));_x000D_
console.log(isLetter(3));_x000D_
console.log(isLetter("H"));
_x000D_
Using Maria-DB and DB-Navigator tool inside IntelliJ, MODIFY Column worked for me instead of Alter Column
After pip install spyder
give this command
pip install --upgrade spyder
This command will update all Spyder dependencies.
Now in command prompt(cmd) navigate to the scripts folder in your python directory. In my system the path is C:\Users\win10\AppData\Local\Programs\Python\Python36-32\Scripts so i use the following command in command prompt.
cd C:\Users\win10\AppData\Local\Programs\Python\Python36-32\Scripts
once you are inside scripts directory type spyder3 and press enter and spyder ide starts.
C:\Users\win10\AppData\Local\Programs\Python\Python36-32\Scripts>spyder3
var log = { "page": window.location.href,
"item": "item",
"action": "action" };
log = JSON.stringify(log);
console.log(log);
console.log(JSON.parse(log));
//The output will be:
//For 1st Console is a String Like:
'{ "page": window.location.href,"item": "item","action": "action" }'
//For 2nd Console is a Object Like:
Object {
page : window.location.href,
item : "item",
action : "action" }
What worked for me:
Since yesterday, I have been trying to install the Eclipse plugin - "Remote System Explorer" from the Eclipse marketplace on a freshly downloaded Eclipse 4.8 as shown below,
and everytime I was getting this error:
Unable to read repository at http://download.eclipse.org/releases/kepler/. Unable to read repository at http://download.eclipse.org/releases/kepler/201306260900/content.jar. download.eclipse.org:80 failed to respond
which brought me to this SO post.
I tried a few solutions mentioned here in the different answers like this one and this one and this one, but none of them worked. I just gave up almost, thinking that either the corporate network here is somehow blocking the specific download requests or the 4.8 version of Eclipse is buggy.
Discovery:
I could not reload all the paths under 'Window' -> 'Preferences' -> 'Install/Update' -> 'Available Software Sites'
.
Preconditions:
What did work for me from the beginning was:
Finally, this answer put me on the right track - for my specific case, at least. Just my step was to do the exact opposite of what that answer was doing.
Solution:
I had to change all the http:\\
paths to https:\\
and suddenly it started to work. I don't know who - either IE/Edge on Windows 10 or the Windows 10 firewall or the company firewall is blocking HTTP communications. But with HTTPS, I can finally install plugins from the Marketplace.
I must say, what is strange is that not all the paths required https
. Except a few, the rest seemed to have had no problem working with HTTP
. But I anyways changed all to HTTPS
, just for good measure.
Note: In case during the update, this same error pops up again, then see in the repositories that any new paths added by eclipse during the update, are also HTTPS and not HTTP.
You're missing a FROM and you need to give the subquery an alias.
SELECT COUNT(*) FROM
(
SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
FROM dbo.Table_A AS a
INNER JOIN dbo.Table_B AS b
ON a.a_id = b.a_id
) AS subquery;
In this post Scrollview vertical and horizontal in android they talk about a possible solution, quoting:
Matt Clark has built a custom view based on the Android source, and it seems to work perfectly: http://blog.gorges.us/2010/06/android-two-dimensional-scrollview
Beware that the class in that page has a bug calculating the view's horizonal width. A fix by Manuel Hilty is in the comments:
Solution: Replace the statement on line 808 by the following:
final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED);
If you need to search many time in the same list, it may pay off to build an index.
Iterate once through, and build a HashMap with the equals value you are looking for as the key and the appropriate node as the value. If you need all instead of anyone of a given equals value, then let the map have a value type of list and build the whole list in the initial iteration.
Please note that you should measure before doing this as the overhead of building the index may overshadow just traversing until the expected node is found.
I have the same problem too, after upgrading win7 to win10. then I check services.msc and found "World Wide Web Publishing Service" was running automatically by default. So then I disabled it, and running the Apache service again.
you can install superagent
npm install superagent --save
then for make post call to server
import request from "../../node_modules/superagent/superagent";
request
.post('http://localhost/userLogin')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send({ username: "username", password: "password" })
.end(function(err, res){
console.log(res.text);
});
Use this, If it shows the error of UTF-8
pd.read_csv('File_name.csv',encoding='latin-1')
For your case Elasticdump is the perfect answer.
First, you need to download the mapping and then the index
# Install the elasticdump
npm install elasticdump -g
# Dump the mapping
elasticdump --input=http://<your_es_server_ip>:9200/index --output=es_mapping.json --type=mapping
# Dump the data
elasticdump --input=http://<your_es_server_ip>:9200/index --output=es_index.json --type=data
If you want to dump the data on any server I advise you to install esdump through docker. You can get more info from this website Blog Link
Some useful are:
Free:
Paid:
The best entries in my opinion are Flexigrid and jQuery Grid.
I found the highest voted answer (hometoast's answer) doesn't work perfectly for me. Two problems:
The following is a modified version:
^((http[s]?|ftp):\/)?\/?([^:\/\s]+)(:([^\/]*))?((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(\?([^#]*))?(#(.*))?$
Position of parts are as follows:
int SCHEMA = 2, DOMAIN = 3, PORT = 5, PATH = 6, FILE = 8, QUERYSTRING = 9, HASH = 12
Edit posted by anon user:
function getFileName(path) {
return path.match(/^((http[s]?|ftp):\/)?\/?([^:\/\s]+)(:([^\/]*))?((\/[\w\/-]+)*\/)([\w\-\.]+[^#?\s]+)(\?([^#]*))?(#(.*))?$/i)[8];
}
If you can modify the client, then have it print out the remote reference and you will see what port it's using. E.g.
ServerApi server = (ServerApi) registry.lookup(ServerApi.RMI_NAME);
System.out.println("Got server handle " + server);
will produce something like:
Got server handle Proxy[ServerApi,RemoteObjectInvocationHandler[UnicastRef [liveRef: [endpoint:172.17.3.190:9001,objID:[-7c63fea8:...
where you can see the port is 9001. If the remote class is not specifying the port, then it will change across reboots. If you want to use a fixed port then you need to make sure the remote class constructor does something like:
super(rmiPort)
You need to redefine the unnamed struct during &Configuration{}
package main
import "fmt"
type Configuration struct {
Val string
Proxy struct {
Address string
Port string
}
}
func main() {
c := &Configuration{
Val: "test",
Proxy: struct {
Address string
Port string
}{
Address: "127.0.0.1",
Port: "8080",
},
}
fmt.Println(c)
}
You can just run the command
git parent
to find the parent of the branch, if you add the @Joe Chrysler's answer as a git alias. It will simplify the usage.
Open gitconfig file located at "~/.gitconfig"
by using any text editor. ( For linux). And for Windows the ".gitconfig" path is generally located at c:\users\your-user\.gitconfig
vim ~/.gitconfig
Add the following alias command in the file:
[alias]
parent = "!git show-branch | grep '*' | grep -v \"$(git rev-parse --abbrev-ref HEAD)\" | head -n1 | sed 's/.*\\[\\(.*\\)\\].*/\\1/' | sed 's/[\\^~].*//' #"
Save and exit the editor.
Run the command git parent
That's it!
You can just create the required CORS configuration as a bean. As per the code below this will allow all requests coming from any origin. This is good for development but insecure. Spring Docs
@Bean
WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
}
}
}
str_replace(PHP_EOL, null, $str);
>>> import os
>>> os.path.basename(os.path.dirname(<your_path>))
For example in Ubuntu:
>>> my_path = '/home/user/documents'
>>> os.path.basename(os.path.dirname(my_path))
# Output: 'user'
For example in Windows:
>>> my_path = 'C:\WINDOWS\system32'
>>> os.path.basename(os.path.dirname(my_path))
# Output: 'WINDOWS'
Both examples tried in Python 2.7
I just installed Linux Mint 19 (based on Ubuntu 18.04) on my machine. I installed MySQL 5.7 from the repo (sudo apt install mysql-server) and surprisingly during installation, the setup didn't prompt to enter root password. As a result I wasn't able to login into MySQL. I googled here and there and tried various answers I found on the net, including the accepted answer above. I uninstalled (purging all dpkgs with mysql in its name) and reinstalled again from the default Linux Mint repositories. NONE works.
After hours of unproductive works, I decided to reinstall MySQL from the official page. I opened MySQL download page (https://dev.mysql.com/downloads/repo/apt) for apt repo and clicked Download button at the bottom right.
Next, run it with dpkg:
sudo dpkg -i mysql-apt-config_0.8.10-1_all.deb
At the installation setup, choose the MySQL version that you'd like to install. The default option is 8.0 but I changed it to 5.7. Click OK to quit. After this, you have a new MySQL repo in your Software Sources.
Update your repo:
sudo apt update
Finally, install MySQL:
sudo apt install mysql-server
And now I was prompted to provide root password! Hope it helps for others with this same experience.
There is also a type - JTokenType.Undefined.
This check must be included in @Brian Rogers answer.
token.Type == JTokenType.Undefined
I ran into this on Python 3 and found this question (and solution). When opening a file, Python 3 supports the encoding keyword to automatically handle the encoding.
Without it, the BOM is included in the read result:
>>> f = open('file', mode='r')
>>> f.read()
'\ufefftest'
Giving the correct encoding, the BOM is omitted in the result:
>>> f = open('file', mode='r', encoding='utf-8-sig')
>>> f.read()
'test'
Just my 2 cents.
describe formatted <table_name>;
inside hive shell.
Notice the "Location" value that shows the location of the table.
Try this
$.trim($("#spa").val()).length > 0
It will not treat any white space if any as a correct value
My problem was int Main() instead of int main()
good luck
For file operations, Python uses the operating system's default buffering unless you configure it do otherwise. You can specify a buffer size, unbuffered, or line buffered.
For example, the open function takes a buffer size argument.
http://docs.python.org/library/functions.html#open
"The optional buffering argument specifies the file’s desired buffer size:"
code:
bufsize = 0
f = open('file.txt', 'w', buffering=bufsize)
SELECT q'[Alex's Tea Factory]' FROM DUAL
I didnt see here mentions about dump file extension (*.dump).
This solution worked for me:
I got a dump file and needed to recover it.
First I tried to do this with pg_restore
and got:
pg_restore: error: input file appears to be a text format dump. Please use psql.
I did it with psql
and worked well:
psql -U myUser-d myDataBase < path_to_the_file/file.dump
I met a similar problem when I tried to store my existing repo in my Ubunt One
account, I fixed it by the following steps:
Step-1: create remote repo
$ cd ~/Ubuntu\ One/
$ mkdir <project-name>
$ cd <project-name>
$ mkdir .git
$ cd .git
$ git --bare init
Step-2: add the remote
$ git remote add origin /home/<linux-user-name>/Ubuntu\ One/<project-name>/.git
Step-3: push the exising git reop to the remote
$ git push -u origin --all
import datetime and then the magic timedelta stuff:
In [63]: datetime.datetime.now()
Out[63]: datetime.datetime(2010, 12, 27, 14, 39, 19, 700401)
In [64]: datetime.datetime.now() - datetime.timedelta(minutes=15)
Out[64]: datetime.datetime(2010, 12, 27, 14, 24, 21, 684435)
What worked for me was,
chmod -R 0777 /opt/lampp/htdocs/
127.0.0.1 restricts access on every interface on port 8000 except development computer. change it to 0.0.0.0:8000 this will allow connection from curl.
SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
sdf.setLenient(false);
By default this is set to TRUE. So even strings of wrong format return good values.
I have used it something like this :
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
formatter.setLenient(false);
String value = "1990/13/23";
try {
Date date = formatter.parse(value);
System.out.println(date);
}catch (ParseException e)
{
System.out.println("its bad");
}
You do
printf ("Hi %s,</br />", $name);
before setting the cookies, which isn't allowed. You can't send any output before the headers, not even a blank line.
I have a slightly different approach. I wanted to make use of the existing functions (like insert_at(index), delete_from(index)) to reverse the list (something like a right shift operation). The complexity is still O(n) but the advantage is more reused code. Have a look at another_reverse() method and let me know what you all think.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
struct node* head = NULL;
void printList(char* msg) {
struct node* current = head;
printf("\n%s\n", msg);
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
}
void insert_beginning(int data) {
struct node* newNode = (struct node*) malloc(sizeof(struct node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL)
{
head = newNode;
} else {
newNode->next = head;
head = newNode;
}
}
void insert_at(int data, int location) {
struct node* newNode = (struct node*) malloc(sizeof(struct node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL)
{
head = newNode;
}
else {
struct node* currentNode = head;
int index = 0;
while (currentNode != NULL && index < (location - 1)) {
currentNode = currentNode->next;
index++;
}
if (currentNode != NULL)
{
if (location == 0) {
newNode->next = currentNode;
head = newNode;
} else {
newNode->next = currentNode->next;
currentNode->next = newNode;
}
}
}
}
int delete_from(int location) {
int retValue = -1;
if (location < 0 || head == NULL)
{
printf("\nList is empty or invalid index");
return -1;
} else {
struct node* currentNode = head;
int index = 0;
while (currentNode != NULL && index < (location - 1)) {
currentNode = currentNode->next;
index++;
}
if (currentNode != NULL)
{
// we've reached the node just one prior to the one we want to delete
if (location == 0) {
if (currentNode->next == NULL)
{
// this is the only node in the list
retValue = currentNode->data;
free(currentNode);
head = NULL;
} else {
// the next node should take its place
struct node* nextNode = currentNode->next;
head = nextNode;
retValue = currentNode->data;
free(currentNode);
}
} // if (location == 0)
else {
// the next node should take its place
struct node* nextNode = currentNode->next;
currentNode->next = nextNode->next;
if (nextNode != NULL
) {
retValue = nextNode->data;
free(nextNode);
}
}
} else {
printf("\nInvalid index");
return -1;
}
}
return retValue;
}
void another_reverse() {
if (head == NULL)
{
printf("\nList is empty\n");
return;
} else {
// get the tail pointer
struct node* tailNode = head;
int index = 0, counter = 0;
while (tailNode->next != NULL) {
tailNode = tailNode->next;
index++;
}
// now tailNode points to the last node
while (counter != index) {
int data = delete_from(index);
insert_at(data, counter);
counter++;
}
}
}
int main(int argc, char** argv) {
insert_beginning(4);
insert_beginning(3);
insert_beginning(2);
insert_beginning(1);
insert_beginning(0);
/* insert_at(5, 0);
insert_at(4, 1);
insert_at(3, 2);
insert_at(1, 1);*/
printList("Original List\0");
//reverse_list();
another_reverse();
printList("Reversed List\0");
/* delete_from(2);
delete_from(2);*/
//printList();
return 0;
}
You could use diff
with following output formatting:
diff --old-line-format='' --unchanged-line-format='' file1 file2
--old-line-format=''
, disable output for file1 if line was differ compare in file2.
--unchanged-line-format=''
, disable output if lines were same.
The accepted answer didn't work for me as my page jumped slightly on click, messing up my scroll animation.
I decided to update the entire URL using window.history.replaceState
rather than using the window.location.hash
method. Thus circumventing the hashChange event fired by the browser.
// Only fire when URL has anchor
$('a[href*="#"]:not([href="#"])').on('click', function(event) {
// Prevent default anchor handling (which causes the page-jumping)
event.preventDefault();
if ( location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname ) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if ( target.length ) {
// Smooth scrolling to anchor
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
// Update URL
window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash);
}
}
});
Hey this is not a big issue what you need to do is.....
1. Run your cmd as administrator.
2.What you will see is like this
c:\windows\system32>
3.Go to your bin location by using cd..
like C:\mysql\bin(my location of bin in my computer is what you are seeing so chose yours correctly)
4.C:\mysql\bin>mysql --install
Service successfully installed.
5.C:\mysql\bin>NET START MySql
The MySql service is starting
The MySql service was started successfully
Then last step is
6.C:\mysql\bin>mysql -u root - p admin
It will ask for password don't enter anything first time because it will use blank, n just press enter you are done.
N later you can set password too...:)
With awk:
curl -sS http://the_repo/com/stackoverflow/the_artifact/maven-metadata.xml | grep latest | awk -F'<latest>' '{print $2}' | awk -F'</latest>' '{print $1}'
With sed:
curl -sS http://the_repo/com/stackoverflow/the_artifact/maven-metadata.xml | grep latest | sed 's:<latest>::' | sed 's:</latest>::'
Casting never needs a new
:
Collection<T> collection = myList;
You don't even make the cast explicit, because Collection
is a super-type of List
, so it will work just like this.
I too had the same problem, but solved after disabling the compiler and again reinstalling the extension. Disable of the compiler can be done by system-> configration-> tools-> compilation.. Here Disable the process... Good Luck
Thanks to both sipwiz and MrEvil. We developed a PHP script that will parse the URL that the user enters and paste www
to the top of it. (e.g. if the customer enters kiragiannis.com, then it will redirect to www.kiragiannis.com). So our customer point their root (e.g. customer1.com
to A
record where our web redirector is) and then www
CNAME
to the real A
record managed by us.
Below the code in case you are interested for future us.
<?php
$url = strtolower($_SERVER["HTTP_HOST"]);
if(strpos($url, "//") !== false) { // remove http://
$url = substr($url, strpos($url, "//") + 2);
}
$urlPagePath = "";
if(strpos($url, "/") !== false) { // store post-domain page path to append later
$urlPagePath = substr($url, strpos($url, "/"));
$url = substr($url, 0, strpos($url,"/"));
}
$urlLast = substr($url, strrpos($url, "."));
$url = substr($url, 0, strrpos($url, "."));
if(strpos($url, ".") !== false) { // get rid of subdomain(s)
$url = substr($url, strrpos($url, ".") + 1);
}
$url = "http://www." . $url . $urlLast . $urlPagePath;
header( "Location:{$url}");
?>
Yes, it will be possible and it won't be that difficult. All what's needed at this point to start with is some kind of converter that will turn MSIL into Dalvik bytecode. Since both formats are open-sourced and well documented, there won't be any problem with it.
So, writing Android applications in C# or VB.NET will be possible, question is how much of .NET framework standard libraries will be supported. But that's another issue.
Oscar Reyes wrote:
I'm pretty sure if google hand ANY interest in .net, they would've design something while Android was in the first stages, not now when they are in production stages. I don't mean it is not possible, what I'm saying is they're not interested. Maybe in mmm hhhh 10 yrs.
Actually what they've already designed is very compatible with Java and .NET
They can't do everything at once, but if you look into Android SDK, there is a tool called dx. This tool converts Java bytecode into Dalvik bytecode, so in other words, you can run programs written in Java on Android with no effort today. Now the same tool is needed for .NET.
Considering how similar .NET and Java are, it's really a matter of time.
ddimitrov wrote:
The .Net->Java->Dalvik translation can be done even now (http://dev.mainsoft.com/), but I think you underestimate the lack of .Net libraries. Of course somebody can port Mono, but it's definitely a non-trivial effort.
No need to port Mono. Android already has VM and some basic API. All what's needed is CIL->Dalvik converter and tiny .NET wrapper for Android API (and maybe some basic implementation of some standard .NET classes). That's it.
Update: .NET already works on Android - you will need product called Monodroid (http://monodroid.net) as stated above.
Try setting display:none
to hide and set display:block
to show.
Posting parameters Using POST:-
URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
The part which you missed is in the the following... i.e., as follows..
// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();
The rest of the thing you can do it.
There is no equivalent of C# async/await in Java at the language level. A concept known as Fibers aka cooperative threads aka lightweight threads could be an interesting alternative. You can find Java libraries providing support for fibers.
Java libraries implementing Fibers
You can read this article (from Quasar) for a nice introduction to fibers. It covers what threads are, how fibers can be implemented on the JVM and has some Quasar specific code.
One thing that has not been mentioned in these answers is that if you are using IIS and have sub applications with their own separate web.config, you may need to have a web.config in the parent directory containing the following code.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS"/>
</customHeaders>
</httpProtocol>
lines=[]
with open('file') as file:
lines.append(file.readline())
Coming very late to the party, I found that ✓
(✓) worked in Opera. I haven't tested it on any other browsers, but it might be useful for some people.
I know this might be considered 'wasteful', but in this scenario I often store the key as an additional column in the value record:
d = {'key1' : ('key1', val, val...), 'key2' : ('key2', val, val...) }
it's a tradeoff and feels wrong, but it's simple and works and of course depends on values being tuples rather than simple values.
Caesar's solution is the best in my opinion, but if you still insist to use the strcpy
function, then after you have your strings ready:
string a = "text";
string b = "image";
You can try either:
strcpy(a.data(), b.data());
or
strcpy(a.c_str(), b.c_str());
Just call either the data()
or c_str()
member functions of the std::string
class, to get the char*
pointer of the string object.
The strcpy()
function doesn't have overload to accept two std::string
objects as parameters.
It has only one overload to accept two char*
pointers as parameters.
Both data
and c_str
return what does strcpy()
want exactly.
var str="stack overflow";
firstChar = str.charAt(0);
secondChar = str.charAt(1);
Tested in IE6+, FF, Chrome, safari.
bat command to start mongodb
create one folder for database like in this example r0
start /d "{path}\bin" mongod.exe --replSet foo --port 27017 --dbpath {path}mongoDataBase\r0
start /d "{path}\bin" mongo.exe 127.0.0.1:27017
In LINQ you can solve it the following way:
Item itemMax = (from i in items
let maxId = items.Max(m => m.ID)
where i.ID == maxId
select i).FirstOrDefault();
Short answer: While it's technically possible to send 100k e-mails each week yourself, the simplest, easiest and cheapest solution is to outsource this to one of the companies that specialize in it (I did say "cheapest": there's no limit to the amount of development time (and therefore money) that you can sink into this when trying to DIY).
Long answer: If you decide that you absolutely want to do this yourself, prepare for a world of hurt (after all, this is e-mail/e-fail we're talking about). You'll need:
mail()
is horrible enough by itself)Surprisingly, that was the easy part. The hard part is actually sending it:
And to top it off, you'll have to manage the legal part of it (various federal, state, and local laws; and even different tangles of laws once you send outside the U.S. (note: you have no way of finding if [email protected] lives in Southwest Elbonia, the country with world's most draconian antispam laws)).
I'm pretty sure I missed a few heads of this hydra - are you still sure you want to do this yourself? If so, there'll be another wave, this time merely the annoying problems inherent in sending an e-mail. (You see, SMTP is a store-and-forward protocol, which means that your e-mail will be shuffled across many SMTP servers around the Internet, in the hope that the next one is a bit closer to the final recipient. Basically, the e-mail is sent to an SMTP server, which puts it into its forward queue; when time comes, it will forward it further to a different SMTP server, until it reaches the SMTP server for the given domain. This forward could happen immediately, or in a few minutes, or hours, or days, or never.) Thus, you'll see the following issues - most of which could happen en route as well as at the destination:
<blink>
is not your friend here, nor is <font color=...>
)and it'll be your job to troubleshoot and solve this (hint: you can't, mostly). The people who run a legit mass-mailing businesses know that in the end you can't solve it, and that they can't solve it either - and they have the reasons well researched, documented and outlined (maybe even as a Powerpoint presentation - complete with sounds and cool transitions - that your bosses can understand), as they've had to explain this a million times before. Plus, for the problems that are actually solvable, they know very well how to solve them.
If, after all this, you are not discouraged and still want to do this, go right ahead: it's even possible that you'll find a better way to do this. Just know that the road ahead won't be easy - sending e-mail is trivial, getting it delivered is hard.
From Wikipedia's Virtual function ...
In object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part of the (runtime) polymorphism portion of object-oriented programming (OOP). In short, a virtual function defines a target function to be executed, but the target might not be known at compile time.
Unlike a non-virtual function, when a virtual function is overridden the most-derived version is used at all levels of the class hierarchy, rather than just the level at which it was created. Therefore if one method of the base class calls a virtual method, the version defined in the derived class will be used instead of the version defined in the base class.
This is in contrast to non-virtual functions, which can still be overridden in a derived class, but the "new" version will only be used by the derived class and below, but will not change the functionality of the base class at all.
whereas..
A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract.
When a pure virtual method exists, the class is "abstract" and can not be instantiated on its own. Instead, a derived class that implements the pure-virtual method(s) must be used. A pure-virtual isn't defined in the base-class at all, so a derived class must define it, or that derived class is also abstract, and can not be instantiated. Only a class that has no abstract methods can be instantiated.
A virtual provides a way to override the functionality of the base class, and a pure-virtual requires it.
This will happen when you doubleclick a JAR file in Windows explorer, but the JAR is by itself actually not an executable JAR. A real executable JAR should have at least a class with a main()
method and have it referenced in MANIFEST.MF
.
In Eclispe, you need to export the project as Runnable JAR file instead of as JAR file to get a real executable JAR.
Or, if your JAR is solely a container of a bunch of closely related classes (a library), then you shouldn't doubleclick it, but open it using some ZIP tool. Windows explorer namely by default associates JAR files with java.exe
, which won't work for those kind of libary JARs.
None of the other answers were working for me. I ended up creating a function within my iframe that returns the object I was looking for:
function getElementWithinIframe() {
return document.getElementById('copy-sheet-form');
}
Then you call that function like so to retrieve the element:
var el = document.getElementById("iframeId").contentWindow.functionNameToCall();
str_replace will do the trick thusly
$new_str = str_replace(' ', '', $old_str);
First off, when you create a "bare repository", you're not going to be doing any work with it (it doesn't contain a working copy, so the git branch
command is not useful).
Now, the reason you wouldn't have a master
branch even after doing a git init
is that there are no commits: when you create your first commit, you will then have a master
branch.
It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1
is null or ConfigurationManager.AppSettings.Get("Url")
is returning null.
Dictionary maintains no order , so before picking top N key value pairs lets make it sorted.
import operator
d = {'a': 3, 'b': 2, 'c': 3, 'd': 4}
d=dict(sorted(d.items(),key=operator.itemgetter(1),reverse=True))
#itemgetter(0)=sort by keys, itemgetter(1)=sort by values
Now we can do the retrieval of top 'N' elements:, using the method structure like this:
def return_top(elements,dictionary_element):
'''Takes the dictionary and the 'N' elements needed in return
'''
topers={}
for h,i in enumerate(dictionary_element):
if h<elements:
topers.update({i:dictionary_element[i]})
return topers
to get the top 2 elements then simply use this structure:
d = {'a': 3, 'b': 2, 'c': 3, 'd': 4}
d=dict(sorted(d.items(),key=operator.itemgetter(1),reverse=True))
d=return_top(2,d)
print(d)
you have id="#message"
... should be id="message"
Unless you've messed with your server, yes it's cached. All the browsers are supposed to handle it the same. Some people (like me) might have their browsers configured so that it doesn't cache any files though. Closing the browser doesn't invalidate the file in the cache. Changing the file on the server should cause a refresh of the file however.
You can look at the query cache: http://www.databasejournal.com/features/mysql/article.php/3110171/MySQLs-Query-Cache.htm but it might not give you access to the actual queries and will be very hit-and-miss if it did work (subtle pun intended)
But MySQL Query Browser very likely maintains its own list of queries that it runs, outside of the MySQL engine. You would have to do the same in your app.
Edit: see dan m's comment leading to this: How to show the last queries executed on MySQL? looks sound.
You are looking for the OS native module for Node.js:
v4: https://nodejs.org/dist/latest-v4.x/docs/api/os.html#os_os_platform
or v5 : https://nodejs.org/dist/latest-v5.x/docs/api/os.html#os_os_platform
os.platform()
Returns the operating system platform. Possible values are 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'. Returns the value of process.platform.
Here author performed tests showed that integer unix timestamp is better than DateTime. Note, he used MySql. But I feel no matter what DB engine you use comparing integers are slightly faster than comparing dates so int index is better than DateTime index. Take T1 - time of comparing 2 dates, T2 - time of comparing 2 integers. Search on indexed field takes approximately O(log(rows)) time because index based on some balanced tree - it may be different for different DB engines but anyway Log(rows) is common estimation. (if you not use bitmask or r-tree based index). So difference is (T2-T1)*Log(rows) - may play role if you perform your query oftenly.
If you're coming to this answer directly from a search, make sure you have already added the csrf token to your form with {{ csrf_field() }}
like the OP.
If you have your session driver set to file:
May have something to do with the storage_path not being writable. This is where it stores session data regarding tokens if you're using file based sessions. The can be verified with is_writable(config('session.files'))
For the OP, the session driver was set to array. Array is for testing only. Since data is not persisted, it will not be able to compare the token on the next request.
The array driver is used during testing and prevents the data stored in the session from being persisted.
https://laravel.com/docs/5.5/session#configuration
Check config/session.php
Lastly, an issue I just had, we had a project which has the session domain and secure settings in config/session.php but the development site was not using HTTPS (SSL/TLS). This caused this generic error since sessions.secure was set to true by default.
Looking at Apple's sample code I came across this pattern. I'm not sure how Swift deals with statics, but this would be thread safe in C#. I include both the property and method for Objective-C interop.
struct StaticRank {
static let shared = RankMapping()
}
class func sharedInstance() -> RankMapping {
return StaticRank.shared
}
class var shared:RankMapping {
return StaticRank.shared
}
With your example:
<input type="checkbox" id="c2" name="c2" value="DE039230952"/>
Replace $$ with document.querySelectorAll in the examples:
$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230
Use the examples directly with:
const $$ = document.querySelectorAll.bind(document);
Some additions:
$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()
There's always the hardware route. Purchase two USB to serial converters, and connect them via a NULL modem.
Pro tips: 1) Windows may assign new COM ports to the adapters after every device sleep or reboot. 2) The market leaders in chips for USB to serial are Prolific and FTDI. Both companies are battling knockoffs, and may be blocked in future official Windows drivers. The Linux drivers however work fine with the clones.
You need to make sure the standalone ChromeDriver binary (which is different than the Chrome browser binary) is either in your path or available in the webdriver.chrome.driver environment variable.
see http://code.google.com/p/selenium/wiki/ChromeDriver for full information on how wire things up.
Edit:
Right, seems to be a bug in the Python bindings wrt reading the chromedriver binary from the path or the environment variable. Seems if chromedriver is not in your path you have to pass it in as an argument to the constructor.
import os
from selenium import webdriver
chromedriver = "/Users/adam/Downloads/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
driver.get("http://stackoverflow.com")
driver.quit()
To load data via a GET request you don't need any URLRequest
(and no semicolons)
let listUrlString = "http://bla.com?batchSize=" + String(batchSize) + "&fromIndex=" + String(fromIndex)
let myUrl = URL(string: listUrlString)!
let task = URLSession.shared.dataTask(with: myUrl) { ...
One more approach, what you can do is
// get your optionals first
Optional<String> p1 = otherObject.getP1();
Optional<BigInteger> p2 = otherObject.getP2();
// bind values to a function
Supplier<Integer> calculatedValueSupplier = () -> { // your logic here using both optional as state}
Once you have built a function(supplier in this case) you will be able to pass this around as any other variable and would be able to call it using
calculatedValueSupplier.apply();
The idea here being whether you have got optional value or not will be internal detail of your function and will not be in parameter. Thinking functions when thinking about optional as parameter is actually very useful technique that I have found.
As to your question whether you should actually do it or not is based on your preference, but as others said it makes your API ugly to say the least.
https://php.net/manual/en/function.pathinfo.php
pathinfo($path, PATHINFO_FILENAME);
Simple functional test: https://ideone.com/POhIDC
From the Object.toString
docs:
Returns a string representation of the object. In general, the
toString
method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.The
toString
method for classObject
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Example:
String[] mystr ={"a","b","c"};
System.out.println("mystr.toString: " + mystr.toString());
output:- mystr.toString: [Ljava.lang.String;@13aaa14a
I know this post is old, but I had a Situation like this and just want to share my solution. All the answers above work fine. But if you have a Code such as those in data.table chaining Syntax it becomes abit challenging. e.g. I had a Problem like this.
mass <- files[, Veg:=tstrsplit(files$file, "/")[1:4][[1]]][, Rain:=tstrsplit(files$file, "/")[1:4][[2]]][, Roughness:=tstrsplit(files$file, "/")[1:4][[3]]][, Geom:=tstrsplit(files$file, "/")[1:4][[4]]][
time_[s]<=12000]
I tried most of the suggestions above and they didn´t work. but I figured out that they can be split after the comma within []
. Splitting at ][
doesn´t work.
mass <- files[, Veg:=tstrsplit(files$file, "/")[1:4][[1]]][,
Rain:=tstrsplit(files$file, "/")[1:4][[2]]][,
Roughness:=tstrsplit(files$file, "/")[1:4][[3]]][,
Geom:=tstrsplit(files$file, "/")[1:4][[4]]][`time_[s]`<=12000]
for block elements:
<textarea style="width:100px; word-wrap:break-word;">_x000D_
ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTC_x000D_
</textarea>
_x000D_
for inline elements:
<span style="width:100px; word-wrap:break-word; display:inline-block;"> _x000D_
ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTC_x000D_
</span>
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function scollPos() {
var div = document.getElementById("myDiv").scrollTop;
document.getElementById("pos").innerHTML = div;
}
</script>
</head>
<body>
<form id="form1">
<div id="pos">
</div>
<div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
Place some large content here
</div>
</form>
</body>
</html>
They are stored in the CGI fieldstorage object.
import cgi
form = cgi.FieldStorage()
print "The user entered %s" % form.getvalue("uservalue")
see below code it may help you.
String q = "SELECT * FROM customer";
Cursor mCursor = mDb.rawQuery(q, null);
or
String q = "SELECT * FROM customer WHERE _id = " + customerDbId ;
Cursor mCursor = mDb.rawQuery(q, null);
I've stored a script in my gist to download an extension from the marketplace using a PowerShell script. Feel free to comment of share it.
https://gist.github.com/azurekid/ca641c47981cf8074aeaf6218bb9eb58
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[string] $Publisher,
[Parameter(Mandatory = $true)]
[string] $ExtensionName,
[Parameter(Mandatory = $true)]
[ValidateScript( {
If ($_ -match "^([0-9].[0-9].[0-9])") {
$True
}
else {
Throw "$_ is not a valid version number. Version can only contain digits"
}
})]
[string] $Version,
[Parameter(Mandatory = $true)]
[string] $OutputLocation
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
Write-Output "Publisher: $($Publisher)"
Write-Output "Extension name: $($ExtensionName)"
Write-Output "Version: $($Version)"
Write-Output "Output location $($OutputLocation)"
$baseUrl = "https://$($Publisher).gallery.vsassets.io/_apis/public/gallery/publisher/$($Publisher)/extension/$($ExtensionName)/$($Version)/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage"
$outputFile = "$($Publisher)-$($ExtensionName)-$($Version).visx"
if (Test-Path $OutputLocation) {
try {
Write-Output "Retrieving extension..."
[uri]::EscapeUriString($baseUrl) | Out-Null
Invoke-WebRequest -Uri $baseUrl -OutFile "$OutputLocation\$outputFile"
}
catch {
Write-Error "Unable to find the extension in the marketplace"
}
}
else {
Write-Output "The Path $($OutputLocation) does not exist"
}
This should handle addition/subtraction, just put a negative value in to subtract and a positive value to add. This also solves the month crossover problem.
function monthAdd(date, month) {
var temp = date;
temp = new Date(date.getFullYear(), date.getMonth(), 1);
temp.setMonth(temp.getMonth() + (month + 1));
temp.setDate(temp.getDate() - 1);
if (date.getDate() < temp.getDate()) {
temp.setDate(date.getDate());
}
return temp;
}
Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');
The second one is normally used for case-sensitive column names.
This is an answer I've already given some time ago:
It depends entirely on the domain-specific application needs. A lot of times direct text file/binary files access can be extremely fast, efficient, as well as providing you all the file access capabilities of your OS's file system.
Furthermore, your programming language most likely already has a built-in module (or is easy to make one) for specific parsing.
If what you need is many appends (INSERTS?) and sequential/few access little/no concurrency, files are the way to go.
On the other hand, when your requirements for concurrency, non-sequential reading/writing, atomicity, atomic permissions, your data is relational by the nature etc., you will be better off with a relational or OO database.
There is a lot that can be accomplished with SQLite3, which is extremely light (under 300kb), ACID compliant, written in C/C++, and highly ubiquitous (if it isn't already included in your programming language -for example Python-, there is surely one available). It can be useful even on db files as big as 140 terabytes, or 128 tebibytes (Link to Database Size), possible more.
If your requirements where bigger, there wouldn't even be a discussion, go for a full-blown RDBMS.
As you say in a comment that "the system" is merely a bunch of scripts, then you should take a look at pgbash.
function endDate(){
$.validator.addMethod("endDate", function(value, element) {
var params = '.startDate';
if($(element).parent().parent().find(params).val()!=''){
if (!/Invalid|NaN/.test(new Date(value))) {
return new Date(value) > new Date($(element).parent().parent().find(params).val());
}
return isNaN(value) && isNaN($(element).parent().parent().find(params).val()) || (parseFloat(value) > parseFloat($(element).parent().parent().find(params).val())) || value == "";
}else{
return true;
}
},jQuery.format('must be greater than start date'));
}
function startDate(){
$.validator.addMethod("startDate", function(value, element) {
var params = '.endDate';
if($(element).parent().parent().parent().find(params).val()!=''){
if (!/Invalid|NaN/.test(new Date(value))) {
return new Date(value) < new Date($(element).parent().parent().parent().find(params).val());
}
return isNaN(value) && isNaN($(element).parent().parent().find(params).val()) || (parseFloat(value) < parseFloat($(element).parent().parent().find(params).val())) || value == "";
}
else{
return true;
}
}, jQuery.format('must be less than end date'));
}
Hope this will help :)
To customize the colors for the carousel controls, captions, and indicators using Sass you can include these variables
$carousel-control-color:
$carousel-caption-color:
$carousel-indicator-active-bg:
Here's a tidy solution where you provide the target date as a Calendar object.
// Used to translate the Month value of a JQuery calendar to the month value expected by a Calendar.
private static final Map<String,Integer> MONTH_TO_CALENDAR_INDEX = new HashMap<String,Integer>();
static {
MONTH_TO_CALENDAR_INDEX.put("January", 0);
MONTH_TO_CALENDAR_INDEX.put("February",1);
MONTH_TO_CALENDAR_INDEX.put("March",2);
MONTH_TO_CALENDAR_INDEX.put("April",3);
MONTH_TO_CALENDAR_INDEX.put("May",4);
MONTH_TO_CALENDAR_INDEX.put("June",5);
MONTH_TO_CALENDAR_INDEX.put("July",6);
MONTH_TO_CALENDAR_INDEX.put("August",7);
MONTH_TO_CALENDAR_INDEX.put("September",8);
MONTH_TO_CALENDAR_INDEX.put("October",9);
MONTH_TO_CALENDAR_INDEX.put("November",10);
MONTH_TO_CALENDAR_INDEX.put("December",11);
}
// ====================================================================================================
// setCalendarPicker
// ====================================================================================================
/**
* Sets the value of specified web element while assuming the element is a JQuery calendar.
* @param byOpen The By phrase that locates the control that opens the JQuery calendar when clicked.
* @param byPicker The By phrase that locates the JQuery calendar.
* @param targetDate The target date that you want set.
* @throws AssertionError if the method is unable to set the date.
*/
public void setCalendarPicker(By byOpen, By byPicker, Calendar targetDate) {
// Open the JQuery calendar.
WebElement opener = driver.findElement(byOpen);
opener.click();
// Locate the JQuery calendar.
WebElement picker = driver.findElement(byPicker);
// Calculate the target and current year-and-month as an integer where value = year*12+month.
// The difference between the two is the number of months we have to move ahead or backward.
int targetYearMonth = targetDate.get(Calendar.YEAR) * 12 + targetDate.get(Calendar.MONTH);
int currentYearMonth = Integer.valueOf(picker.findElement(By.className("ui-datepicker-year")).getText()) * 12
+ Integer.valueOf(MONTH_TO_CALENDAR_INDEX.get(picker.findElement(By.className("ui-datepicker-month")).getText()));
// Calculate the number of months we need to move the JQuery calendar.
int delta = targetYearMonth - currentYearMonth;
// As a sanity check, let's not allow more than 10 years so that we don't inadvertently spin in a loop for zillions of months.
if (Math.abs(delta) > 120) throw new AssertionError("Target date is more than 10 years away");
// Push the JQuery calendar forward or backward as appropriate.
if (delta > 0) {
while (delta-- > 0) picker.findElement(By.className("ui-icon-circle-triangle-e")).click();
} else if (delta < 0 ){
while (delta++ < 0) picker.findElement(By.className("ui-icon-circle-triangle-w")).click();
}
// Select the day within the month.
String dayOfMonth = String.valueOf(targetDate.get(Calendar.DAY_OF_MONTH));
WebElement tableOfDays = picker.findElement(By.cssSelector("tbody:nth-child(2)"));
for (WebElement we : tableOfDays.findElements(By.tagName("td"))) {
if (dayOfMonth.equals(we.getText())) {
we.click();
// Send a tab to completely leave this control. If the next control the user will access is another CalendarPicker,
// the picker might not get selected properly if we stay on the current control.
opener.sendKeys("\t");
return;
}
}
throw new AssertionError(String.format("Unable to select specified day"));
}
Just use floatval()
.
E.g.:
$var = '122.34343';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
And in case you wonder doubleval()
is just an alias for floatval()
.
And as the other say, in a financial application, float values are critical as these are not precise enough. E.g. adding two floats could result in something like 12.30000000001
and this error could propagate.
2 problems with elements:
Use Attributes.
Also, Spring recommends only using the annotation on concrete classes and not interfaces.
http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html
You can also set cell's selectionStyle
to.none
in interface builder. The same solution as @AhmedLotfy provided, only from IB.
Actually, neither statement says anything about heap or stack. The code
Object o;
creates one of the following, depending on its context:
This means that the storage location is determined by the context in which the object is defined. In addition, the C++ standard does not talk about stack vs heap storage. Instead, it talks about storage duration, which can be either automatic, dynamic, static or thread-local. However, most implementations implement automatic storage via the call stack, and dynamic storage via the heap.
Local variables, which have automatic storage, are thus created on the stack. Static (and thread-local) objects are generally allocated in their own memory regions, neither on the stack nor on the heap. And member variables are allocated wherever the object they belong to is allocated. They have their containing object’s storage duration.
To illustrate this with an example:
struct Foo {
Object o;
};
Foo foo;
int main() {
Foo f;
Foo* p = new Foo;
Foo* pf = &f;
}
Now where is the object Foo::o
(that is, the subobject o
of an object of class Foo
) created? It depends:
foo.o
has static storage because foo
has static storage, and therefore lives neither on the stack nor on the heap.f.o
has automatic storage since f
has automatic storage (= it lives on the stack).p->o
has dynamic storage since *p
has dynamic storage (= it lives on the heap).pf->o
is the same object as f.o
because pf
points to f
.In fact, both p
and pf
in the above have automatic storage. A pointer’s storage is indistinguishable from any other object’s, it is determined by context. Furthermore, the initialising expression has no effect on the pointer storage.
The pointee (= what the pointer points to) is a completely different matter, and could refer to any kind of storage: *p
is dynamic, whereas *pf
is automatic.
This strange error, in my case was a symptom of gnome-keyring-daemon
incorrectly naming the key to which it required a password.
I follow the steps outlined here, and entered the password via the terminal. The error, aka the confounding GUI interface, was resolved. See: https://askubuntu.com/questions/3045/how-to-disable-gnome-keyring
These types of arrays are known as jagged arrays in Java:
int[][] multD = new int[3][];
multD[0] = new int[3];
multD[1] = new int[2];
multD[2] = new int[5];
In this scenario each row of the array holds the different number of columns. In the above example, the first row will hold three columns, the second row will hold two columns, and the third row holds five columns. You can initialize this array at compile time like below:
int[][] multD = {{2, 4, 1}, {6, 8}, {7, 3, 6, 5, 1}};
You can easily iterate all elements in your array:
for (int i = 0; i<multD.length; i++) {
for (int j = 0; j<multD[i].length; j++) {
System.out.print(multD[i][j] + "\t");
}
System.out.println();
}
Use and empty()
whit negation (for test if not empty)
if(!empty($_GET['id'])) {
// if get id is not empty
}
Here's the solution you're looking for:
>>> foos = [1.0, 2.0, 3.0, 4.0, 5.0]
>>> bars = [1, 2, 3]
>>> [(x, bars) for x in foos]
[(1.0, [1, 2, 3]), (2.0, [1, 2, 3]), (3.0, [1, 2, 3]), (4.0, [1, 2, 3]), (5.0, [
1, 2, 3])]
I'd recommend using a list comprehension (the [(x, bars) for x in foos]
part) over using map as it avoids the overhead of a function call on every iteration (which can be very significant). If you're just going to use it in a for loop, you'll get better speeds by using a generator comprehension:
>>> y = ((x, bars) for x in foos)
>>> for z in y:
... print z
...
(1.0, [1, 2, 3])
(2.0, [1, 2, 3])
(3.0, [1, 2, 3])
(4.0, [1, 2, 3])
(5.0, [1, 2, 3])
The difference is that the generator comprehension is lazily loaded.
UPDATE In response to this comment:
Of course you know, that you don't copy bars, all entries are the same bars list. So if you modify any one of them (including original bars), you modify all of them.
I suppose this is a valid point. There are two solutions to this that I can think of. The most efficient is probably something like this:
tbars = tuple(bars)
[(x, tbars) for x in foos]
Since tuples are immutable, this will prevent bars from being modified through the results of this list comprehension (or generator comprehension if you go that route). If you really need to modify each and every one of the results, you can do this:
from copy import copy
[(x, copy(bars)) for x in foos]
However, this can be a bit expensive both in terms of memory usage and in speed, so I'd recommend against it unless you really need to add to each one of them.
Here is a totally out of the box solution.
In the ahk script, a) Ftp the commands (.ksh) file to the linux machine
b) Use plink like below. Plink should be installed if you have putty.
plink sessionname -l username -pw password test.ksh
or
plink -ssh example.com -l username -pw password test.ksh
All the steps will be performed in sequence whenever you press F9 in windows.
For anyone trying to do this in asp.net core. You can use claims.
public class CustomEmailProvider : IUserIdProvider
{
public virtual string GetUserId(HubConnectionContext connection)
{
return connection.User?.FindFirst(ClaimTypes.Email)?.Value;
}
}
Any identifier can be used, but it must be unique. If you use a name identifier for example, it means if there are multiple users with the same name as the recipient, the message would be delivered to them as well. I have chosen email because it is unique to every user.
Then register the service in the startup class.
services.AddSingleton<IUserIdProvider, CustomEmailProvider>();
Next. Add the claims during user registration.
var result = await _userManager.CreateAsync(user, Model.Password);
if (result.Succeeded)
{
await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Email, Model.Email));
}
To send message to the specific user.
public class ChatHub : Hub
{
public async Task SendMessage(string receiver, string message)
{
await Clients.User(receiver).SendAsync("ReceiveMessage", message);
}
}
Note: The message sender won't be notified the message is sent. If you want a notification on the sender's end. Change the SendMessage
method to this.
public async Task SendMessage(string sender, string receiver, string message)
{
await Clients.Users(sender, receiver).SendAsync("ReceiveMessage", message);
}
These steps are only necessary if you need to change the default identifier. Otherwise, skip to the last step where you can simply send messages by passing userIds or connectionIds to SendMessage
. For more
My guess is that rake
is a batch program. When you invoke it without call
, then control doesn't return to your build.bat
. Try:
@echo off
cls
CALL rake
pause
Multiplies 10000 and stores as BIGINT, like "Currency" in Visual Basic and Office. See https://msdn.microsoft.com/en-us/library/office/gg264338.aspx
Maybe you can take a look at closure in JavaScript. Here is a working solution:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Test</title>_x000D_
</head>_x000D_
<body>_x000D_
<p class="button">Button 0</p>_x000D_
<p class="button">Button 1</p>_x000D_
<p class="button">Button 2</p>_x000D_
<script>_x000D_
var buttons = document.getElementsByClassName('button');_x000D_
for (var i=0 ; i < buttons.length ; i++){_x000D_
(function(index){_x000D_
buttons[index].onclick = function(){_x000D_
alert("I am button " + index);_x000D_
};_x000D_
})(i)_x000D_
}_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
I prefer this because it prevents a single item list with an empty item if your source string is empty:
IEnumerable<string> namesList =
!string.isNullOrEmpty(names) ? names.Split(',') : Enumerable.Empty<string>();
Use the random
module: http://docs.python.org/library/random.html
import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)
This samples the two values without replacement (so the two values are different).
Sorry I am very late to the party.
Let me try to explain the difference using mvn dependency:tree
command
Consider the below example
Parent POM - My Project
<modules>
<module>app</module>
<module>data</module>
</modules>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
</dependencies>
</dependencyManagement>
Child POM - data module
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>
Child POM - app module (has no extra dependency, so leaving dependencies empty)
<dependencies>
</dependencies>
On running mvn dependency:tree
command, we get following result
Scanning for projects...
------------------------------------------------------------------------
Reactor Build Order:
MyProject
app
data
------------------------------------------------------------------------
Building MyProject 1.0-SNAPSHOT
------------------------------------------------------------------------
--- maven-dependency-plugin:2.8:tree (default-cli) @ MyProject ---
com.iamvickyav:MyProject:pom:1.0-SNAPSHOT
\- com.google.guava:guava:jar:19.0:compile
------------------------------------------------------------------------
Building app 1.0-SNAPSHOT
------------------------------------------------------------------------
--- maven-dependency-plugin:2.8:tree (default-cli) @ app ---
com.iamvickyav:app:jar:1.0-SNAPSHOT
\- com.google.guava:guava:jar:19.0:compile
------------------------------------------------------------------------
Building data 1.0-SNAPSHOT
------------------------------------------------------------------------
--- maven-dependency-plugin:2.8:tree (default-cli) @ data ---
com.iamvickyav:data:jar:1.0-SNAPSHOT
+- org.apache.commons:commons-lang3:jar:3.9:compile
\- com.google.guava:guava:jar:19.0:compile
Google guava is listed as dependency in every module (including parent), whereas the apache commons is listed as dependency only in data module (not even in parent module)
for group headers/footers:
=iif(RunningValue(*group on field*,CountDistinct,"*parent group name*") Mod 2,"White","AliceBlue")
You can also use this to “reset” the row color count within each group. I wanted the first detail row in each sub group to start with White and this solution (when used on the detail row) allowed that to happen:
=IIF(RunningValue(Fields![Name].Value, CountDistinct, "NameOfPartnetGroup") Mod 2, "White", "Wheat")
See: http://msdn.microsoft.com/en-us/library/ms159136(v=sql.100).aspx
convert_dtypes
The (self) accepted answer doesn't take into consideration the possibility of NaNs in object columns.
df = pd.DataFrame({
'a': [1, 2, np.nan],
'b': [True, False, np.nan]}, dtype=object)
df
a b
0 1 True
1 2 False
2 NaN NaN
df['a'].astype(str).astype(int) # raises ValueError
This chokes because the NaN is converted to a string "nan", and further attempts to coerce to integer will fail. To avoid this issue, we can soft-convert columns to their corresponding nullable type using convert_dtypes
:
df.convert_dtypes()
a b
0 1 True
1 2 False
2 <NA> <NA>
df.convert_dtypes().dtypes
a Int64
b boolean
dtype: object
If your data has junk text mixed in with your ints, you can use pd.to_numeric
as an initial step:
s = pd.Series(['1', '2', '...'])
s.convert_dtypes() # converts to string, which is not what we want
0 1
1 2
2 ...
dtype: string
# coerces non-numeric junk to NaNs
pd.to_numeric(s, errors='coerce')
0 1.0
1 2.0
2 NaN
dtype: float64
# one final `convert_dtypes` call to convert to nullable int
pd.to_numeric(s, errors='coerce').convert_dtypes()
0 1
1 2
2 <NA>
dtype: Int64
This is a common question in C++ programming. There are two valid answers to this. There are advantages and disadvantages to both answers and your choice will depend on context. The common answer is to put all the implementation in the header file, but there's another approach will will be suitable in some cases. The choice is yours.
The code in a template is merely a 'pattern' known to the compiler. The compiler won't compile the constructors cola<float>::cola(...)
and cola<string>::cola(...)
until it is forced to do so. And we must ensure that this compilation happens for the constructors at least once in the entire compilation process, or we will get the 'undefined reference' error. (This applies to the other methods of cola<T>
also.)
The problem is caused by the fact that main.cpp
and cola.cpp
will be compiled separately first. In main.cpp
, the compiler will implicitly instantiate the template classes cola<float>
and cola<string>
because those particular instantiations are used in main.cpp
. The bad news is that the implementations of those member functions are not in main.cpp
, nor in any header file included in main.cpp
, and therefore the compiler can't include complete versions of those functions in main.o
. When compiling cola.cpp
, the compiler won't compile those instantiations either, because there are no implicit or explicit instantiations of cola<float>
or cola<string>
. Remember, when compiling cola.cpp
, the compiler has no clue which instantiations will be needed; and we can't expect it to compile for every type in order to ensure this problem never happens! (cola<int>
, cola<char>
, cola<ostream>
, cola< cola<int> >
... and so on ...)
The two answers are:
cola.cpp
, which particular template classes will be required, forcing it to compile cola<float>
and cola<string>
.main.cpp
) uses the template class.At the end of cola.cpp
, you should add lines explicitly instantiating all the relevant templates, such as
template class cola<float>;
template class cola<string>;
and you add the following two lines at the end of nodo_colaypila.cpp
:
template class nodo_colaypila<float>;
template class nodo_colaypila<std :: string>;
This will ensure that, when the compiler is compiling cola.cpp
that it will explicitly compile all the code for the cola<float>
and cola<string>
classes. Similarly, nodo_colaypila.cpp
contains the implementations of the nodo_colaypila<...>
classes.
In this approach, you should ensure that all the of the implementation is placed into one .cpp
file (i.e. one translation unit) and that the explicit instantation is placed after the definition of all the functions (i.e. at the end of the file).
The common answer is to move all the code from the implementation files cola.cpp
and nodo_colaypila.cpp
into cola.h
and nodo_colaypila.h
. In the long run, this is more flexible as it means you can use extra instantiations (e.g. cola<char>
) without any more work. But it could mean the same functions are compiled many times, once in each translation unit. This is not a big problem, as the linker will correctly ignore the duplicate implementations. But it might slow down the compilation a little.
The default answer, used by the STL for example and in most of the code that any of us will write, is to put all the implementations in the header files. But in a more private project, you will have more knowledge and control of which particular template classes will be instantiated. In fact, this 'bug' might be seen as a feature, as it stops users of your code from accidentally using instantiations you have not tested for or planned for ("I know this works for cola<float>
and cola<string>
, if you want to use something else, tell me first and will can verify it works before enabling it.").
Finally, there are three other minor typos in the code in your question:
#endif
at the end of nodo_colaypila.hnodo_colaypila<T>* ult, pri;
should be nodo_colaypila<T> *ult, *pri;
- both are pointers.nodo_colaypila.h
, not in this implementation file.Try restarting the server with
sudo /usr/local/mysql/support-files/mysql.server start
If there is any error then follow the below steps
mysqld
You will see the the below log. Notice the highlighted portion of the MySQL directory here
mysqld: Can't change dir to '/usr/local/mysql-5.7.14-osx10.11-x86_64/data/' (Errcode: 13 - Permission denied) 2016-10-04T14:09:19.392581Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). 2016-10-04T14:09:19.392847Z 0 [Warning] Insecure configuration for --secure-file-priv: Current value does not restrict location of generated files. Consider setting it to a valid, non-empty path. 2016-10-04T14:09:19.392921Z 0 [Note] mysqld (mysqld 5.7.14) starting as process 1402 ... 2016-10-04T14:09:19.397569Z 0 [Warning] Can't create test file
/usr/local/mysql-5.7.14-osx10.11-x86_64/data/Sudharshan.lower-test
2016-10-04T14:09:19.397597Z 0 [Warning] Can't create test file /usr/local/mysql-5.7.14-osx10.11-x86_64/data/Sudharshan.lower-test
2016-10-04T14:09:19.397712Z 0 [ERROR] failed to set datadir to /usr/local/mysql-5.7.14-osx10.11-x86_64/data/
2016-10-04T14:09:19.397776Z 0 [ERROR] Aborting
2016-10-04T14:09:19.397795Z 0 [Note] Binlog end
2016-10-04T14:09:19.397925Z 0 [Note] mysqld: Shutdown complete
sudo chown -R _mysql:_mysql /usr/local/mysql-5.7.14-osx10.11-x86_64
Note the MySQL folder path /usr/local on the the previous log, and in my case it was mysql-5.7.14-osx10.11-x86_64, and you have to update it based on the log you get on your machine to provide read access to the MySQL directory
sudo /usr/local/mysql/support-files/mysql.server start
Starting MySQL
SUCCESS!
The hold on
feature is switched on by default in matplotlib.pyplot
. So each time you evoke plt.plot()
before plt.show()
a drawing is added to the plot. Launching plt.plot()
after the function plt.show()
leads to redrawing the whole picture.
As people already mentioned, it could be internet problems or proxy configuration.
I found this question when I was searching about the same problem. In my case, it was proxy configuration.
Answers posted here didn't solve my issue, because every link suggest a configuration that shows the username and passoword and I can't use it.
I was searching about it elsewere and I found a configuration to be made on settings.xml, I needed to make some changes. Here is the final code:
<profiles>
<profile>
<id>MavenRepository</id>
<repositories>
<repository>
<id>central</id>
<url>https://repo1.maven.org/maven2</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
</profile>
</profiles>
<activeProfiles>
<activeProfile>MavenRepository</activeProfile>
</activeProfiles>
I hope be useful.
For me, this js reproduces the same problem that happens with Paola
My solution:
$(document.body).tooltip({selector: '[title]'})
.on('click mouseenter mouseleave','[title]', function(ev) {
$(this).tooltip('mouseenter' === ev.type? 'show': 'hide');
});
I had the same problem and it was because the ~/.bash_profile
had invalid fi
statements.
The fix:
sudo nano ~/.bash_profile
fi
statements (the ones missing an opening if
)source ~/.bash_profile
You can create the vector idnat2
without if
and ifelse
.
The function replace
can be used to replace all occurrences of "colony"
with "overseas"
:
idnat2 <- replace(idbp, idbp == "colony", "overseas")
Do you have a _ViewStart.cshtml
in this directory? I had the same problem you're having when I tried using _ViewStart. Then I renamed it _mydefaultview, moved it to the Views/Shared
directory, and switched to specifying no view in cshtml files where I don't want it, and specifying _mydefaultview for the rest. Don't know why this was necessary, but it worked.
Shame on me...
I looked at the user guide and the first function is $this->db->insert_id();
This also works with activerecord inserts...
EDIT: I updated the link
Going down your list:
Utf32String
class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)There's more on my Unicode page and tips for debugging Unicode problems.
The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.
Because it's been a several years since this question was first asked, the other answers are outdated or incomplete.
Here's the code for a modern implementation using jQuery:
$( 'div#1' ).on( 'click', function( event ) {
if ( event.ctrlKey ) {
//is ctrl + click
} else {
//normal click
}
} );
As for detecting right-clicks, this was correctly provided by another user but I'll list it here just to have everything in one place.
$( 'div#1' ).on( 'contextmenu', function( event ) {
// right-click handler
} ) ;
You can use the text editing controller to manipulate the value inside a textfield.
var textController = new TextEditingController();
Now, create a new textfield and set textController
as the controller for the textfield as shown below.
new TextField(controller: textController)
Now, create a RaisedButton
anywhere in your code and set the desired text in the onPressed
method of the RaisedButton
.
new RaisedButton(
onPressed: () {
textController.text = "New text";
}
),
First, let's note that git push
"wants" two more arguments and will make them up automatically if you don't supply them. The basic command is therefore git push remote refspec
.
The remote
part is usually trivial as it's almost always just the word origin
. The trickier part is the refspec
. Most commonly, people write a branch name here: git push origin master
, for instance. This uses your local branch to push to a branch of the same name1 on the remote, creating it if necessary. But it doesn't have to be just a branch name.
In particular, a refspec
has two colon-separated parts. For git push
, the part on the left identifies what to push,2 and the part on the right identifies the name to give to the remote. The part on the left in this case would be branch_name
and the part on the right would be branch_name_test
. For instance:
git push origin foo:foo_test
As you are doing the push, you can tell your git push
to set your branch's upstream name at the same time, by adding -u
to the git push
options. Setting the upstream name makes your git save the foo_test
(or whatever) name, so that a future git push
with no arguments, while you're on the foo
branch, can try to push to foo_test
on the remote (git also saves the remote, origin
in this case, so that you don't have to enter that either).
You need only pass -u
once: it basically just runs git branch --set-upstream-to
for you. (If you pass -u
again later, it re-runs the upstream-setting, changing it as directed; or you can run git branch --set-upstream-to
yourself.)
However, if your git is 2.0 or newer, and you have not set any special configuration, you will run into the same kind of thing that had me enter footnote 1 above: push.default
will be set to simple
, which will refuse to push because the upstream's name differs from your own local name. If you set push.default
to upstream
, git will stop complaining—but the simplest solution is just to rename your local branch first, so that the local and remote names match. (What settings to set, and/or whether to rename your branch, are up to you.)
1More precisely, git consults your remote.remote.push
setting to derive the upstream half of the refspec. If you haven't set anything here, the default is to use the same name.
2This doesn't have to be a branch name. For instance, you can supply HEAD
, or a commit hash, here. If you use something other than a branch name, you may have to spell out the full refs/heads/branch
on the right, though (it depends on what names are already on the remote).
A clean way is to make an asynchronous API call inside componentDidMount with try/catch function.
When we called an API, we receive a response. Then we apply JSON method on it, to convert the response into a JavaScript object. Then we take from that response object only his child object named "results" (data.results).
In the beginning we defined "userList" in state as an empty array. As soon as we make the API call and receive data from that API, we assign the "results" to userList using setState method.
Inside the render function we tell that userList will be coming from state. Since the userList is an array of objects we map through it, to display a picture, a name and a phone number of each object "user". To retrieve this information we use dot notation (e.g. user.phone).
NOTE: depending on your API, your response may look different. Console.log the whole "response" to see which variables you need from it, and then assign them in setState.
UserList.js
import React, { Component } from "react";
export default class UserList extends Component {
state = {
userList: [], // list is empty in the beginning
error: false
};
componentDidMount() {
this.getUserList(); // function call
}
getUserList = async () => {
try { //try to get data
const response = await fetch("https://randomuser.me/api/");
if (response.ok) { // ckeck if status code is 200
const data = await response.json();
this.setState({ userList: data.results});
} else { this.setState({ error: true }) }
} catch (e) { //code will jump here if there is a network problem
this.setState({ error: true });
}
};
render() {
const { userList, error } = this.state
return (
<div>
{userList.length > 0 && userList.map(user => (
<div key={user}>
<img src={user.picture.medium} alt="user"/>
<div>
<div>{user.name.first}{user.name.last}</div>
<div>{user.phone}</div>
<div>{user.email}</div>
</div>
</div>
))}
{error && <div>Sorry, can not display the data</div>}
</div>
)
}}
The cleanest way is to start from a stream of indices:
String[] names = {"Sam", "Pamela", "Dave", "Pascal", "Erik"};
IntStream.range(0, names.length)
.filter(i -> names[i].length() <= i)
.mapToObj(i -> names[i])
.collect(Collectors.toList());
The resulting list contains "Erik" only.
One alternative which looks more familiar when you are used to for loops would be to maintain an ad hoc counter using a mutable object, for example an AtomicInteger
:
String[] names = {"Sam", "Pamela", "Dave", "Pascal", "Erik"};
AtomicInteger index = new AtomicInteger();
List<String> list = Arrays.stream(names)
.filter(n -> n.length() <= index.incrementAndGet())
.collect(Collectors.toList());
Note that using the latter method on a parallel stream could break as the items would not necesarily be processed "in order".
As of Python v3.6
, random.choices
could be used to return a list
of elements of specified size from the given population with optional weights.
random.choices(population, weights=None, *, cum_weights=None, k=1)
population : list
containing unique observations. (If empty, raises IndexError
)
weights : More precisely relative weights required to make selections.
cum_weights : cumulative weights required to make selections.
k : size(len
) of the list
to be outputted. (Default len()=1
)
Few Caveats:
1) It makes use of weighted sampling with replacement so the drawn items would be later replaced. The values in the weights sequence in itself do not matter, but their relative ratio does.
Unlike np.random.choice
which can only take on probabilities as weights and also which must ensure summation of individual probabilities upto 1 criteria, there are no such regulations here. As long as they belong to numeric types (int/float/fraction
except Decimal
type) , these would still perform.
>>> import random
# weights being integers
>>> random.choices(["white", "green", "red"], [12, 12, 4], k=10)
['green', 'red', 'green', 'white', 'white', 'white', 'green', 'white', 'red', 'white']
# weights being floats
>>> random.choices(["white", "green", "red"], [.12, .12, .04], k=10)
['white', 'white', 'green', 'green', 'red', 'red', 'white', 'green', 'white', 'green']
# weights being fractions
>>> random.choices(["white", "green", "red"], [12/100, 12/100, 4/100], k=10)
['green', 'green', 'white', 'red', 'green', 'red', 'white', 'green', 'green', 'green']
2) If neither weights nor cum_weights are specified, selections are made with equal probability. If a weights sequence is supplied, it must be the same length as the population sequence.
Specifying both weights and cum_weights raises a TypeError
.
>>> random.choices(["white", "green", "red"], k=10)
['white', 'white', 'green', 'red', 'red', 'red', 'white', 'white', 'white', 'green']
3) cum_weights are typically a result of itertools.accumulate
function which are really handy in such situations.
From the documentation linked:
Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.
So, either supplying weights=[12, 12, 4]
or cum_weights=[12, 24, 28]
for our contrived case produces the same outcome and the latter seems to be more faster / efficient.
Depends, if i remember correctly i think asp.net won't render the html object out when you set visible to false.
If you want to be able to control it from the client side, then you better just include the css value to set it invisible rather than using visible =false.
.row.vertical-divider {_x000D_
overflow: hidden;_x000D_
}_x000D_
.row.vertical-divider > div[class^="col-"] {_x000D_
text-align: center;_x000D_
padding-bottom: 100px;_x000D_
margin-bottom: -100px;_x000D_
border-left: 3px solid #F2F7F9;_x000D_
border-right: 3px solid #F2F7F9;_x000D_
}_x000D_
.row.vertical-divider div[class^="col-"]:first-child {_x000D_
border-left: none;_x000D_
}_x000D_
.row.vertical-divider div[class^="col-"]:last-child {_x000D_
border-right: none;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="row vertical-divider" style="margin-top: 30px">_x000D_
<div class="col-xs-6">Hi there</div>_x000D_
<div class="col-xs-6">Hi world<br/>hi world</div>_x000D_
</div>
_x000D_
If your Objects
are containing of Strings
only, then you can do it like this:
Map<String,Object> map = new HashMap<String,Object>(); //Object is containing String
Map<String,String> newMap =new HashMap<String,String>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if(entry.getValue() instanceof String){
newMap.put(entry.getKey(), (String) entry.getValue());
}
}
If every Objects
are not String
then you can replace (String) entry.getValue()
into entry.getValue().toString()
.
The problem I had was that although the source data was correctly formatted as 'date' dd/mm/yyyy, the pivot table placed (for example) 22/05/2019 between 16/05/2019 and 17/05/2019. This data was visible in the pivot table, but in the wrong place. In addition, the Pivot chart refused to show that data for that date even though the 'Date' filter allowed it to be selected.
In my case, I had to:
From the Pivot Chart,open the 'Date' Filter menu.
select the 'Sort Oldest to Newest' option.
you can set the height and width of a view in a relative layout like this
ViewGroup.LayoutParams params = view.getLayoutParams();
params.height = 130;
view.setLayoutParams(params);
Your quotes only need to surround the value part of the attribute-equals selector, [attr='val']
, like this:
$('a#check_var').click(function() {
alert($("input:radio[name='r']:checked").val()+ ' '+
$("input:radio[name='s']:checked").val());
});?
You can use the Bean Comparator to sort on any property in your custom class.
For PostgreSQL:
GROUP BY to_char(timestampfield, 'yyyy-mm-dd')
or using cast:
GROUP BY timestampfield::date
if you want speed, use the second option and add an index:
CREATE INDEX tablename_timestampfield_date_idx ON tablename(date(timestampfield));
The returned data is the binary data of the image type. If you use JavaScript to retrieve the user photo, please get the photo data as blob type in a XMLHttpRequest, and then retrieve the blob URL from the response. For your reference:
var request = new XMLHttpRequest;
var photoUri=config.endpoints.graphApiUri + "/v1.0/me/photo/$value";
request.open("GET",photoUri);
request.setRequestHeader("Authorization","Bearer "+token);
request.responseType = "blob";
request.onload = function (){
if(request.readyState == 4 && request.status == 200){
var image = document.createElement("img");
var url = window.URL || window.webkitURL;
var blobUrl = url.createObjectURL(request.response);
image.src = blobUrl;
document.getElementById("UserShow").appendChild(image);
}
};
request.send(null);
Yet another variation...
SELECT
Count(*) AS existFlag
FROM
sys.columns
WHERE
[name] = N 'ColumnName'
AND [object_id] = OBJECT_ID(N 'TableName')
For Mac Users
I am using Mac and I was facing same problem while I was trying to push a project from Android Studio. The reason for that other user had previously logged into Github and his credentials were saved in Keychain Access.
You need to remove those credentials from Keychain Access and then try to push.
Hope it help to Mac users.
You need to use the change directory command 'cd' to change directory
cd C:\Users\MyName\Desktop
you can use cd \d
to change the drive as well.
link for additional resources http://ss64.com/nt/cd.html
The two most usual choices are GTK+, which has documentation links here, and is mostly used with C; or Qt which has documentation here and is more used with C++.
I posted these two as you do not specify an operating system and these two are pretty cross-platform.
It depends what is the character and what encoding it is in:
An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits.
An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte).
A Unicode character in UTF-8 encoding is between 8 bits (1 byte) and 32 bits (4 bytes).
A Unicode character in UTF-16 encoding is between 16 (2 bytes) and 32 bits (4 bytes), though most of the common characters take 16 bits. This is the encoding used by Windows internally.
A Unicode character in UTF-32 encoding is always 32 bits (4 bytes).
An ASCII character in UTF-8 is 8 bits (1 byte), and in UTF-16 - 16 bits.
The additional (non-ASCII) characters in ISO-8895-1 (0xA0-0xFF) would take 16 bits in UTF-8 and UTF-16.
That would mean that there are between 0.03125 and 0.125 characters in a bit.
If you are using Query builder then you may use a blow
DB::table(Newsletter Subscription)
->select('*')
->whereIn('id', $send_users_list)
->get()
If you are working with Eloquent then you can use as below
$sendUsersList = Newsletter Subscription:: select ('*')
->whereIn('id', $send_users_list)
->get();
A catch-block in a try statement needs to catch exactly the exception that the code inside the try {}
-block can throw (or a super class of that).
try {
//do something that throws ExceptionA, e.g.
throw new ExceptionA("I am Exception Alpha!");
}
catch(ExceptionA e) {
//do something to handle the exception, e.g.
System.out.println("Message: " + e.getMessage());
}
What you are trying to do is this:
try {
throw new ExceptionB("I am Exception Bravo!");
}
catch(ExceptionA e) {
System.out.println("Message: " + e.getMessage());
}
This will lead to an compiler error, because your java knows that you are trying to catch an exception that will NEVER EVER EVER occur. Thus you would get: exception ExceptionA is never thrown in body of corresponding try statement
.
To convert IQuerable
or IEnumerable
to a list, you can do one of the following:
IQueryable<object> q = ...;
List<object> l = q.ToList();
or:
IQueryable<object> q = ...;
List<object> l = new List<object>(q);
if you have yout tomcat installed you can do :
sh path2tomcat/bin/shutdown.sh
Put whatever you want to send to PHP in the value
attribute.
<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<option value="--Any--">--Any--</option>
<option value="Toyota">Toyota</option>
<option value="Nissan">Nissan</option>
</select>
You can also omit the value
attribute. It defaults to using the text.
If you don't want to change the HTML, you can put an array in your PHP to translate the values:
$makes = array(2 => 'Toyota',
3 => 'Nissan');
$maker = $makes[$_POST['Make']];
# To support matches from the beginning, not any matches:
items = ['a', 'ab', 'abc', 'bac']
prefix = 'ab'
filter(lambda x: x.startswith(prefix), items)
If I have the class:
public class MyClass
{
public void MyMethod()
{
}
}
and I then do:
MyClass myClass = null;
myClass.MyMethod();
The second line throws this exception becuase I'm calling a method on a reference type object that is null
(I.e. has not been instantiated by calling myClass = new MyClass()
)
To avoid 'Unclosed block: CssSyntaxError' errors being thrown from sass compilers add a ';' to the end of @content.
@mixin placeholder {
::-webkit-input-placeholder { @content;}
:-moz-placeholder { @content;}
::-moz-placeholder { @content;}
:-ms-input-placeholder { @content;}
}
Ports This section is used to define the mapping between the host server and Docker container.
ports:
- 10005:80
It means the application running inside the container is exposed at port 80. But external system/entity cannot access it, so it need to be mapped to host server port.
Note: you have to open the host port 10005 and modify firewall rules to allow external entities to access the application.
They can use
http://{host IP}:10005
something like this
EXPOSE This is exclusively used to define the port on which application is running inside the docker container.
You can define it in dockerfile as well. Generally, it is good and widely used practice to define EXPOSE inside dockerfile because very rarely anyone run them on other port than default 80 port
I need to select every production with a category that doesn't contain "Business"
Although I upvoted @Arran's answer as correct, I would also add this... Strictly interpreted, the OP's specification would be implemented as
//production[category[not(contains(., 'Business'))]]
rather than
//production[not(contains(category, 'Business'))]
The latter selects every production whose first category
child doesn't contain "Business". The two XPath expressions will behave differently when a production
has no category
children, or more than one.
It doesn't make any difference in practice as long as every <production>
has exactly one <category>
child, as in your short example XML. Whether you can always count on that being true or not, depends on various factors, such as whether you have a schema that enforces that constraint. Personally, I would go for the more robust option, since it doesn't "cost" much... assuming your requirement as stated in the question is really correct (as opposed to e.g. 'select every production that doesn't have a category that contains "Business"').
Use the df command:
df -h
If you're using framework 4.0 then the entry in the web.config (<pages validateRequest="false" />)
<configuration>
<system.web>
<pages validateRequest="false" />
</system.web>
</configuration>
If you're using framework 4.5 then the entry in the web.config (requestValidationMode="2.0")
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" requestValidationMode="2.0"/>
</system.web>
If you want for only single page then, In you aspx file you should put the first line as this :
<%@ Page EnableEventValidation="false" %>
if you already have something like <%@ Page so just add the rest => EnableEventValidation="false"
%>
I recommend not to do it.
Error in file(file, "rt") :
I just faced the same error and resolved by removing spacing in address using paste0 instead of paste
filepath=paste0(directory,"/",filename[1],sep="")
To make an unit test specifically on the abstract class, you should derive it for testing purpose, test base.method() results and intended behaviour when inheriting.
You test a method by calling it so test an abstract class by implementing it...
For Drupal users, this Chris Lane's answer of:
ini_set('memory_limit', '-1');
works but we need to put it just after the opening
<?php
tag in the index.php file in your site's root directory.
Function is not a property/method from range.
If you want to sum values then use the following:
Range("A1").Value = Application.Sum(Range(Cells(2, 1), Cells(3, 2)))
EDIT:
if you want the formula then use as follows:
Range("A1").Formula = "=SUM(" & Range(Cells(2, 1), Cells(3, 2)).Address(False, False) & ")"
'The two false after Adress is to define the address as relative (A2:B3).
'If you omit the parenthesis clause or write True instead, you can set the address
'as absolute ($A$2:$B$3).
In case you are allways going to use the same range address then you can use as Rory sugested:
Range("A1").Formula ="=Sum(A2:B3)"
Can you change the if condition to this:
if (!is.na(comments[l])) print(comments[l]);
You can only check for NA values with is.na().
if you want to solve this
$ node server events.js:141 throw er; // Unhandled 'error' event ^
Error: listen EADDRINUSE :::3000 at Object.exports._errnoException (util.js:907:11) at exports._exceptionWithHostPort (util.js:930:20) at Server._listen2 (net.js:1250:14) at listen (net.js:1286:10) at Server.listen (net.js:1382:5) at EventEmitter.listen (C:\sendbox\mean\node_modules\express\lib\application .js:617:24) at Object. (C:\sendbox\mean\server.js:28:5) at Module._compile (module.js:409:26) at Object.Module._extensions..js (module.js:416:10) at Module.load (module.js:343:32)
change your port number to 8000
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
With code like this:
const int node_ct = 8;
const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };
And in the configure.ac
AC_PROG_CC_C99
The compiler on my dev box was happy. The compiler on the server complained with:
error: variable-sized object may not be initialized
const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };
and
warning: excess elements in array initializer
const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };
for each element
It doesn't complain at all about, for example:
int expected[] = { 1, 2, 3, 4, 5 };
however, I decided that I like the check on size.
Rather than fighting, I went with a varargs initializer:
#include <stdarg.h>
void int_array_init(int *a, const int ct, ...) {
va_list args;
va_start(args, ct);
for(int i = 0; i < ct; ++i) {
a[i] = va_arg(args, int);
}
va_end(args);
}
called like,
const int node_ct = 8;
int expected[node_ct];
int_array_init(expected, node_ct, 1, 3, 4, 2, 5, 6, 7, 8);
As such, the varargs support is more robust than the support for the array initializer.
Someone might be able to do something like this in a macro.
Find PR with sample code at https://github.com/wbreeze/davenport/pull/15/files
Regarding https://stackoverflow.com/a/3535455/608359 from @paxdiablo, I liked it; but, felt insecure about having the number of times the initializaion pointer advances synchronized with the number of elements allocated to the array. Worst case, the initializing pointer moves beyond the allocated length. As such, the diff in the PR contains,
int expected[node_ct];
- int *p = expected;
- *p++ = 1; *p++ = 2; *p++ = 3; *p++ = 4;
+ int_array_init(expected, node_ct, 1, 2, 3, 4);
The int_array_init
method will safely assign junk if the number of
arguments is fewer than the node_ct. The junk assignment ought to be easier
to catch and debug.
To update a subset of fields, you can use update_fields
:
survey.save(update_fields=["active"])
The update_fields
argument was added in Django 1.5. In earlier versions, you could use the update()
method instead:
Survey.objects.filter(pk=survey.pk).update(active=True)
I wrote a little 2,2kb library of saving image in localStorage JQueryImageCaching Usage:
<img data-src="path/to/image">
<script>
$('img').imageCaching();
</script>
Another option is to use \dfrac instead of \frac, which makes the whole fraction larger and hence more readable.
And no, I don't know if there is an option to get something in between \frac and \dfrac, sorry.
AFAIK $(window).height();
returns the height of your window and $(document).height();
returns the height of your document
self.close() does not work, are you sure you closing a window and not a script generated popup ?
you guys might want to look at this : https://bugzilla.mozilla.org/show_bug.cgi?id=183697
Let assume i am having a RestController
with GET/POST/PUT/DELETE
operations and i have to write unit test using spring boot.I will just share code of RestController class and respective unit test.Wont be sharing any other related code to the controller ,can have assumption on that.
@RestController
@RequestMapping(value = “/myapi/myApp” , produces = {"application/json"})
public class AppController {
@Autowired
private AppService service;
@GetMapping
public MyAppResponse<AppEntity> get() throws Exception {
MyAppResponse<AppEntity> response = new MyAppResponse<AppEntity>();
service.getApp().stream().forEach(x -> response.addData(x));
return response;
}
@PostMapping
public ResponseEntity<HttpStatus> create(@RequestBody AppRequest request) throws Exception {
//Validation code
service.createApp(request);
return ResponseEntity.ok(HttpStatus.OK);
}
@PutMapping
public ResponseEntity<HttpStatus> update(@RequestBody IDMSRequest request) throws Exception {
//Validation code
service.updateApp(request);
return ResponseEntity.ok(HttpStatus.OK);
}
@DeleteMapping
public ResponseEntity<HttpStatus> delete(@RequestBody AppRequest request) throws Exception {
//Validation
service.deleteApp(request.id);
return ResponseEntity.ok(HttpStatus.OK);
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Main.class)
@WebAppConfiguration
public abstract class BaseTest {
protected MockMvc mvc;
@Autowired
WebApplicationContext webApplicationContext;
protected void setUp() {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
protected String mapToJson(Object obj) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(obj);
}
protected <T> T mapFromJson(String json, Class<T> clazz)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, clazz);
}
}
public class AppControllerTest extends BaseTest {
@MockBean
private IIdmsService service;
private static final String URI = "/myapi/myApp";
@Override
@Before
public void setUp() {
super.setUp();
}
@Test
public void testGet() throws Exception {
AppEntity entity = new AppEntity();
List<AppEntity> dataList = new ArrayList<AppEntity>();
AppResponse<AppEntity> dataResponse = new AppResponse<AppEntity>();
entity.setId(1);
entity.setCreated_at("2020-02-21 17:01:38.717863");
entity.setCreated_by(“Abhinav Kr”);
entity.setModified_at("2020-02-24 17:01:38.717863");
entity.setModified_by(“Jyoti”);
dataList.add(entity);
dataResponse.setData(dataList);
Mockito.when(service.getApp()).thenReturn(dataList);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(URI)
.accept(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
String expectedJson = this.mapToJson(dataResponse);
String outputInJson = mvcResult.getResponse().getContentAsString();
assertEquals(HttpStatus.OK.value(), response.getStatus());
assertEquals(expectedJson, outputInJson);
}
@Test
public void testCreate() throws Exception {
AppRequest request = new AppRequest();
request.createdBy = 1;
request.AppFullName = “My App”;
request.appTimezone = “India”;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).createApp(Mockito.any(AppRequest.class));
service.createApp(request);
Mockito.verify(service, Mockito.times(1)).createApp(request);
RequestBuilder requestBuilder = MockMvcRequestBuilders.post(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
@Test
public void testUpdate() throws Exception {
AppRequest request = new AppRequest();
request.id = 1;
request.modifiedBy = 1;
request.AppFullName = “My App”;
request.appTimezone = “Bharat”;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).updateApp(Mockito.any(AppRequest.class));
service.updateApp(request);
Mockito.verify(service, Mockito.times(1)).updateApp(request);
RequestBuilder requestBuilder = MockMvcRequestBuilders.put(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
@Test
public void testDelete() throws Exception {
AppRequest request = new AppRequest();
request.id = 1;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).deleteApp(Mockito.any(Integer.class));
service.deleteApp(request.id);
Mockito.verify(service, Mockito.times(1)).deleteApp(request.id);
RequestBuilder requestBuilder = MockMvcRequestBuilders.delete(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
}
To always round up
int alwaysRoundUp(int n, int multiple)
{
if (n % multiple != 0) {
n = ((n + multiple) / multiple) * multiple;
// Another way
//n = n - n % multiple + multiple;
}
return n;
}
alwaysRoundUp(1, 10) -> 10
alwaysRoundUp(5, 10) -> 10
alwaysRoundUp(10, 10) -> 10
To always round down
int alwaysRoundDown(int n, int multiple)
{
n = (n / multiple) * multiple;
return n;
}
alwaysRoundDown(1, 10) -> 0
alwaysRoundDown(5, 10) -> 0
alwaysRoundDown(10, 10) -> 10
To round the normal way
int normalRound(int n, int multiple)
{
n = ((n + multiple/2)/multiple) * multiple;
return n;
}
normalRound(1, 10) -> 0
normalRound(5, 10) -> 10
normalRound(10, 10) -> 10
There is no way to know that through the Android API. You have to store some flag by yourself and make it persist either in a SharedPreferenceEditor
or using a database.
If you want to base some licence related stuff on this flag, I suggest you use an obfuscated preference editor provided by the LVL library. It's simple and clean.
Regards, Stephane
Since node 4.8.0 you are able to use the feature of ES6 called generator. You may follow this article for deeper concepts. But basically you can use generators and promises to get this job done. I'm using bluebird to promisify and manage the generator.
Your code should be fine like the example below.
const Promise = require('bluebird');
function* getResponse(query) {
const r = yield new Promise(resolve => myApi.exec('SomeCommand', resolve);
return r;
}
Promise.coroutine(getResponse)()
.then(response => console.log(response));
I struggled with this issue for a little bit too. I noticed a lot of you posted really complicated resolutions but there is a much easier way to do this! Its just a program and you shouldn't have to modify scripts, or install third party tools. The issue is related to High DPI scaling as mentioned above but what I think a lot of you are missing is that you can't directly modify compatibility settings on the launcher itself. The launcher and eclipse are two different programs! You need to browse to the Eclipse.exe and override the High DPI scaling option there. Once set, you can use the launcher as normal. The launcher will hit the executable, launch the eclipse.exe and since you set the compatibility settings on the .exe it will run using those settings. I spent like 10 minutes tracking down where the exe was so if its any help mine was located in: C:\Users\username\AppData\Local\Yatta\Launcher\installations\eclipse-ide-for-java-developers\eclipse.exe
Here is a screen shot of how I set my compatibility settings.
And yes, the icons were super small before adjusting this setting. I tried setting compatibility settings on the launcher itself but it obviously didn't fix the issue. But after setting the override High DPI setting for the eclipse.exe icons are now normal size. Let me know if this works for others!
XmlDocument doc = new XmlDocument();
doc.Load("MonFichierXML.xml");
XmlNode node = doc.SelectSingleNode("Magasin");
XmlNodeList prop = node.SelectNodes("Items");
foreach (XmlNode item in prop)
{
items Temp = new items();
Temp.AssignInfo(item);
lstitems.Add(Temp);
}
Executing Linq queries can generate extra threads. When I try to execute code that uses Linq query collection in the immediate window it often refuses to run because not enough threads are available to the debugger.
As others have said, for threads to exit when they are finished is perfectly normal.
I was facing the same situation.
I begin by declaring the structures I need:
Set<String> myKeysInSet = null;
String[] myArrayOfString = null;
In my case, I have a JSON object and I need all the keys in this JSON to be stored in an array of strings. Using the GSON library, I use JSON.keySet() to get the keys and move to my Set :
myKeysInSet = json_any.keySet();
With this, I have a Set structure with all the keys, as I needed it. So I just need to the values to my Array of Strings. See the code below:
myArrayOfString = myKeysInSet.toArray(new String[myKeysInSet.size()]);
This was my first answer in StackOverflow. Sorry for any error :D
In IPython (jupyter
) 7.3 and later, there is a magic %pip
and %conda
command that will install into the current kernel (rather than into the instance of Python that launched the notebook).
%pip install geocoder
In earlier versions, you need to use sys to fix the problem like in the answer by FlyingZebra1
import sys
!{sys.executable} -m pip install geocoder
An elegant way to move your file to an nonexistent directory is to create the following extension to native FileInfo class:
public static class FileInfoExtension
{
//second parameter is need to avoid collision with native MoveTo
public static void MoveTo(this FileInfo file, string destination, bool autoCreateDirectory) {
if (autoCreateDirectory)
{
var destinationDirectory = new DirectoryInfo(Path.GetDirectoryName(destination));
if (!destinationDirectory.Exists)
destinationDirectory.Create();
}
file.MoveTo(destination);
}
}
Then use brand new MoveTo extension:
using <namespace of FileInfoExtension>;
...
new FileInfo("some path")
.MoveTo("target path",true);
The better option is create a new table copy the rows to the destination table, drop the actual table and rename the newly created table . This method is good for small tables,
From the bottom of the ?mutate_each
(at least in dplyr 0.5) it looks like that function, as in @docendo discimus's answer, will be deprecated and replaced with more flexible alternatives mutate_if
, mutate_all
, and mutate_at
. The one most similar to what @hadley mentions in his comment is probably using mutate_at
. Note the order of the arguments is reversed, compared to mutate_each
, and vars()
uses select()
like semantics, which I interpret to mean the ?select_helpers
functions.
dat %>% mutate_at(vars(starts_with("fac")),funs(factor)) %>%
mutate_at(vars(starts_with("dbl")),funs(as.numeric))
But mutate_at
can take column numbers instead of a vars()
argument, and after reading through this page, and looking at the alternatives, I ended up using mutate_at
but with grep
to capture many different kinds of column names at once (unless you always have such obvious column names!)
dat %>% mutate_at(grep("^(fac|fctr|fckr)",colnames(.)),funs(factor)) %>%
mutate_at(grep("^(dbl|num|qty)",colnames(.)),funs(as.numeric))
I was pretty excited about figuring out mutate_at
+ grep
, because now one line can work on lots of columns.
EDIT - now I see matches()
in among the select_helpers, which handles regex, so now I like this.
dat %>% mutate_at(vars(matches("fac|fctr|fckr")),funs(factor)) %>%
mutate_at(vars(matches("dbl|num|qty")),funs(as.numeric))
Another generally-related comment - if you have all your date columns with matchable names, and consistent formats, this is powerful. In my case, this turns all my YYYYMMDD columns, which were read as numbers, into dates.
mutate_at(vars(matches("_DT$")),funs(as.Date(as.character(.),format="%Y%m%d")))
Adding a space before the EOF delimiter allows to avoid cmd:
- shell: |
cat <<' EOF'
This is a test.
EOF
I've seen some people promote 'package by feature' over 'package by layer' but I've used quite a few approaches over many years and found 'package by layer' much better than 'package by feature'.
Further to that I have found that a hybrid: 'package by module, layer then feature' strategy works extremely well in practice as it has many advantages of 'package by feature':
I explain in depth here: Java Package Name Structure and Organization but my standard package structure is:
revdomain.moduleType.moduleName.layer.[layerImpl].feature.subfeatureN.subfeatureN+1...
Where:
revdomain Reverse domain e.g. com.mycompany
moduleType [app*|framework|util]
moduleName e.g. myAppName if module type is an app or 'finance' if its an accounting framework
layer [model|ui|persistence|security etc.,]
layerImpl eg., wicket, jsp, jpa, jdo, hibernate (Note: not used if layer is model)
feature eg., finance
subfeatureN eg., accounting
subfeatureN+1 eg., depreciation
*Sometimes 'app' left out if moduleType is an application but putting it in there makes the package structure consistent across all module types.
Use inet_ntop()
and inet_pton()
if you need it other way around. Do not use inet_ntoa(), inet_aton()
and similar as they are deprecated and don't support ipv6.
Here is a nice guide with quite a few examples.
// IPv4 demo of inet_ntop() and inet_pton()
struct sockaddr_in sa;
char str[INET_ADDRSTRLEN];
// store this IP address in sa:
inet_pton(AF_INET, "192.0.2.33", &(sa.sin_addr));
// now get it back and print it
inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN);
printf("%s\n", str); // prints "192.0.2.33"