You should edit "settings.json". In that add, "editor.lineNumbers":"on",
. You can check comments for various options you have.
In Visual Studio Code - 2017, you can also directly go to a given line number. There are following three ways to do that.
For those who might need it, a "FILE_LINE" macro to easily print file and line:
#define STRINGIZING(x) #x
#define STR(x) STRINGIZING(x)
#define FILE_LINE __FILE__ ":" STR(__LINE__)
You can delete a particular single line with its line number by
sed -i '33d' file
This will delete the line on 33 line number and save the updated file.
As of the latest version:
PhpStorm > Preferences.. > Editor > General > Appearance > Show line numbers
Only way to know how many lines there are in file is to count them. You can of course create a metric from your data giving you an average length of one line and then get the file size and divide that with avg. length but that won't be accurate.
I'm using Debian 7 64-bit.
I didn't have a .vimrc file in my home folder. I created one and was able to set user defaults for vim.
However, for Debian 7, another way is to edit /etc/vim/vimrc
Here is a comment block in that file:
" All system-wide defaults are set in $VIMRUNTIME/debian.vim (usually just
" /usr/share/vim/vimcurrent/debian.vim) and sourced by the call to :runtime
" you can find below. If you wish to change any of those settings, you should
" do it in this file (/etc/vim/vimrc), since debian.vim will be overwritten
" everytime an upgrade of the vim packages is performed. It is recommended to
" make changes after sourcing debian.vim since it alters the value of the
" 'compatible' option.
I read this article it was really helpful for troubleshooting any kind of inconveniences
https://support.microsoft.com/en-us/kb/224453
this is a case of waitresource KEY: 16:72057595075231744 (ab74b4daaf17)
-- First SQL Provider to find the SPID (Session ID)
-- Second Identify problem, check Status, Open_tran, Lastwaittype, waittype, and waittime
-- iMPORTANT Waitresource select * from sys.sysprocesses where spid = 57
select * from sys.databases where database_id=16
-- with Waitresource check this to obtain object id
select * from sys.partitions where hobt_id=72057595075231744
select * from sys.objects where object_id=2105058535
You don't need CSS for this.
<img src="abc"/>
now with link:
<a href="#myLink"><img src="abc"/></a>
Or with jquery, later on, you can use the wrap property, see these questions answer:
Before you begin, if you are uncomfortable with a command line, you can do all the following steps using SourceTree, GitExtension, GitHub Desktop, or your favorite tool.
To solve the issue, you might have two scenarios:
1) Fix only remote repository branch which is behind commit
Example: Both branches are on the remote side
ahead === Master branch
behind === Develop branch
Solution:
Clone the repository to the local workspace: this will give you the Master branch which is ahead with commit
git clone repositoryUrl
Create a branch with Develop name and checkout to that branch locally
git checkout -b DevelopBranchName // this command creates and checkout the branch
Pull from the remote Develop branch. Conflict might occur. if so, fix the conflict and commit the changes.
git pull origin DevelopBranchName
Merge the local Develop branch with the remote Develop branch
git merge origin develop
Push the merged branch to the remote Develop branch
git push origin develop
2) Local Master branch is behind the remote Master branch
This means every locally created branch is behind.
Before preceding, you have to commit or stash all the changes you made on the branch that is behind commits.
Solution:
Checkout your local Master branch
git checkout master
Pull from remote Master branch
git pull origin master
Now your local Master is in sync with the remote Branch but other local branches, that branched from the local Master branch, are not in sync with your local Master branch because of the above command. To fix that:
Checkout the branch that is behind your local Master branch
git checkout BranchNameBehindCommit
Merge with the local Master branch
git merge master // Now your branch is in sync with local Master branch
If this branch is on the remote repository, you have to push your changes
git push origin branchBehindCommit
There is no way in PostgreSQL to deconstruct a scalar JSON object. Thus, as you point out,
select length(to_json('Some "text"'::TEXT) ::TEXT);
is 15,
The trick is to convert the JSON into an array of one JSON element, then extract that element using ->>
.
select length( array_to_json(array[to_json('Some "text"'::TEXT)])->>0 );
will return 11.
I was looking for the TOTAL size of the column and hit this article, my solution is based off of MarcE's.
SELECT sum(DATALENGTH(your_field)) AS FIELDSIZE FROM your_table
Change overflow:hidden
to overflow:visible
. It works better. I use like this:
#menu ul li ul {
background-color:#fe1c1c;
width:85px;
height:0px;
opacity:0;
box-shadow:1px 3px 10px #000000;
border-radius:3px;
z-index:1;
-webkit-transition:all 0.5s ease;
-moz-transition:all 0.6s ease;
}
#menu ul li:hover ul {
overflow:visible;
opacity:1;
height:140px;
}
visible
is better because overflow:hidden
act exactly like a display:none
.
Rookie, if you want to write a file to server by socket, how about using fileoutputstream instead of dataoutputstream? dataoutputstream is more fit for protocol-level read-write. it is not very reasonable for your code in bytes reading and writing. loop to read and write is necessary in java io. and also, you use a buffer way. flush is necessary. here is a code sample: http://www.rgagnon.com/javadetails/java-0542.html
There's a class of question on SO that sometimes make less than perfect sense, this one is perilously close :-)
Perhaps you could explain your aversion to using one of the two methods you ruled out.
If it's just because you don't want to pepper your code with if
statements or exception catching code, one solution is to use a helper function that will take care of it for you, something like:
static String substring_safe (String s, int start, int len) { ... }
which will check lengths beforehand and act accordingly (either return smaller string or pad with spaces).
Then you don't have to worry about it in your code at all, just call:
String s2 = substring_safe (s, 10, 7);
instead of:
String s2 = s.substring (10,7);
This would work in the case that you seem to be worried about (based on your comments to other answers), not breaking the flow of the code when doing lots of string building stuff.
I have the same questions, and got some information from this link: git fetch doesn't fetch all branches
So now, I may not sure how this situation happened, at least we can solve it:
Step 1. Check your "remote.origin.fetch" setting, should be like this
$ git config --get remote.origin.fetch
+refs/heads/private_dev_branch:refs/remotes/origin/private_dev_branch
Step 2. Change "remote.origin.fetch" to fetch everything
$ git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
$ git config --get remote.origin.fetch
+refs/heads/*:refs/remotes/origin/*
Then, you can try "git pull" (maybe "git fetch origin" also works but I didn't try) to get all the branch.
your exists syntax is wrong and you should seperate DDL with go like below
if exists(select 1 from sys.views where name='tst' and type='v')
drop view tst;
go
create view tst
as
select * from test
you also can check existence test, with object_id like below
if object_id('tst','v') is not null
drop view tst;
go
create view tst
as
select * from test
In SQL 2016,you can use below syntax to drop
Drop view if exists dbo.tst
From SQL2016 CU1,you can do below
create or alter view vwTest
as
select 1 as col;
go
You also need to make sure what is in the .bashrc file of the user.
I've also got this ridiculous error because I put cd
and ls
commands in there, as it was mean to let them see the current files & directories when the user is has logged in from ssh.
You can also get through it by the code below:
file=open(completefilepath,'r',encoding='utf8',errors="ignore")
file.read()
I suggest you using bootstrap which works perfectly:
@import url('http://getbootstrap.com/dist/css/bootstrap.css');_x000D_
html, body, .container-table {_x000D_
height: 100%;_x000D_
}_x000D_
.container-table {_x000D_
display: table;_x000D_
}_x000D_
.vertical-center-row {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0" />_x000D_
<title>Login Page | ... </title>_x000D_
_x000D_
<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/bootstrap.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<div class="container container-table">_x000D_
<div class="row vertical-center-row">_x000D_
<div class="text-center col-md-4 col-md-offset-4" style="">_x000D_
<form id="login" action="dashboard.html" method="post">_x000D_
_x000D_
<div class="username">_x000D_
<div class="usernameinner">_x000D_
<input type="text" name="username" id="username" placeholder="Login" />_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="password">_x000D_
<div class="passwordinner">_x000D_
<input type="password" name="password" id="password" placeholder="Mot de passe" />_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<button id="login-button">Connexion</button>_x000D_
_x000D_
<div class="keep"><input type="checkbox" /> Gardez moi connecté</div>_x000D_
_x000D_
</form>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
The thing on the right of <-
is a formula
object. It is often used to denote a statistical model, where the thing on the left of the ~
is the response and the things on the right of the ~
are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".
The myFormula <-
part of that line stores the formula in an object called myFormula
so you can use it in other parts of your R code.
Other common uses of formula objects in R
The lattice
package uses them to specify the variables to plot.
The ggplot2
package uses them to specify panels for plotting.
The dplyr
package uses them for non-standard evaulation.
@Mark Rajcok gave a great solution for ion projects that include a range type input.
In any other case of non ion projects I will suggest this:
HTML:
<input type="text" name="points" #points maxlength="8" [(ngModel)]="range" (ngModelChange)="range=saverange($event, points)">
Component:
onChangeAchievement(eventStr: string, eRef): string {
//Do something (some manipulations) on input and than return it to be saved:
//In case you need to force of modifing the Element-Reference value on-focus of input:
var eventStrToReplace = eventStr.replace(/[^0-9,eE\.\+]+/g, "");
if (eventStr != eventStrToReplace) {
eRef.value = eventStrToReplace;
}
return this.getNumberOnChange(eventStr);
}
The idea here:
Letting the (ngModelChange)
method to do the Setter job:
(ngModelChange)="range=saverange($event, points)
Enabling direct access to the native Dom element using this call:
eRef.value = eventStrToReplace;
I was able to generate good looking HTML files with the following snip-it shown in Code 1.
* <pre>
* {@code
* A-->B
* \
* C-->D
* \ \
* G E-->F
* }
*</pre>
(Code 1)
Code 1 turned into the generated javadoc HTML page in Fig 1, as expected.
A-->B
\
C-->D
\ \
G E-->F
(Fig. 1)
However, in NetBeans 7.2, if you hit Alt+Shift+F (to reformat the current file), Code 1 turns in to Code 2.
* <
* pre>
* {@code
* A-->B
* \
* C-->D
* \ \
* G E-->F
* }
* </pre>
(Code 2)
where the first <pre>
is now broken onto two lines. Code 2 produces generated javadoc HTML file as shown in Fig 2.
< pre> A-->B \ C-->D \ \ G E-->F
(Fig 2)
Steve B's suggestion (Code 3) seems to give the best results and remains formatted as expected even after hitting Alt+Shift+F.
*<p><blockquote><pre>
* A-->B
* \
* C-->D
* \ \
* G E-->F
* </pre></blockquote>
(Code 3)
Use of Code 3 produces the same javadoc HTML output as shown in Fig 1.
The top answer here seems to be an OS dependent answer; for a more portable solution you can write up a quick sleep function using the ctime header file (although this may be a poor implementation on my part).
#include <iostream>
#include <ctime>
using namespace std;
void sleep(float seconds){
clock_t startClock = clock();
float secondsAhead = seconds * CLOCKS_PER_SEC;
// do nothing until the elapsed time has passed.
while(clock() < startClock+secondsAhead);
return;
}
int main(){
cout << "Next string coming up in one second!" << endl;
sleep(1.0);
cout << "Hey, what did I miss?" << endl;
return 0;
}
memory mapping is not only used to map files into memory but is also a tool to request RAM from kernel. These are those inode 0 entries - your stack, heap, bss segments and more
If you're doing something like
for /l %%i in (1,1,500) do @echo %time%
or
if foo (
echo %time%
do_something
echo %time%
)
then you could simply put a setlocal enabledelayedexpansion
at the beginning of your batch file and use !time!
instead of %time%
which gets evaluated on execution, not on parsing the line (which includes complete blocks enclosed in parentheses).
Some of the time savers:
The Canoo blog contains some (+8) articles on some more advanced IntelliJ keyboard shortcuts.
The Key Promoter and Shortcut keys list plugins are really helpful for (constantly) learning new IntelliJ keyboard shortcuts.
Calendar has a set() method that can set the year, month, and day-of-month in one call:
myCal.set( theYear, theMonth, theDay );
Export all databases in Ubuntu
1 - mysqldump -u root -p --databases database1 database2 > ~/Desktop/databases_1_2.sql
OR
2 - mysqldump -u root -p --all_databases > ~/Desktop/all_databases.sql
Code:
List<String> list = new ArrayList<String>();
list.add("a");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
array.put(list.get(i));
}
JSONObject obj = new JSONObject();
try {
obj.put("result", array);
} catch (JSONException e) {
e.printStackTrace();
}
position: fixed;
Will make this happen.
It handles like position:absolute;
with the exception that it will scroll with the window as the user scrolls down the content.
m2e 1.7 introduces a new syntax for lifecycle mapping metadata that doesn't cause this warning anymore:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<!-- This executes the goal in Eclipse on project import.
Other options like are available, eg ignore. -->
<?m2e execute?>
<phase>generate-sources</phase>
<goals><goal>add-source</goal></goals>
<configuration>
<sources>
<source>src/bootstrap/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
All the answers are not really correct, try this:
select * from shirts where 1 IN (colors);
BTW. you should prefer coding against an Interface.
private ArrayList<String[]> action = new ArrayList<String[]>();
Should be
private List<String[]> action = new ArrayList<String[]>();
Our version of Oracle is running on Red Hat Enterprise Linux. We experimented with several different types of group permissions to no avail. The /defaultdir directory had a group that was a secondary group for the oracle user. When we updated the /defaultdir directory to have a group of "oinstall" (oracle's primary group), I was able to select from the external tables underneath that directory with no problem.
So, for others that come along and might have this issue, make the directory have oracle's primary group as the group and it might resolve it for you as it did us. We were able to set the permissions to 770 on the directory and files and selecting on the external tables works fine now.
When you use just "localhost" the MySQL client library tries to use a Unix domain socket for the connection instead of a TCP/IP connection. The error is telling you that the socket, called MySQL
, cannot be used to make the connection, probably because it does not exist (error number 2).
From the MySQL Documentation:
On Unix, MySQL programs treat the host name localhost specially, in a way that is likely different from what you expect compared to other network-based programs. For connections to localhost, MySQL programs attempt to connect to the local server by using a Unix socket file. This occurs even if a --port or -P option is given to specify a port number. To ensure that the client makes a TCP/IP connection to the local server, use --host or -h to specify a host name value of 127.0.0.1, or the IP address or name of the local server. You can also specify the connection protocol explicitly, even for localhost, by using the --protocol=TCP option.
There are a few ways to solve this problem.
127.0.0.1
instead of localhost
when you connect. The Unix socket might by faster and safer to use, though.php.ini
: open the MySQL configuration file my.cnf
to find where MySQL creates the socket, and set PHP's mysqli.default_socket
to that path. On my system it's /var/run/mysqld/mysqld.sock
.Configure the socket directly in the PHP script when opening the connection. For example:
$db = new MySQLi('localhost', 'kamil', '***', '', 0,
'/var/run/mysqld/mysqld.sock')
Either link the shell to an object, have the batch job terminate the shell object (exit) and have the VBA code continue once the shell object = Nothing?
Or have a look at this: Capture output value from a shell command in VBA?
You should add maven-resources-plugin in your pom.xml file. Deleting ~/.m2/repository does not work always.
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.4</version>
</plugin>
</plugins>
Now build your project again. It should be successful!
mybytestring.encode(somecodec) is meaningful for these values of somecodec
:
I am not sure what decoding an already decoded unicode text is good for. Trying that with any encoding seems to always try to encode with the system's default encoding first.
If it is an auto generated key, then you can use Statement#getGeneratedKeys()
for this. You need to call it on the same Statement
as the one being used for the INSERT
. You first need to create the statement using Statement.RETURN_GENERATED_KEYS
to notify the JDBC driver to return the keys.
Here's a basic example:
public void create(User user) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_INSERT,
Statement.RETURN_GENERATED_KEYS);
) {
statement.setString(1, user.getName());
statement.setString(2, user.getPassword());
statement.setString(3, user.getEmail());
// ...
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating user failed, no rows affected.");
}
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
user.setId(generatedKeys.getLong(1));
}
else {
throw new SQLException("Creating user failed, no ID obtained.");
}
}
}
}
Note that you're dependent on the JDBC driver as to whether it works. Currently, most of the last versions will work, but if I am correct, Oracle JDBC driver is still somewhat troublesome with this. MySQL and DB2 already supported it for ages. PostgreSQL started to support it not long ago. I can't comment about MSSQL as I've never used it.
For Oracle, you can invoke a CallableStatement
with a RETURNING
clause or a SELECT CURRVAL(sequencename)
(or whatever DB-specific syntax to do so) directly after the INSERT
in the same transaction to obtain the last generated key. See also this answer.
you may use the below code it works fine with swift 3
var preferredLanguage : String = Bundle.main.preferredLocalizations.first!
jQuery is up in here, so:
jQuery.fn.goodOLauterHTML= function() {
return $('<a></a>').append( this.clone() ).html();
}
Return all that HTML stuff:
$('div' /*elys with HTML text stuff that you want */ ).goodOLauterHTML(); // alerts tags and all
Any searching with select statement yield you only object name, where search keyword contains. Easiest and efficient way is get script of procedure/function and then search in generated text file, I also follows this technique :) So you are exact pinpoint.
If you want to set width dynamically with variable than use [] braces instead {{}}:
<div [style.width.px]="[widthVal]" [style.height.px]="[heightVal]"></div>
<div [style.width.%]="[widthVal]" [style.height.%]="[heightVal]"></div>
The POST data which holds the submitted form data is being echoed in the form, eg:
<input name="firstname" type="text" placeholder="First Name" required="required"
value="<?php echo $_POST['firstname'];?>"
Either clear the POST data once you have done with the form - ie all inputs were ok and you have actioned whatever your result from a form is.
Or, once you have determined the form is ok and have actioned whatever you action from the form, redirect the user to a new page to say "all done, thanks" etc.
header('Location: thanks.php');
exit();
This stops the POST data being present, it's know as "Post/Redirect/Get":
http://en.wikipedia.org/wiki/Post/Redirect/Get
The Post/Redirect/Get (PRG) method and using another page also ensures that if users click browser refresh, or back button having navigated somewhere else, your form is not submitted again.
This means if your form inserts into a database, or emails someone (etc), without the PRG method the values will (likely) be inserted/emailed every time they click refresh or revisit the page using their history/back button.
The "new" way of doing this since jQuery 1.5 (Jan 2011) is to use deferred objects instead of passing a success
callback. You should return the result of $.ajax
and then use the .done
, .fail
etc methods to add the callbacks outside of the $.ajax
call.
function getData() {
return $.ajax({
url : 'example.com',
type: 'GET'
});
}
function handleData(data /* , textStatus, jqXHR */ ) {
alert(data);
//do some stuff
}
getData().done(handleData);
This decouples the callback handling from the AJAX handling, allows you to add multiple callbacks, failure callbacks, etc, all without ever needing to modify the original getData()
function. Separating the AJAX functionality from the set of actions to be completed afterwards is a good thing!.
Deferreds also allow for much easier synchronisation of multiple asynchronous events, which you can't easily do just with success:
For example, I could add multiple callbacks, an error handler, and wait for a timer to elapse before continuing:
// a trivial timer, just for demo purposes -
// it resolves itself after 5 seconds
var timer = $.Deferred();
setTimeout(timer.resolve, 5000);
// add a done handler _and_ an `error:` handler, even though `getData`
// didn't directly expose that functionality
var ajax = getData().done(handleData).fail(error);
$.when(timer, ajax).done(function() {
// this won't be called until *both* the AJAX and the 5s timer have finished
});
ajax.done(function(data) {
// you can add additional callbacks too, even if the AJAX call
// already finished
});
Other parts of jQuery use deferred objects too - you can synchronise jQuery animations with other async operations very easily with them.
Here is a simple brute force way of identifying superfluous header includes. It's not perfect but eliminates the "obvious" unnecessary includes. Getting rid of these goes a long way in cleaning up the code.
The scripts can be accessed directly on GitHub.
If you want to revert the file to its state in master
:
git checkout origin/master [filename]
Well if you are getting into a linux machine you can use the package manager of that linux distro.
If you are using Ubuntu just use apt-get search python, check the list and do apt-get install python2.7 (not sure if python2.7 or python-2.7, check the list)
You could use yum in fedora and do the same.
if you want to install it on your windows machine i dont know any package manager, i would download the wget for windows, donwload the package from python.org and install it
Alternatively,
<style type="text/css">
#example {
display: block;
width: 30px;
height: 10px;
background: url(../images/example.png) no-repeat;
text-indent: -9999px;
}
</style>
<a href="http://www.example.com" id="example">See an example!</a>
More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.
You are looking for JavaScript's String
method substring
e.g.
'Hiya how are you'.substring(0,8);
Which returns the string starting at the first character and finishing before the 9th character - i.e. 'Hiya how'.
Maybe the dot notation for current folder is incorrect?
Print the result of File.getCanonicalFile()
to check the path.
Can anyone explain to me why src isn't the current folder?
Your IDE is setting the class-path when invoking the JVM.
E.G. (reaches for Netbeans) If you select menus File
| Project Properties (all classes)
you might see something similar to:
It is the Working Directory
that is of interest here.
There are only two ways to put a value into an array, and one is just syntactic sugar for the other:
a[i] = v;
*(a+i) = v;
Thus, to put something as the 4th element, you don't have any choice but arr[4] = 5
. However, it should fail in your code, because the array is only allocated for 4 elements.
If you understand it well you can explain it simple. And the simplest way is abstracting it from the context. Code aside, even programming aside. A metaphor example will do it better.
Let's imagine that a function is a room whose walls are of glass, but they are special glass, like the ones in an interrogation room. From outside they are opaque, from inside they are transparent. It can be rooms inside other rooms, and the only way of contact is a phone.
If you call from the outside, you don't know what is in it, but you know that the people inside will do a task if you give them certain information. They can see outside, so they can ask you for stuff that are outside and make changes to that stuff, but you can't change what it is inside from the outside, you don't even see (know) what it is inside. The people inside that room you are calling see what it is outside, but not what it is inside the rooms in that room, so they interact with them the way you are doing from outside. The people inside the most inner rooms can see many things, but the people of the most outer room don't even know about the most inner rooms' existence.
For each call to an inner room, the people in that room keeps a record of the information about that specific call, and they are so good doing that that they never mistake one call stuff with other call stuff.
Rooms are functions, visibility is scope, people doing task is statements, stuff are objects, phone calls are function calls, phone call information is arguments, call records are scope instances, the most outer room is the global object.
I guess no one mentioned this so I will write it here. In phpMyAdmin 4.x, there is "Add Routine" link under "Routines" tab at the top row. This link opens a popup dialog where you can write your Stored procedure without worrying about delimiter or template.
Add Routine
Note that for simple test stored procedure, you may want to drop the default parameter which is already given or you can simply set it with a value.
If you have only one type of collections (e.g. scatter with no error bars) you can also change the colours after that you have plotted them, this sometimes is easier to perform.
import matplotlib.pyplot as plt
from random import randint
import numpy as np
#Let's generate some random X, Y data X = [ [frst group],[second group] ...]
X = [ [randint(0,50) for i in range(0,5)] for i in range(0,24)]
Y = [ [randint(0,50) for i in range(0,5)] for i in range(0,24)]
labels = range(1,len(X)+1)
fig = plt.figure()
ax = fig.add_subplot(111)
for x,y,lab in zip(X,Y,labels):
ax.scatter(x,y,label=lab)
#Now this is actually the code that you need, an easy fix your colors just cut and paste not you need ax.
colormap = plt.cm.gist_ncar #nipy_spectral, Set1,Paired
colorst = [colormap(i) for i in np.linspace(0, 0.9,len(ax.collections))]
for t,j1 in enumerate(ax.collections):
j1.set_color(colorst[t])
ax.legend(fontsize='small')
The output gives you differnent colors even when you have many different scatter plots in the same subplot.
This is how I solve my problem:
parseFloat(parseFloat(floatString).toFixed(2));
There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).
Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.
Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.
I was having the same problem.
There is a difference between a Bar chart
and a Stacked Bar chart
As there is a difference between a Line chart
and a Stacked Line chart
.
The stacked one, will not ignore the 0 or blank values, but will show a cumulative value according with the other legends.
Simply right click the graph, click Change Chart Type
and pick a non-stacked chart.
open ~/.bash_profile and add these bash functions to the end of the file
function androidinstall(){
adb install -r ./bin/$1.apk
}
function androidrun(){
ant clean debug
adb shell am start -n $1/$1.$2
}
then open the Android project folder
androidinstall app-debug && androidrun com.example.app MainActivity
From Screen User's Manual ;
screen -d -r "screenName"
Reattach a session and if necessary detach it first
I made this simpler by making some improvements on the following classes (from other answers):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestOO
{
class Program
{
static void Main(string[] args)
{
BaseClass _base = new BaseClass();
Console.WriteLine("Calling virtual method directly");
_base.SayHello();
Console.WriteLine("Calling single method directly");
_base.SayGoodbye();
DerivedClass _derived = new DerivedClass();
Console.WriteLine("Calling new method from derived class");
_derived.SayHello();
Console.WriteLine("Calling overrided method from derived class");
_derived.SayGoodbye();
DerivedClass2 _derived2 = new DerivedClass2();
Console.WriteLine("Calling new method from derived2 class");
_derived2.SayHello();
Console.WriteLine("Calling overrided method from derived2 class");
_derived2.SayGoodbye();
Console.ReadLine();
}
}
public class BaseClass
{
public void SayHello()
{
Console.WriteLine("Hello\n");
}
public virtual void SayGoodbye()
{
Console.WriteLine("Goodbye\n");
}
public void HelloGoodbye()
{
this.SayHello();
this.SayGoodbye();
}
}
public abstract class AbstractClass
{
public void SayHello()
{
Console.WriteLine("Hello\n");
}
//public virtual void SayGoodbye()
//{
// Console.WriteLine("Goodbye\n");
//}
public abstract void SayGoodbye();
}
public class DerivedClass : BaseClass
{
public new void SayHello()
{
Console.WriteLine("Hi There");
}
public override void SayGoodbye()
{
Console.WriteLine("See you later");
}
}
public class DerivedClass2 : AbstractClass
{
public new void SayHello()
{
Console.WriteLine("Hi There");
}
// We should use the override keyword with abstract types
//public new void SayGoodbye()
//{
// Console.WriteLine("See you later2");
//}
public override void SayGoodbye()
{
Console.WriteLine("See you later");
}
}
}
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
Well, it's not a single statement, but it's about as close as you can get with oracle:
BEGIN
FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
END LOOP;
END;
You can use TreeSet
that automatically order list values:
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
System.out.println("Tree Set Example!\n");
TreeSet <String>tree = new TreeSet<String>();
tree.add("aaa");
tree.add("acbbb");
tree.add("aab");
tree.add("c");
tree.add("a");
Iterator iterator;
iterator = tree.iterator();
System.out.print("Tree set data: ");
//Displaying the Tree set data
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
}
}
I lastly add 'a' but last element must be 'c'.
Once I also got that same type of error.
I.E:
C:\oracle\product\10.2.0\db_2>SQLPLUS SYS AS SYSDBA
Error 6 initializing SQL*Plus
Message file sp1<lang>.msb not found
SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory
This error is occurring as the home path is not correctly set. To rectify this, if you are using Windows, run the below query:
C:\oracle\product\10.2.0\db_2>SET ORACLE_HOME=C:\oracle\product\10.2.0\db_2
C:\oracle\product\10.2.0\db_2>SQLPLUS SYS AS SYSDBA
SQL*Plus: Release 10.2.0.3.0 - Production on Tue Apr 16 13:17:42 2013
Copyright (c) 1982, 2006, Oracle. All Rights Reserved.
Or if you are using Linux, then replace set
with export
for the above command like so:
C:\oracle\product\10.2.0\db_2>EXPORT ORACLE_HOME='C:\oracle\product\10.2.0\db_2'
C:\oracle\product\10.2.0\db_2>SQLPLUS SYS AS SYSDBA
SQL*Plus: Release 10.2.0.3.0 - Production on Tue Apr 16 13:17:42 2013
Copyright (c) 1982, 2006, Oracle. All Rights Reserved.
The simplest solution is to use a derived table:
Select Count(*)
From (
Select ...
From TempTable
Group By column_1, column_2, column_3, column_4
) As Z
Another solution is to use a Count Distinct:
Select ...
, ( Select Count( Distinct column_1, column_2, column_3, column_4 )
From TempTable ) As CountOfItems
From TempTable
Group By column_1, column_2, column_3, column_4
Even shorter way, may require newer ASP.Net:
string authority = Request.Url.GetComponents(UriComponents.SchemeAndServer,UriFormat.Unescaped)
The UriComponents enum lets you specify which component(s) of the URI you want to include.
Because %
is only defined for integer types. That's the modulus operator.
5.6.2 of the standard:
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]
As Oli pointed out, you can use fmod()
. Don't forget to include math.h
.
Update after I understand more how fragments work. Each fragment belongs to a parent activity. So just use:
getActivity().whatever
From within the fragment. It is a better answer because you avoid superflous casts. If you cannot avoid the casts with this solution use the one below.
============
what you have to do is to cast to the outer activity
((MainActivity) getActivity()).Method();
creating a new instance will be confusing the android frame and it will not be able to recognize it. see also :
Create a DTO as CustomObject
Use below method to convert XML String to DTO using JAXB
private static CustomObject getCustomObject(final String ruleStr) {
CustomObject customObject = null;
try {
JAXBContext jaxbContext = JAXBContext.newInstance(CustomObject.class);
final StringReader reader = new StringReader(ruleStr);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
customObject = (CustomObject) jaxbUnmarshaller.unmarshal(reader);
} catch (JAXBException e) {
LOGGER.info("getCustomObject parse error: ", e);
}
return customObject;
}
Check if the activity isFinishing()
before showing the fragment.
Example:
if(!isFinishing()) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
DummyFragment dummyFragment = DummyFragment.newInstance();
ft.add(R.id.dummy_fragment_layout, dummyFragment);
ft.commitAllowingStateLoss();
}
In my case updating GIT helps - I had version 2.23 and with installing version 2.26.2.windows.1 problem disapears.
So if you are sure your SSH key is valid then (see @VonC answer):
And it should be ok.
Any reason they can't just click on the tab for your sheet when they want it?
if(document.readyState === 'complete') {
DoStuffFunction();
} else {
if (window.addEventListener) {
window.addEventListener('load', DoStuffFunction, false);
} else {
window.attachEvent('onload', DoStuffFunction);
}
}
you can do this using OUT parameter and CROSS JOIN
CREATE OR REPLACE FUNCTION get_object_fields(my_name text, OUT f1 text, OUT f2 text)
AS $$
SELECT t1.name, t2.name
FROM table1 t1
CROSS JOIN table2 t2
WHERE t1.name = my_name AND t2.name = my_name;
$$ LANGUAGE SQL;
then use it as a table:
select get_object_fields( 'Pending') ;
get_object_fields
-------------------
(Pending,code)
(1 row)
or
select * from get_object_fields( 'Pending');
f1 | f
---------+---------
Pending | code
(1 row)
or
select (get_object_fields( 'Pending')).f1;
f1
---------
Pending
(1 row)
This supports:
ng new project-name --routing
You can add --style=scss
for SASS .scss support.
You can add --ng4
for using Angular 4 instead of Angular 2.
After creating the project, the CLI will automatically run npm install
for you. If you want to use Yarn instead, or just want to look at the project skeleton without install, check how to do it here.
Inside the project folder:
ng build -prod
At the current version you need to to specify --aot
manually, because it can be used in development mode (although that's not practical due to slowness).
This also performs AoT compilation for even smaller bundles (no Angular compiler, instead, generated compiler output). The bundles are much smaller with AoT if you use Angular 4 as the generated code is smaller.
You can test your app with AoT in development mode (sourcemaps, no minification) and AoT by running ng build --aot
.
The default output dir is ./dist
, although it can be changed in ./angular-cli.json
.
The result of build step is the following:
(Note: <content-hash>
refers to hash / fingerprint of the contents of the file that's meant to be a cache busting way, this is possible since Webpack writes the script
tags by itself)
./dist/assets
./src/assets/**
./dist/index.html
./src/index.html
, after adding webpack scripts to it./angular-cli.json
./dist/inline.js
./dist/main.<content-hash>.bundle.js
./dist/styles.<content-hash>.bundle.js
In older versions it also created gzipped versions for checking their size, and .map
sourcemaps files, but this is no longer happening as people kept asking to remove these.
In certain other occasions, you might find other unwanted files/folders:
./out-tsc/
./src/tsconfig.json
's outDir
./out-tsc-e2e/
./e2e/tsconfig.json
's outDir
./dist/ngfactory/
Look in your .svn
folder, there will be a file in it called lock
. Delete that file and you will be able to update. There may be more lock files in the .svn
directory of each subdirectory. They will need deleting also. This could be done as a batch quite simply from the command line with e.g.
find . -name 'lock' -exec rm -v {} \;
Note that you are manually editing files in the .svn
folder. They have been put there for a reason. That reason might be a mistake, but if not you could be damaging your local copy.
These days, socket.on('connect', ...) is not working for me. I use the below code to check at 1st connecting.
if (socket.connected)
console.log('socket.io is connected.')
and use this code when reconnected.
socket.on('reconnect', ()=>{
//Your Code Here
});
The root issue in my case was a file conflict in the .settings folder. So, deleting the .settings folder would have resolved the Maven error, but I wanted to keep some of my local configuration files. I resolved the conflict, then tried a Maven update again and it worked.
function random_color(){
return sprintf('#%06X', mt_rand(0, 0xFFFFFF));
}
That's what frameworks do, e.g. if you initialize session in Front Controller or boostrap script, you won't have to care about it's initalization either for page controllers or ajax controllers. PHP frameworks are not a panacea, but they do so many useful things like this!
In rails 6, simply add this to your controller:
class UsersController < ApplicationController
include UsersHelper
# Your actions
end
Now the user_helpers.rb will be available in the controller.
Using g++, you can add the command line option: -fstack-protector-all
.
On your example it resulted in the following:
> g++ -o t -fstack-protector-all t.cc
> ./t
3
4
/bin/bash: line 1: 15450 Segmentation fault ./t
It doesn't really help you find or solve the problem, but at least the segfault will let you know that something is wrong.
Just modify one of the returned entities:
Customer c = (from x in dataBase.Customers
where x.Name == "Test"
select x).First();
c.Name = "New Name";
dataBase.SaveChanges();
Note, you can only update an entity (something that extends EntityObject, not something that you have projected using something like select new CustomObject{Name = x.Name}
Try to type in cmd: php artisan key:generate the problems will be solved
You don't need to reset all your user data to switch users. Try clicking on your name in the upper right corner then click on "Account settings". There you will get an option to sign out of the IDE. Once signed out you can sign back in as another Microsoft account.
Your problem is that you have declare twice the exec-maven-plugin :
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>C:\apache-camel-2.11.0\examples\camel-example-smooks-
integration\src\main\java\example\Main< /mainClass>
</configuration>
</plugin>
...
< plugin>
< groupId>org.codehaus.mojo</groupId>
< artifactId>exec-maven-plugin</artifactId>
< version>1.2</version>
< /plugin>
Using the Node.js readline module.
var fs = require('fs');
var readline = require('readline');
var filename = process.argv[2];
readline.createInterface({
input: fs.createReadStream(filename),
terminal: false
}).on('line', function(line) {
console.log('Line: ' + line);
});
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
The macros defined in <inttypes.h>
are the most correct way to print values of types uint32_t
, uint16_t
, and so forth -- but they're not the only way.
Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf
format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)
An alternative is to cast the values to a predefined type and use the format for that type.
Types int
and unsigned int
are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t
or uint16_t
, respectively. Similarly, long
and unsigned long
are at least 32 bits wide, and long long
and unsigned long long
are at least 64 bits wide.
For example, I might write your program like this (with a few additional tweaks):
#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>
int main(void)
{
uint32_t a=12, a1;
uint16_t b=1, b1;
a1 = htonl(a);
printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
b1 = htons(b);
printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
return 0;
}
One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>
. Such an implementation most likely wouldn't have <stdint.h>
either, but the technique is useful for other integer types.
LayoutInflater.inflate() provides a means to convert a res/layout/*.xml file defining a view into an actual View object usable in your application source code.
basic two steps: get the inflater and then inflate the resource
How do you get the inflater?
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
How do you get the view assuming the xml file is "list_item.xml"?
View view = inflater.inflate(R.layout.list_item, parent, false);
Try layout()
which I have used for this in the past by simply creating an empty plot below, properly scaled at around 1/4 or so and placing the legend parts manually in it.
There are some older questions here about legend()
which should get you started.
quite simple:
ul.yourlist li { float:left; }
or
ul.yourlist li { display:inline; }
You want options(warn=-1)
. However, note that warn=0
is not the safest warning level and it should not be assumed as the current one, particularly within scripts or functions. Thus the safest way to temporary turn off warnings is:
oldw <- getOption("warn")
options(warn = -1)
[your "silenced" code]
options(warn = oldw)
Here I have a solution that avoid multiple requests, for loops and old document removal.
You can easily create a new idea manually using something like:_id:ObjectId()
But knowing Mongo will automatically assign an _id if missing, you can use aggregate to create a $project
containing all the fields of your document, but omit the field _id. You can then save it with $out
So if your document is:
{
"_id":ObjectId("5b5ed345cfbce6787588e480"),
"title": "foo",
"description": "bar"
}
Then your query will be:
db.getCollection('myCollection').aggregate([
{$match:
{_id: ObjectId("5b5ed345cfbce6787588e480")}
}
{$project:
{
title: '$title',
description: '$description'
}
},
{$out: 'myCollection'}
])
The manual for GNU Make gives a clear definition for all
in its list of standard targets.
If the author of the Makefile is following that convention then the target all
should:
make
should do the same as make all
.To achieve 1 all
is typically defined as a .PHONY
target that depends on the executable(s) that form the entire program:
.PHONY : all
all : executable
To achieve 2 all
should either be the first target defined in the make file or be assigned as the default goal:
.DEFAULT_GOAL := all
I wanted the dropdown to select the matching value of the id in the action method. The trick is to set the Selected property when creating the SelectListItem Collection. It would not work any other way, perhaps I missed something but in end, it is more elegant in my option.
You can write any method that returns a boolean to set the Selected value based on your requirements, in my case I used the existing Equal Method
public ActionResult History(long id)
{
var app = new AppLogic();
var historyVM = new ActivityHistoryViewModel();
historyVM.ProcessHistory = app.GetActivity(id);
historyVM.Process = app.GetProcess(id);
var processlist = app.GetProcessList();
historyVM.ProcessList = from process in processlist
select new SelectListItem
{
Text = process.ProcessName,
Value = process.ID.ToString(),
Selected = long.Equals(process.ID, id)
};
var listitems = new List<SelectListItem>();
return View(historyVM);
}
Your test requires a ServletContext: add @WebIntegrationTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT
...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html
UPDATE
In Spring Boot 1.4.x and above @WebIntegrationTest
is no longer preferred. @SpringBootTest
or @WebMvcTest
Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable
Type in command line
echo %JAVA_HOME%
and
java -version
To verify whether your installation was done successfully.
This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.
Steps to resolve:
Open the Run window:
Press windows+R
Open registry window:
Type regedit
and enter.
Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\
If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.
For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:
Create a new subkey of 1.8.
For 1.8 create a String Key with name JavaHome with the value of JRE home:
Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html
I had the same issue every time I tried to create a new project, but based on the console output, it was because of two versions of android-support-v4 that were different:
[2014-10-29 16:31:57 - HeadphoneSplitter] Found 2 versions of android-support-v4.jar in the dependency list,
[2014-10-29 16:31:57 - HeadphoneSplitter] but not all the versions are identical (check is based on SHA-1 only at this time).
[2014-10-29 16:31:57 - HeadphoneSplitter] All versions of the libraries must be the same at this time.
[2014-10-29 16:31:57 - HeadphoneSplitter] Versions found are:
[2014-10-29 16:31:57 - HeadphoneSplitter] Path: C:\Users\jbaurer\workspace\appcompat_v7\libs\android-support-v4.jar
[2014-10-29 16:31:57 - HeadphoneSplitter] Length: 627582
[2014-10-29 16:31:57 - HeadphoneSplitter] SHA-1: cb6883d96005bc85b3e868f204507ea5b4fa9bbf
[2014-10-29 16:31:57 - HeadphoneSplitter] Path: C:\Users\jbaurer\workspace\HeadphoneSplitter\libs\android-support-v4.jar
[2014-10-29 16:31:57 - HeadphoneSplitter] Length: 758727
[2014-10-29 16:31:57 - HeadphoneSplitter] SHA-1: efec67655f6db90757faa37201efcee2a9ec3507
[2014-10-29 16:31:57 - HeadphoneSplitter] Jar mismatch! Fix your dependencies
I don't know a lot about Eclipse. but I simply deleted the copy of the jar file from my project's libs folder so that it would use the appcompat_v7 jar file instead. This fixed my issue.
You can bind a click handler that returns false:
$('.my-link').click(function () {return false;});
To re-enable it again, unbind the handler:
$('.my-link').unbind('click');
Note that disabled
doesn't work because it is designed for form inputs only.
jQuery has anticipated this already, providing a shortcut as of jQuery 1.4.3:
$('.my-link').bind('click', false);
And to unbind / re-enable:
$('.my-link').unbind('click', false);
You can use the DirectoryInfo.GetFiles
method:
FileInfo[] files = DirectoryInfo.GetFiles("*.xml");
I had the following problem where I was fetching data from a database and wanted to display a string containing \n
. None of the solutions above worked for me and I finally came up with a solution: https://stackoverflow.com/a/61484190/7251208
I'm not an expert, but I'd assume that enough smart people looked at Java's random number generator over the years. Hence, I'd also assume that random UUIDs are good. So you should really have the theoretical collision probability (which is about 1 : 3 × 10^38 for all possible UUIDs. Does anybody know how this changes for random UUIDs only? Is it 1/(16*4)
of the above?)
From my practical experience, I've never seen any collisions so far. I'll probably have grown an astonishingly long beard the day I get my first one ;)
In addition to what Angular University said above you may want to use @Import to aggregate @Configuration classes to the other class (AuthenticationController in my case) :
@Import(SecurityConfig.class)
@RestController
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
//some logic
}
Spring doc about Aggregating @Configuration classes with @Import: link
Hi curious you can validate your google recaptcha at client side also 100% work for me to verify your google recaptcha just see below code
This code at the html body:
<div class="g-recaptcha" id="rcaptcha" style="margin-left: 90px;" data-sitekey="my_key"></div>
<span id="captcha" style="margin-left:100px;color:red" />
This code put at head section on call get_action(this)
method form button:
function get_action(form) {
var v = grecaptcha.getResponse();
if(v.length == 0)
{
document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
return false;
}
if(v.length != 0)
{
document.getElementById('captcha').innerHTML="Captcha completed";
return true;
}
}
I have achieved this with the help of Attribute Routing in MVC5. Admittedly I am new to MVC coming from a decade of web development using WebForms, but the following has worked for me. Unlike the accepted answer this allows all the overloaded actions to be rendered by the same view file.
First enable Attribute Routing in App_Start/RouteConfig.cs.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Optionally decorate your controller class with a default route prefix.
[RoutePrefix("Returns")]
public class ReturnsController : BaseController
{
//.......
Then decorate your controller actions that overload each other with a common route and parameters to suit. Using type constrained parameters you can use the same URI format with IDs of different types.
[HttpGet]
// Returns
public ActionResult Index()
{
//.....
}
[HttpGet]
[Route("View")]
// Returns/View
public ActionResult View()
{
// I wouldn't really do this but it proves the concept.
int id = 7026;
return View(id);
}
[HttpGet]
[Route("View/{id:int}")]
// Returns/View/7003
public ActionResult View(int id)
{
//.....
}
[HttpGet]
[Route("View/{id:Guid}")]
// Returns/View/99300046-0ba4-47db-81bf-ba6e3ac3cf01
public ActionResult View(Guid id)
{
//.....
}
Hope this helps and is not leading somebody down the wrong path. :-)
Try to edit your my.cf and comment the original sql_mode and add sql_mode = "".
vi /etc/mysql/my.cnf
sql_mode = ""
save and quit...
service mysql restart
You can perform a simple each
loop on the range from 1 to `x´:
(1..x).each do |i|
#...
end
Heh, I just taught this class.
There are several options.
Simple: Pick the first or last element of the range. (bad on partially sorted input)
Better: Pick the item in the middle of the range. (better on partially sorted input)
However, picking any arbitrary element runs the risk of poorly partitioning the array of size n into two arrays of size 1 and n-1. If you do that often enough, your quicksort runs the risk of becoming O(n^2).
One improvement I've seen is pick median(first, last, mid); In the worst case, it can still go to O(n^2), but probabilistically, this is a rare case.
For most data, picking the first or last is sufficient. But, if you find that you're running into worst case scenarios often (partially sorted input), the first option would be to pick the central value( Which is a statistically good pivot for partially sorted data).
If you're still running into problems, then go the median route.
If you don't mind the binary size, you can use iproute2 as library.
Pros:
Cons:
If you accept itertools but not numpy, here is an adaptation of rwh_primes2 for Python 3 that runs about twice as fast on my machine. The only substantial change is using a bytearray instead of a list for the boolean, and using compress instead of a list comprehension to build the final list. (I'd add this as a comment like moarningsun if I were able.)
import itertools
izip = itertools.zip_longest
chain = itertools.chain.from_iterable
compress = itertools.compress
def rwh_primes2_python3(n):
""" Input n>=6, Returns a list of primes, 2 <= p < n """
zero = bytearray([False])
size = n//3 + (n % 6 == 2)
sieve = bytearray([True]) * size
sieve[0] = False
for i in range(int(n**0.5)//3+1):
if sieve[i]:
k=3*i+1|1
start = (k*k+4*k-2*k*(i&1))//3
sieve[(k*k)//3::2*k]=zero*((size - (k*k)//3 - 1) // (2 * k) + 1)
sieve[ start ::2*k]=zero*((size - start - 1) // (2 * k) + 1)
ans = [2,3]
poss = chain(izip(*[range(i, n, 6) for i in (1,5)]))
ans.extend(compress(poss, sieve))
return ans
Comparisons:
>>> timeit.timeit('primes.rwh_primes2(10**6)', setup='import primes', number=1)
0.0652179726976101
>>> timeit.timeit('primes.rwh_primes2_python3(10**6)', setup='import primes', number=1)
0.03267321276325674
and
>>> timeit.timeit('primes.rwh_primes2(10**8)', setup='import primes', number=1)
6.394284538007014
>>> timeit.timeit('primes.rwh_primes2_python3(10**8)', setup='import primes', number=1)
3.833829450302801
As basZero mentioned, X-Forwarded-For should be checked for comma. (Look at : http://en.wikipedia.org/wiki/X-Forwarded-For). The general format of the field is: X-Forwarded-For: clientIP, proxy1, proxy2... and so on. So we will be seeing something like this : X-FORWARDED-FOR: 129.77.168.62, 129.77.63.62.
This is a security and maintainability question.
Whenever possible, you should use 'safe' (unidirectional) methods such as GET and HEAD in order to limit potential vulnerability.
Whenever possible, you should use 'idempotent' methods such as GET, HEAD, PUT and DELETE, which can't have side effects and are therefore less error prone/easier to control.
You can try this fineuploader
It works fine under IE6(and above), Chrome or Firefox
This solution creates a psobject and adds each object to an array, it then creates the csv by piping the contents of the array through Export-CSV.
$results = @()
foreach ($computer in $computerlist) {
if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
{
foreach ($file in $REMOVE) {
Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
Copy-Item E:\Code\powershell\shortcuts\* "\\$computer\$DESTINATION\"
}
} else {
$details = @{
Date = get-date
ComputerName = $Computer
Destination = $Destination
}
$results += New-Object PSObject -Property $details
}
}
$results | export-csv -Path c:\temp\so.csv -NoTypeInformation
If you pipe a string object to a csv you will get its length written to the csv, this is because these are properties of the string, See here for more information.
This is why I create a new object first.
Try the following:
write-output "test" | convertto-csv -NoTypeInformation
This will give you:
"Length"
"4"
If you use the Get-Member on Write-Output as follows:
write-output "test" | Get-Member -MemberType Property
You will see that it has one property - 'length':
TypeName: System.String
Name MemberType Definition
---- ---------- ----------
Length Property System.Int32 Length {get;}
This is why Length will be written to the csv file.
Update: Appending a CSV Not the most efficient way if the file gets large...
$csvFileName = "c:\temp\so.csv"
$results = @()
if (Test-Path $csvFileName)
{
$results += Import-Csv -Path $csvFileName
}
foreach ($computer in $computerlist) {
if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
{
foreach ($file in $REMOVE) {
Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
Copy-Item E:\Code\powershell\shortcuts\* "\\$computer\$DESTINATION\"
}
} else {
$details = @{
Date = get-date
ComputerName = $Computer
Destination = $Destination
}
$results += New-Object PSObject -Property $details
}
}
$results | export-csv -Path $csvFileName -NoTypeInformation
Here is a very simple way to create an IP certificate that Chrome will trust.
The ssl.conf file...
[ req ]
default_bits = 4096
distinguished_name = req_distinguished_name
req_extensions = req_ext
prompt = no
[ req_distinguished_name ]
commonName = 192.168.1.10
[ req_ext ]
subjectAltName = IP:192.168.1.10
Where, of course 192.168.1.10 is the local network IP we want Chrome to trust.
Create the certificate:
openssl genrsa -out key1.pem
openssl req -new -key key1.pem -out csr1.pem -config ssl.conf
openssl x509 -req -days 9999 -in csr1.pem -signkey key1.pem -out cert1.pem -extensions req_ext -extfile ssl.conf
rm csr1.pem
On Windows import the certificate into the Trusted Root Certificate Store on all client machines. On Android Phone or Tablet download the certificate to install it. Now Chrome will trust the certificate on windows and Android.
On windows dev box the best place to get openssl.exe is from "c:\Program Files\Git\usr\bin\openssl.exe"
Always show errors on a testing server. Never show errors on a production server.
Write a script to determine whether the page is on a local, testing, or live server, and set $state to "local", "testing", or "live". Then:
if( $state == "local" || $state == "testing" )
{
ini_set( "display_errors", "1" );
error_reporting( E_ALL & ~E_NOTICE );
}
else
{
error_reporting( 0 );
}
http://dev.mysql.com/doc/refman/5.0/en/insert-select.html
For case1:
INSERT INTO TAB_STUDENT(name_student, id_teacher_fk)
SELECT 'Joe The Student', id_teacher
FROM TAB_TEACHER
WHERE name_teacher = 'Professor Jack'
LIMIT 1
For case2 you just have to do 2 separate insert statements
One more variant using extension
and argument name range
This extension uses Range
and ClosedRange
extension Array {
subscript (range r: Range<Int>) -> Array {
return Array(self[r])
}
subscript (range r: ClosedRange<Int>) -> Array {
return Array(self[r])
}
}
Tests:
func testArraySubscriptRange() {
//given
let arr = ["1", "2", "3"]
//when
let result = arr[range: 1..<arr.count] as Array
//then
XCTAssertEqual(["2", "3"], result)
}
func testArraySubscriptClosedRange() {
//given
let arr = ["1", "2", "3"]
//when
let result = arr[range: 1...arr.count - 1] as Array
//then
XCTAssertEqual(["2", "3"], result)
}
Here's an ES6 version of the answer provided by 7stud.
const sel = document.createElement('select');
sel.name = 'drop1';
sel.id = 'Select1';
const cars = [
"Volvo",
"Saab",
"Mercedes",
"Audi",
];
const options = cars.map(car => {
const value = car.toLowerCase();
return `<option value="${value}">${car}</option>`;
});
sel.innerHTML = options;
window.onload = () => document.body.appendChild(sel);
This can be addressed using the following LINQ expression:
var result = peopleList2.Where(p => !peopleList1.Any(p2 => p2.ID == p.ID));
An alternate way of expressing this via LINQ, which some developers find more readable:
var result = peopleList2.Where(p => peopleList1.All(p2 => p2.ID != p.ID));
Warning: As noted in the comments, these approaches mandate an O(n*m) operation. That may be fine, but could introduce performance issues, and especially if the data set is quite large. If this doesn't satisfy your performance requirements, you may need to evaluate other options. Since the stated requirement is for a solution in LINQ, however, those options aren't explored here. As always, evaluate any approach against the performance requirements your project might have.
If you are interested in understand performance, the best answer is to use a profiler.
Otherwise, System.Diagnostics.StopWatch provides a high resolution timer.
For Android, I previously used tPacketCapture but it didn't work well for an app streaming some video. I'm now using Shark. You need to be root to use it though.
It uses TCPDump (check the arguments you can pass) and creates a pcap file that can be read by Wireshark. The default arguments are usually good enough for me.
Eric's answer helpfully explains that the trouble comes from comparing a Pandas Series (containing a NumPy array) to a Python string. Unfortunately, his two workarounds both just suppress the warning.
To write code that doesn't cause the warning in the first place, explicitly compare your string to each element of the Series and get a separate bool for each. For example, you could use map
and an anonymous function.
myRows = df[df['Unnamed: 5'].map( lambda x: x == 'Peter' )].index.tolist()
You can always format a date by extracting the parts and combine them using string functions:
var date = new Date();_x000D_
var dateStr =_x000D_
("00" + (date.getMonth() + 1)).slice(-2) + "/" +_x000D_
("00" + date.getDate()).slice(-2) + "/" +_x000D_
date.getFullYear() + " " +_x000D_
("00" + date.getHours()).slice(-2) + ":" +_x000D_
("00" + date.getMinutes()).slice(-2) + ":" +_x000D_
("00" + date.getSeconds()).slice(-2);_x000D_
console.log(dateStr);
_x000D_
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
'async': false
says it's depreciated. I did notice if I run console.log('test1');
on ajax success, then console.log('test2');
in normal js after the ajax function, test2
prints before test1
so the issue is an ajax call has a small delay, but doesn't stop the rest of the function to get results. The variable simply, was not set "yet", so you need to delay the next function.
function runPHP(){
var input = document.getElementById("input1");
var result = 'failed to run php';
$.ajax({ url: '/test.php',
type: 'POST',
data: {action: 'test'},
success: function(data) {
result = data;
}
});
setTimeout(function(){
console.log(result);
}, 1000);
}
on test.php (incase you need to test this function)
function test(){
print 'ran php';
}
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = htmlentities($_POST['action']);
switch($action) {
case 'test' : test();break;
}
}
if its date in 24 hours and start in morning and end in the night should add something like :
declare @Approval_date datetime
set @Approval_date =getdate()
Approval_date between @Approval_date +' 00:00:00.000' and @Approval_date +' 23:59:59.999'
I had huge problems with this
First I tried .clear()
then I tried .destroy()
and I tried setting my chart reference to null
What finally fixed the issue for me: deleting the <canvas>
element and then reappending a new <canvas>
to the parent container
There's a million ways to do this:
var resetCanvas = function () {
$('#results-graph').remove(); // this is my <canvas> element
$('#graph-container').append('<canvas id="results-graph"><canvas>');
canvas = document.querySelector('#results-graph'); // why use jQuery?
ctx = canvas.getContext('2d');
ctx.canvas.width = $('#graph').width(); // resize to parent width
ctx.canvas.height = $('#graph').height(); // resize to parent height
var x = canvas.width/2;
var y = canvas.height/2;
ctx.font = '10pt Verdana';
ctx.textAlign = 'center';
ctx.fillText('This text is centered on the canvas', x, y);
};
Have your thread notify some other thread when it’s finished. This way you’ll always know exactly what’s going on.
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string.Join("", test);
Unfortunately max-width + max-height do not fully cover my task... So I have found another solution:
To save the Image ratio while scaling you also can use object-fit
CSS3 propperty.
Useful article: Control image aspect ratios with CSS3
img {
width: 100%; /* or any custom size */
height: 100%;
object-fit: contain;
}
Bad news: IE not supported (Can I Use)
you can use directly (blur) event in input tag.
<div>
<input [value] = "" (blur) = "result = $event.target.value" placeholder="Type Something">
{{result}}
</div>
and you will get output in "result"
Simply because CPU/ABI says "No system images installed for this target". You need to install system images.
In the Android SDK Manager check that you have installed "ARM EABI v7a System Image" (for each Android version from 4.0 and on you have to install a system image to be able to run a virtual device)
In your case only ARM system image exsits (Android 4.2). If you were running an older version, Intel has provided System Images (Intel x86 ATOM). You can check on the internet to see the comparison in performance between both.
In my case (see image below) I haven't installed a System Image for Android 4.2, whereas I have installed ARM and Intel System Images for 4.1.2
As long as I don't install the 4.2 System Image I would have the same problem as you.
UPDATE : This recent article Speeding Up the Android Emaulator on Intel Architectures explains how to use/install correctly the intel system images to speed up the emulator.
EDIT/FOLLOW UP
What I show in the picture is for Android 4.2, as it was the original question, but is true for every versions of Android.
Of course (as @RedPlanet said), if you are developing for MIPS CPU devices you have to install the "MIPS System Image".
Finally, as @SeanJA said, you have to restart eclipse to see the new installed images. But for me, I always restart a software which I updated to be sure it takes into account all the modifications, and I assume it is a good practice to do so.
I liked the way @OscarRyz presents. Although here i am continuing the story of serialization which was originally written by @amitgupta.
Even though knowing about the robot class structure and having serialized data Earth's scientist were not able to deserialize the data which can make robots working.
Exception in thread "main" java.io.InvalidClassException:
SerializeMe; local class incompatible: stream classdesc
:
Mars's scientists were waiting for the complete payment. Once the payment was done Mars's scientists shared the serialversionUID with Earth's scientists. Earth's scientist set it to robot class and everything became fine.
The code listed below works:
var favicon = require('serve-favicon');
app.use(favicon(__dirname + '/public/images/favicon.ico'));
Just make sure to refresh your browser or clear your cache.
For 'd/m/Y'
dates:
usort($array, function ($a, $b, $i = 'datetime') {
$t1 = strtotime(str_replace('/', '-', $a[$i]));
$t2 = strtotime(str_replace('/', '-', $b[$i]));
return $t1 > $t2;
});
where $i
is the array index
Had the issue again when i moved from one machine to another and had everything reinstalled. In my case, i'm using both 32bit and 64bit Oracle ODP.NET installs.
When listing the assemblies on my new machine i ended up with the following list
C:\oracle\product\11.2.0\X64\odp.net\bin\4>gacutil /l|findstr Oracle.DataAccess
Oracle.DataAccess, Version=2.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=AMD64
Policy.2.102.Oracle.DataAccess, Version=2.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=AMD64
Policy.2.111.Oracle.DataAccess, Version=2.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=AMD64
Policy.2.112.Oracle.DataAccess, Version=2.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=AMD64
Oracle.DataAccess, Version=4.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=AMD64
Policy.4.112.Oracle.DataAccess, Version=4.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=AMD64
only 64bit DLLs to be seen here.
I couldn't see it from the web.config but the one i was using was a 32bit version.
When checking my old machine with the GACutil, i saw more DLLs, also the X86 ones.
Fixed by reapplying the registration process(both x32/x64 version referenced here)
OraProvCfg.exe /action:gac /providerpath:C:\oracle\product\11.2.0\x32\ODP.NET\bin\4\Oracle.DataAccess.dll
OraProvCfg.exe /action:gac /providerpath:C:\oracle\product\11.2.0\x64\ODP.NET\bin\4\Oracle.DataAccess.dll
after that , Visual Studio was a happy bunny and compiled everything again for me.
For anyone trying to set this for Rails projects, add
set directory=tmp,/tmp
into your
~/.vimrc
So the .swp files will be in their natural location - the tmp directory (per project).
This happened to me when I tried to update a table whose size on disk was bigger than the available disk space. The solution for me was simply to increase the available disk space.
$(document ).ready(function() {
$('select[name=selectorname]').change(function() {
alert($(this).val());});
});
Declare @v1 varchar(max), @v2 varchar(200);
Declare @sql nvarchar(max);
Set @sql = N'SELECT @v1 = value1, @v2 = value2
FROM dbo.TblTest -- always use schema
WHERE ID = 61;';
EXEC sp_executesql @sql,
N'@v1 varchar(max) output, @v2 varchar(200) output',
@v1 output, @v2 output;
You should also pass your input, like wherever 61 comes from, as proper parameters (but you won't be able to pass table and column names that way).
For that you neet to use the g flag of regex.... Like this :
var new_string=old_string.replace( / (regex) /g, replacement_text);
That sh
XCode > 6.0 AND iOS > 8.0 The below script works if you have XCode version > 8.0
I use the below small Script to tail the simulator logs onto the system console.
#!/bin/sh
sim_dir=`xcrun instruments -s | grep "iPhone 6 (8.2 Simulator)" | awk {'print $NF'} | tr -d '[]'`
tail -f ~/Library/Logs/CoreSimulator/$sim_dir/system.log
You can pass in the simulator type used in the Grep as an argument. As mentioned in the above posts, there are simctl and instruments command to view the type of simulators available for use depending on the Xcode version. To View the list of available devices/simulators.
xcrun instruments -s
OR
xcrun simctl list
Now you can pass in the Device code OR Simulator type as an argument to the script and replace the "iPhone 6 (8.2 Simulator)" inside grep to be $1
Here is my solution:
yourEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
NumberFormat formatter = new DecimalFormat("#.##");
double doubleVal = Double.parseDouble(s.toString());
yourEditText.setText(formatter.format(doubleVal));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
@Override
public void afterTextChanged(Editable s) {}
});
If the user enters a number with more than two numbers after the decimal point, it will be automatically corrected.
I hope I have helped!
class
vs static
class
is used inside Reference Type
(class):
static
is used inside Reference Type
and Value Type
(class, enum):
protocol MyProtocol {
// class var protocolClassVariable : Int { get }//ERROR: Class properties are only allowed within classes
static var protocolStaticVariable : Int { get }
// class func protocolClassFunc()//ERROR: Class methods are only allowed within classes
static func protocolStaticFunc()
}
struct ValueTypeStruct: MyProtocol {
//MyProtocol implementation begin
static var protocolStaticVariable: Int = 1
static func protocolStaticFunc() {
}
//MyProtocol implementation end
// class var classVariable = "classVariable"//ERROR: Class properties are only allowed within classes
static var staticVariable = "staticVariable"
// class func classFunc() {} //ERROR: Class methods are only allowed within classes
static func staticFunc() {}
}
class ReferenceTypeClass: MyProtocol {
//MyProtocol implementation begin
static var protocolStaticVariable: Int = 2
static func protocolStaticFunc() {
}
//MyProtocol implementation end
var variable = "variable"
// class var classStoredPropertyVariable = "classVariable"//ERROR: Class stored properties not supported in classes
class var classComputedPropertyVariable: Int {
get {
return 1
}
}
static var staticStoredPropertyVariable = "staticVariable"
static var staticComputedPropertyVariable: Int {
get {
return 1
}
}
class func classFunc() {}
static func staticFunc() {}
}
final class FinalSubReferenceTypeClass: ReferenceTypeClass {
override class var classComputedPropertyVariable: Int {
get {
return 2
}
}
override class func classFunc() {}
}
//class SubFinalSubReferenceTypeClass: FinalSubReferenceTypeClass {}// ERROR: Inheritance from a final class
new String(byteArray, Charset.defaultCharset())
This will convert a byte array to the default charset in java. It may throw exceptions depending on what you supply with the byteArray.
You are trying to run Java code with Python. In Python/Selenium, the org.openqa.selenium.interactions.Actions
are reflected in ActionChains
class:
from selenium.webdriver.common.action_chains import ActionChains
element = driver.find_element_by_id("my-id")
actions = ActionChains(driver)
actions.move_to_element(element).perform()
Or, you can also "scroll into view" via scrollIntoView()
:
driver.execute_script("arguments[0].scrollIntoView();", element)
If you are interested in the differences:
Assuming that this
is .d
, you can write
$(this).closest('.a');
The closest
method returns the innermost parent of your element that matches the selector.
There are some good answers already with explanations of why the mixture of the non-static Context
method getText()
can't be used with your static final String
.
A good question to ask is: why do you want to do this? You are attempting to load a String
from your strings
resource, and populate its value into a public static
field. I assume that this is so that some of your other classes can access it? If so, there is no need to do this. Instead pass a Context
into your other classes and call context.getText(R.string.TTT)
from within them.
public class NonActivity {
public static void doStuff(Context context) {
String TTT = context.getText(R.string.TTT);
...
}
}
And to call this from your Activity
:
NonActivity.doStuff(this);
This will allow you to access your String
resource without needing to use a public static
field.
Do note that if you're adding stuff, you might always want to check that you're not going beyond the limits of int
(especially in homework exercises).
Also, int main ()
should return an int
.
Using a "do .. while" loop:
#include<iostream>
using namespace std;
int main ()
{
int sum = 0;
int previous = 0;
int number;
int numberitems;
int count = 0;
cout << "Enter number of items: ";
cin >> numberitems;
if ( numberitems <= 0 )
{
//no request to perform sum
cout << "Quitting without summing.\n\n";
return 0;
}
do
{
cout << "Enter number to add : ";
cin >> number;
sum+=number;
// check here that the addition didn't break anything.
// Negative + negative should stay negative, positive + postive should stay positive
if ((number > 0 && previous > 0 && sum < 0) || (number < 0 && previous < 0 && sum > 0))
{
cout << "Error: Beyond int limits !!";
return 1;
}
count++;
previous = sum;
}
while ( count < numberitems);
cout<<"sum is: "<< sum<<endl;
return 0;
}
If you are using angular
and ie 9, 10
or edge
use :
myModule.config(['$httpProvider', function($httpProvider) {
//initialize get if not there
if (!$httpProvider.defaults.headers.get) {
$httpProvider.defaults.headers.get = {};
}
// Answer edited to include suggestions from comments
// because previous version of code introduced browser-related errors
//disable IE ajax request caching
$httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
// extra
$httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
$httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
}]);
To completely disable cache
.
I don't think that they really are random, but my guess is those are some hashes.
Whenever I need some random identifier, I usually use a GUID and convert it to its "naked" representation:
Guid.NewGuid().ToString("n");
After posting this I did come up with a way that works. However, I don't feel it is the best way to handle this. Any suggestions on a better one?
//Check to see if we get rows back, if we do just bind.
if (dtFunding.Rows.Count != 0)
{
grdFunding.DataSource = dtFunding;
grdFunding.DataBind();
}
else
{
//Other wise add a emtpy "New Row" to the datatable and then hide it after binding.
dtFunding.Rows.Add(dtFunding.NewRow());
grdFunding.DataSource = dtFunding;
grdFunding.DataBind();
grdFunding.Rows[0].Visible = false;
}
The following code will not raise an exception and will exit without a traceback:
import os
os._exit(1)
See this question and related answers for more details. Surprised why all other answers are so overcomplicated.
Create the data/db directory in your main (windows) partition:
C:\> mkdir \data
C:\> mkdir \data\db
and then go to your mongo_directory/bin and run mongod.exe:
C:\> cd \my_mongo_dir\bin
C:\my_mongo_dir\bin> mongod
DON't CLOSE THIS WINDOW
Now in a different command prompt window run Mongo:
C:\> cd \my_mongo_dir\bin
C:\my_mongo_dir\bin> mongo
(REMEMBER YOU HAVE TO KEEP THAT OTHER WINDOW OPEN)
This solved the problem for me.
I've used this with Jackson 2.x and Spring 3.1.2+
servlet-context.xml:
Note that the root element is <beans:beans>
, so you may need to remove beans
and add mvc
to some of these elements depending on your setup.
<annotation-driven>
<message-converters>
<beans:bean
class="org.springframework.http.converter.StringHttpMessageConverter" />
<beans:bean
class="org.springframework.http.converter.ResourceHttpMessageConverter" />
<beans:bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<beans:property name="objectMapper" ref="jacksonObjectMapper" />
</beans:bean>
</message-converters>
</annotation-driven>
<beans:bean id="jacksonObjectMapper"
class="au.edu.unimelb.atcom.transfer.json.mappers.JSONMapper" />
au.edu.unimelb.atcom.transfer.json.mappers.JSONMapper.java:
public class JSONMapper extends ObjectMapper {
public JSONMapper() {
SimpleModule module = new SimpleModule("JSONModule", new Version(2, 0, 0, null, null, null));
module.addSerializer(Date.class, new DateSerializer());
module.addDeserializer(Date.class, new DateDeserializer());
// Add more here ...
registerModule(module);
}
}
DateSerializer.java:
public class DateSerializer extends StdSerializer<Date> {
public DateSerializer() {
super(Date.class);
}
@Override
public void serialize(Date date, JsonGenerator json,
SerializerProvider provider) throws IOException,
JsonGenerationException {
// The client side will handle presentation, we just want it accurate
DateFormat df = StdDateFormat.getBlueprintISO8601Format();
String out = df.format(date);
json.writeString(out);
}
}
DateDeserializer.java:
public class DateDeserializer extends StdDeserializer<Date> {
public DateDeserializer() {
super(Date.class);
}
@Override
public Date deserialize(JsonParser json, DeserializationContext context)
throws IOException, JsonProcessingException {
try {
DateFormat df = StdDateFormat.getBlueprintISO8601Format();
return df.parse(json.getText());
} catch (ParseException e) {
return null;
}
}
}
Please see IIS7 Integrated mode: Request is not available in this context exception in Application_Start:
The “Request is not available in this context” exception is one of the more common errors you may receive on when moving ASP.NET applications to Integrated mode on IIS 7.0. This exception happens in your implementation of the Application_Start method in the global.asax file if you attempt to access the HttpContext of the request that started the application.
please try to make it as a character
string str = "Tigger";
//then str[0] will return 'T' not "T"
First install setuptools
sudo pip install setuptools
Then install mysql-connector
sudo pip install mysql-connector
If using Python3, then replace pip by pip3
For those who need absolute positioning, a simple option I opted for is to add a wrapper component that is styled to cover the whole page with a transparent background. Then you can add an onClick on this element to close your inside component.
<div style={{
position: 'fixed',
top: '0', right: '0', bottom: '0', left: '0',
zIndex: '1000',
}} onClick={() => handleOutsideClick()} >
<Content style={{position: 'absolute'}}/>
</div>
As it is right now if you add a click handler on content, the event will also be propagated to the upper div and therefore trigger the handlerOutsideClick. If this is not your desired behavior, simply stop the event progation on your handler.
<Content style={{position: 'absolute'}} onClick={e => {
e.stopPropagation();
desiredFunctionCall();
}}/>
`
You may try using ellipsis by adding the following in CSS:
.truncate {
width: 250px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
But it seems like this code just applies to one-line trim. More ways to trim text and show ellipsis can be found in this website: http://blog.sanuker.com/?p=631
This is a take on Mike W's answer:
internal static DateTime GetPreviousMonth(bool returnLastDayOfMonth)
{
DateTime firstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );
DateTime lastDayOfLastMonth = firstDayOfThisMonth.AddDays (-1);
if (returnLastDayOfMonth) return lastDayOfLastMonth;
return firstDayOfThisMonth.AddMonths(-1);
}
You can call it like so:
dateTimePickerFrom.Value = GetPreviousMonth(false);
dateTimePickerTo.Value = GetPreviousMonth(true);
And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747
I have run into this several times and have an example dictionary that I created from a function get_max_Path()
, and it returns the sample dictionary:
{2: 0.3097502930247044,
3: 0.4413177909384636,
4: 0.5197224051562838,
5: 0.5717654946470984,
6: 0.6063959031223476,
7: 0.6365209824708223,
8: 0.655918861281035,
9: 0.680844386645206}
To convert this to a dataframe, I ran the following:
df = pd.DataFrame.from_dict(get_max_path(2), orient = 'index').reset_index()
Returns a simple two column dataframe with a separate index:
index 0
0 2 0.309750
1 3 0.441318
Just rename the columns using f.rename(columns={'index': 'Column1', 0: 'Column2'}, inplace=True)
Daniel Kutik's answer is correct, but it can be even more safe, with database renaming.
So, the truly safe way is:
In case of emergency, just rename DBs back
i'd also like to know the right way, but you can always peek either into:
$ cat .git/packed-refs
or:
$ cat .git/refs/tags/*
private float distanceFrom_in_Km(float lat1, float lng1, float lat2, float lng2) {
if (lat1== null || lng1== null || lat2== null || lng2== null)
{
return null;
}
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
The function parse_str()
automatically reads all query parameters into an array.
For example, if the URL is http://www.example.com/page.php?x=100&y=200
, the code
$queries = array();
parse_str($_SERVER['QUERY_STRING'], $queries);
will store parameters into the $queries
array ($queries['x']=100
, $queries['y']=200
).
Look at documentation of parse_str
EDIT
According to the PHP documentation, parse_str()
should only be used with a second parameter. Using parse_str($_SERVER['QUERY_STRING'])
on this URL will create variables $x
and $y
, which makes the code vulnerable to attacks such as http://www.example.com/page.php?authenticated=1
.
Try this
class piramid
{
public static void main(String[] args)
{
//System.out.println("Hello World!");
int max = 7;
int k=max/2;
int j ;
printf("\n");
printf("\n");
printf("\n");
printf("\n");
for(i=k;i>0;i--){
for(j=0;j<k+1;j++){
if(i==j){
printf("*");
}else if(j>i){
printf(" ");
printf("*");
}else {
printf(" ");
}
}
printf("\n");
}
}
}
hope it will help you
Assume you were:
There are many more examples, but these are the most common, in my experience.
No jQuery:
// Return an array of the selected opion values
// select is an HTML select element
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
Quick example:
<select multiple>
<option>opt 1 text
<option value="opt 2 value">opt 2 text
</select>
<button onclick="
var el = document.getElementsByTagName('select')[0];
alert(getSelectValues(el));
">Show selected values</button>
The following definition might be more efficient than the first solution proposed
def new_list_from_intervals(original_list, *intervals):
n = sum(j - i for i, j in intervals)
new_list = [None] * n
index = 0
for i, j in intervals :
for k in range(i, j) :
new_list[index] = original_list[k]
index += 1
return new_list
then you can use it like below
new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))
Just create another form (let's call it formPopup
) using Visual Studio. In a button handler write the following code:
var formPopup = new Form();
formPopup.Show(this); // if you need non-modal window
If you need a non-modal window use: formPopup.Show();
. If you need a dialog (so your code will hang on this invocation until you close the opened form) use: formPopup.ShowDialog()
You are using field access strategy (determined by @Id annotation). Put any JPA related annotation right above each field instead of getter property
@OneToMany(targetEntity=Student.class, mappedBy="college", fetch=FetchType.EAGER)
private List<Student> students;
Replace
values = ",".join(value_list)
with
values = ','.join([str(i) for i in value_list])
OR
values = ','.join(str(value_list)[1:-1])
For testing only two values, I'd personally do this:
if x ~= 0 and x ~= 1 then
print( "X must be equal to 1 or 0" )
return
end
If you need to test against more than two values, I'd stuff your choices in a table acting like a set, like so:
choices = {[0]=true, [1]=true, [3]=true, [5]=true, [7]=true, [11]=true}
if not choices[x] then
print("x must be in the first six prime numbers")
return
end
There are different points of view. One is they are the same. But in practice, we need to differentiate formal parameters (declarations in the method's header) and actual parameters (values passed at the point of invocation). While phrases "formal parameter" and "actual parameter" are common, "formal argument" and "actual argument" are not used. This is because "argument" is used mainly to denote "actual parameter". As a result, some people insist that "parameter" can denote only "formal parameter".
You can't add a Button to an empty list without creating a new instance of that Button. You are missing the
Button newButton = new Button();
in your code plus get rid of the .Capacity
try my header here for a quick and easy way to color text: Aedi's Color Header
Color Your Output in Unix using C++!!
ATTRIBUTES_OFF, BOLD, UNDERSCORE, BLINK, REVERSE_VIDEO, CONCEALED
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE
General Format, include value you want in $variable$
COLOR_$Foreground_Color$_$Background_Color$
COLOR_$Text_Attribute$_$Foreground_Color$_$Background_Color$
COLOR_NORMAL // To set color to default
e.g.
COLOR_BLUE_BLACK // Leave Text Attribute Blank if no Text Attribute appied
COLOR_UNDERSCORE_YELLOW_RED
COLOR_NORMAL
Just use to stream the color you want before outputting text and use again to set the color to normal after outputting text.
cout << COLOR_BLUE_BLACK << "TEXT" << COLOR_NORMAL << endl;
cout << COLOR_BOLD_YELLOW_CYAN << "TEXT" << COLOR_NORMAL << endl;
Try:
self.request.get('sports_played', allow_multiple=True)
or
self.request.POST.getall('sports_played')
More specifically:
When you are reading data from the checkbox array, make sure array has:
len>0
In this case:
len(self.request.get('array', allow_multiple=True)) > 0
For those of you in a .NET environment the following can be a handy way to filter non-numbers out (this example is in VB.NET, but it's probably similar in C#):
If Double.IsNaN(MyVariableName) Then
MyVariableName = 0 ' Or whatever you want to do here to "correct" the situation
End If
If you try to use a variable that has a NaN value you will get the following error:
Value was either too large or too small for a Decimal.
There are workarounds but no clean/short/sweet way to do it with streams and to be honest, you would probably be better off with:
int idx = 0;
for (Param p : params) query.bind(idx++, p);
Or the older style:
for (int idx = 0; idx < params.size(); idx++) query.bind(idx, params.get(idx));
I've used them as static variables for a function. For example, given the following C code:
int fn(int i)
{
static f = 1;
f += i;
return f;
}
I can implement the function similarly in Python:
def fn(i):
fn.f += i
return fn.f
fn.f = 1
This would definitely fall into the "abuses" end of the spectrum.
This post helped me with zip()
. I know I'm a few years late, but I still want to contribute. This is in Python 3.
Note: in python 2.x, zip()
returns a list of tuples; in Python 3.x, zip()
returns an iterator.
itertools.izip()
in python 2.x == zip()
in python 3.x
Since it looks like you're building a list of tuples, the following code is the most pythonic way of trying to accomplish what you are doing.
>>> lat = [1, 2, 3]
>>> long = [4, 5, 6]
>>> tuple_list = list(zip(lat, long))
>>> tuple_list
[(1, 4), (2, 5), (3, 6)]
Or, alternatively, you can use list comprehensions
(or list comps
) should you need more complicated operations. List comprehensions also run about as fast as map()
, give or take a few nanoseconds, and are becoming the new norm for what is considered Pythonic versus map()
.
>>> lat = [1, 2, 3]
>>> long = [4, 5, 6]
>>> tuple_list = [(x,y) for x,y in zip(lat, long)]
>>> tuple_list
[(1, 4), (2, 5), (3, 6)]
>>> added_tuples = [x+y for x,y in zip(lat, long)]
>>> added_tuples
[5, 7, 9]
this.setState creates an infinite loop when used in ComponentDidUpdate when there is no break condition in the loop. You can use redux to set a variable true in the if statement and then in the condition set the variable false then it will work.
Something like this.
if(this.props.route.params.resetFields){
this.props.route.params.resetFields = false;
this.setState({broadcastMembersCount: 0,isLinkAttached: false,attachedAffiliatedLink:false,affilatedText: 'add your affiliate link'});
this.resetSelectedContactAndGroups();
this.hideNext = false;
this.initialValue_1 = 140;
this.initialValue_2 = 140;
this.height = 20
}
In python version >= 2.7 and in python 3:
d = {el:0 for el in a}
See also inconsistent box model between input, select, ...
Use curl --data-urlencode
; from man curl
:
This posts data, similar to the other
--data
options with the exception that this performs URL-encoding. To be CGI-compliant, the<data>
part should begin with a name followed by a separator and a content specification.
Example usage:
curl \
--data-urlencode "paramName=value" \
--data-urlencode "secondParam=value" \
http://example.com
See the man page for more info.
This requires curl 7.18.0 or newer (released January 2008). Use curl -V
to check which version you have.
You can as well encode the query string:
curl -G \
--data-urlencode "p1=value 1" \
--data-urlencode "p2=value 2" \
http://example.com
# http://example.com?p1=value%201&p2=value%202
A simple snippet if any need it:
var fs = require('fs'), objMod = {};
process.argv.slice(2).map(function(y, i) {
y = y.split('=');
if (y[0] && y[1]) objMod[y[0]] = y[1];
else console.log('Error in argument number ' + (i+1));
});
It's just an addition, with this you can get the data into CSV format
import sys,os
try:
import pandas as pd
except:
os.system("pip3 install pandas")
root = "/home/kiran/Downloads/MainFolder" # it may have many subfolders and files inside
lst = []
from fnmatch import fnmatch
pattern = "*.csv" #I want to get only csv files
pattern = "*.*" # Note: Use this pattern to get all types of files and folders
for path, subdirs, files in os.walk(root):
for name in files:
if fnmatch(name, pattern):
lst.append((os.path.join(path, name)))
df = pd.DataFrame({"filePaths":lst})
df.to_csv("filepaths.csv")
Try this, I work myself to do so
\i 'somedir\\script2.sql'
Answer from Gijs was most valuable for me, but unfortunately the extension does not work.
Here's a rewritten extension that works, it may help someone:
jQuery.fn.getLabels = function () {
return this.map(function () {
var parentLabels = $(this).parents('label').get();
var associatedLabels = this.id ? associatedLabels = $("label[for='" + this.id + "']").get() : [];
return parentLabels.concat(associatedLabels);
});
};
More compact way to get the difference between two datetime objects and then convert the difference into seconds is shown below (Python 3x):
from datetime import datetime
time1 = datetime.strftime('18 01 2021', '%d %m %Y')
time2 = datetime.strftime('19 01 2021', '%d %m %Y')
difference = time2 - time1
difference_in_seconds = difference.total_seconds()
I know this is very late, but maybe this will help someone else.
I use a Cancel button to return to the referring url. In the View, try adding this:
@{
ViewBag.Title = "Page title";
Layout = "~/Views/Shared/_Layout.cshtml";
if (Request.UrlReferrer != null)
{
string returnURL = Request.UrlReferrer.ToString();
ViewBag.ReturnURL = returnURL;
}
}
Then you can set your buttons href like this:
<a href="@ViewBag.ReturnURL" class="btn btn-danger">Cancel</a>
Other than that, the update by Jason Enochs works great!
First, this code here,
string [] scripts = new String [] ("test3","test4","test5");
should be
String[] scripts = new String [] {"test3","test4","test5"};
Please read this tutorial on Arrays
Second,
Arrays are fixed size, so you can't add new Strings to above array. You may override existing values
scripts[0] = string1;
(or)
Create array with size then keep on adding elements till it is full.
If you want resizable arrays, consider using ArrayList.
As the previous answer did show an example of how the full hook might look like here is the code of my working post-receive hook:
#!/usr/bin/python
import sys
from subprocess import call
if __name__ == '__main__':
for line in sys.stdin.xreadlines():
old, new, ref = line.strip().split(' ')
if ref == 'refs/heads/master':
print "=============================================="
print "Pushing to master. Triggering jenkins. "
print "=============================================="
sys.stdout.flush()
call(["curl", "-sS", "http://jenkinsserver/git/notifyCommit?url=ssh://user@gitserver/var/git/repo.git"])
In this case I trigger jenkins jobs only when pushing to master and not other branches.
You can bind function as follows, instead of init on load
$("div").css("height", $(window).height());
$(?window?).bind("resize",function() {
$("div").css("height", $(window).height());
});????
Alternative solution based on the OP's own solution by utilizing an enum
. Additionally, a parser and round-trip tests are included.
public class RomanNumber {
public enum Digit {
M(1000, 3),
CM(900, 1),
D(500, 1),
CD(400, 1),
C(100, 3),
XC(90, 1),
L(50, 1),
XL(40, 1),
X(10, 3),
IX(9, 1),
V(5, 1),
IV(4, 1),
I(1, 3);
public final int value;
public final String symbol = name();
public final int maxArity;
private Digit(int value, int maxArity) {
this.value = value;
this.maxArity = maxArity;
}
}
private static final Digit[] DIGITS = Digit.values();
public static String of(int number) {
if (number < 1 || 3999 < number) {
throw new IllegalArgumentException(String.format(
"Roman numbers are only defined for numbers between 1 and 3999 (%d was given)",
number
));
}
StringBuilder sb = new StringBuilder();
for (Digit digit : DIGITS) {
int value = digit.value;
String symbol = digit.symbol;
while (number >= value) {
sb.append(symbol);
number -= value;
}
}
return sb.toString();
}
public static int parse(String roman) {
if (roman.isEmpty()) {
throw new NumberFormatException("The empty string does not comprise a valid Roman number");
}
int number = 0;
int offset = 0;
for (Digit digit : DIGITS) {
int value = digit.value;
int maxArity = digit.maxArity;
String symbol = digit.symbol;
for (int i = 0; i < maxArity && roman.startsWith(symbol, offset); i++) {
number += value;
offset += symbol.length();
}
}
if (offset != roman.length()) {
throw new NumberFormatException(String.format(
"The string '%s' does not comprise a valid Roman number",
roman
));
}
return number;
}
/** TESTS */
public static void main(String[] args) {
/* Demonstrating round-trip for all possible inputs. */
for (int number = 1; number <= 3999; number++) {
String roman = of(number);
int parsed = parse(roman);
if (parsed != number) {
System.err.format(
"ERROR: number: %d, roman: %s, parsed: %d\n",
number,
roman,
parsed
);
}
}
/* Some illegal inputs. */
int[] illegalNumbers = { -1, 0, 4000, 4001 };
for (int illegalNumber : illegalNumbers) {
try {
of(illegalNumber);
System.err.format(
"ERROR: Expected failure on number %d\n",
illegalNumber
);
} catch (IllegalArgumentException e) {
// Failed as expected.
}
}
String[] illegalRomans = { "MMMM", "CDCD", "IM", "T", "", "VV", "DM" };
for (String illegalRoman : illegalRomans) {
try {
parse(illegalRoman);
System.err.format(
"ERROR: Expected failure on roman %s\n",
illegalRoman
);
} catch (NumberFormatException e) {
// Failed as expected.
}
}
}
}
textView2.setText(String.format("%.2f", result));
and
DecimalFormat form = new DecimalFormat("0.00");
textView2.setText(form.format(result) );
...cause "NumberFormatException" error in locale for Europe because it sets result as comma instead of point decimal - error occurs when textView is added to number in editText. Both solutions are working excellent in locale US and UK.
for the plugins that doesn't use fn namespace (for example pnotify), this works:
if($.pluginname) {
alert("plugin loaded");
} else {
alert("plugin not loaded");
}
This doesn't work:
if($.fn.pluginname)
You can use several g++ commands and then link, but the easiest is to use a traditional Makefile or some other build system: like Scons (which are often easier to set up than Makefiles).
As all the other correct answers says, die
and exit
are identical/aliases.
Although I have a personal convention that when I want to end the execution of a script when it is expected and desired, I use exit;
. And when I need to end the execution due to some problems (couldn't connect to db, can't write to file etc.), I use die("Something went wrong.");
to "kill" the script.
When I use exit:
header( "Location: http://www.example.com/" ); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit; // I would like to end now.
When I use die:
$data = file_get_contents( "file.txt" );
if( $data === false ) {
die( "Failure." ); // I don't want to end, but I can't continue. Die, script! Die!
}
do_something_important( $data );
This way, when I see exit
at some point in my code, I know that at this point I want to exit because the logic ends here.
When I see die
, I know that I'd like to continue execution, but I can't or shouldn't due to error in previous execution.
Of course this only works when working on a project alone. When there is more people nobody will prevent them to use die
or exit
where it does not fit my conventions...
Select
A.maskid
, A.maskname
, A.schoolid
, B.schoolname
, STUFF((
SELECT ',' + T.maskdetail
FROM dbo.maskdetails T
WHERE A.maskid = T.maskid
FOR XML PATH('')), 1, 1, '') as maskdetail
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid
Group by A.maskid
, A.maskname
, A.schoolid
, B.schoolname
Here is a complete solution with application-json
:
// Input values will be grabbed by ID
<input id="loginEmail" type="text" name="email" placeholder="Email">
<input id="loginPassword" type="password" name="password" placeholder="Password">
// return stops normal action and runs login()
<button onclick="return login()">Submit</button>
<script>
function login() {
// Form fields, see IDs above
const params = {
email: document.querySelector('#loginEmail').value,
password: document.querySelector('#loginPassword').value
}
const http = new XMLHttpRequest()
http.open('POST', '/login')
http.setRequestHeader('Content-type', 'application/json')
http.send(JSON.stringify(params)) // Make sure to stringify
http.onload = function() {
// Do whatever with response
alert(http.responseText)
}
}
</script>
Ensure that your Backend API can parse JSON.
For example, in Express JS:
import bodyParser from 'body-parser'
app.use(bodyParser.json())