Arrays in Java have a fixed length that cannot be changed. So Java provides classes that allow you to maintain lists of variable length.
Generally, there is the List<T>
interface, which represents a list of instances of the class T
. The easiest and most widely used implementation is the ArrayList
. Here is an example:
List<String> words = new ArrayList<String>();
words.add("Hello");
words.add("World");
words.add("!");
List.add()
simply appends an element to the list and you can get the size of a list using List.size()
.
To connect to a new server, you click on home + add new connection. Put IP or webserver URL in new connection.
I was getting this same error and spent a day and a half trying to find a solution. Naomi's answer lead me to the solution I needed.
My input (type=button) had an attribute name
that was identical to a function name that was being called by the onClick event. Once I changed the attribute name
everything worked.
<input type="button" name="clearEmployer" onClick="clearEmployer();">
changed to:
<input type="button" name="clearEmployerBtn" onClick="clearEmployer();">
You can check detail of error by running this command
sudo service mongod status
if error is something like this
simply running this will resolve your issue
rm /tmp/mongodb-27017.sock
Also, if all you are trying to do is break up the main.go file into multiple files, then just name the other files "package main" as long as you only define the main function in one of those files, you are good to go.
This can be achieved with the stat module to skip the task when file exists.
- hosts: servers
tasks:
- name: Ansible check file exists.
stat:
path: /etc/issue
register: p
- debug:
msg: "File exists..."
when: p.stat.exists
- debug:
msg: "File not found"
when: p.stat.exists == False
For JavaFx based applications.
//returns System Clipboard
final Clipboard clipboard = Clipboard.getSystemClipboard();
// ClipboardContent provides flexibility to store data in different formats
final ClipboardContent content = new ClipboardContent();
content.putString("Some text");
content.putHtml("<b>Some</b> text");
//this will be replaced by previous putString
content.putString("Some different text");
//set the content to clipboard
clipboard.setContent(content);
// validate before retrieving it
if(clipboard.hasContent(DataFormat.HTML)){
System.out.println(clipboard.getHtml());
}
if(clipboard.hasString()){
System.out.println(clipboard.getString());
}
ClipboardContent can save multiple data in several data formats like(html,url,plain text,image).
For more information see official documentation
The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*
. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*
.
So if you want to remove all the privileges and start totally from scratch do the following:
Revoke all privileges on database level:
REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';
Drop the user 'phpmyadmin'@'localhost'
DROP USER 'phpmyadmin'@'localhost';
Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.
To give you a bit background on what described above: as soon as you create a user the mysql.user
table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'
. If you do a show grants for 'phpmyadmin'@'localhost';
you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL
to this user on database level, this will be stored in the table mysql.db
. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb';
you will see a 'Y'
on every priv.
Above described shows the scenario you have on your db at the present. So having a user that only has USAGE
privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS;
he has no other privileges.
What I do in my Asp Net Core Api applications it is to create a class that extends from ObjectResult and provide many constructors to customize the content and the status code. Then all my Controller actions use one of the costructors as appropiate. You can take a look at my implementation at: https://github.com/melardev/AspNetCoreApiPaginatedCrud
and
https://github.com/melardev/ApiAspCoreEcommerce
here is how the class looks like(go to my repo for full code):
public class StatusCodeAndDtoWrapper : ObjectResult
{
public StatusCodeAndDtoWrapper(AppResponse dto, int statusCode = 200) : base(dto)
{
StatusCode = statusCode;
}
private StatusCodeAndDtoWrapper(AppResponse dto, int statusCode, string message) : base(dto)
{
StatusCode = statusCode;
if (dto.FullMessages == null)
dto.FullMessages = new List<string>(1);
dto.FullMessages.Add(message);
}
private StatusCodeAndDtoWrapper(AppResponse dto, int statusCode, ICollection<string> messages) : base(dto)
{
StatusCode = statusCode;
dto.FullMessages = messages;
}
}
Notice the base(dto) you replace dto by your object and you should be good to go.
As mentioned in the comments, starting with Ubuntu 18.04 and Linux Mint Tara you need to first sudo apt install qemu-kvm
.
To check the ownership of /dev/kvm
use
ls -al /dev/kvm
The user was root
, the group kvm
. To check which users are in the kvm
group, use
grep kvm /etc/group
This returned
kvm:x:some_number:
on my system: as there is nothing rightwards of the final :
, there are no users in the kvm
group.
To add your user to the kvm group, you could use
sudo adduser $USER kvm
which adds the user to the group, and check once again with grep kvm /etc/group
.
As mentioned by @marcolz, the command newgrp kvm
should change the group membership live for you. If that did not work, @Knossos mentioned that you might want to log out and back in (or restart), for the permissions to take effect. Or do as @nmirceac mentioned and re-login in the same shell via su - $USER
.
The obvious answer is to use one of the special forms of parameter expansion:
: ${STATE?"Need to set STATE"}
: ${DEST:?"Need to set DEST non-empty"}
Or, better (see section on 'Position of double quotes' below):
: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"
The first variant (using just ?
) requires STATE to be set, but STATE="" (an empty string) is OK — not exactly what you want, but the alternative and older notation.
The second variant (using :?
) requires DEST to be set and non-empty.
If you supply no message, the shell provides a default message.
The ${var?}
construct is portable back to Version 7 UNIX and the Bourne Shell (1978 or thereabouts). The ${var:?}
construct is slightly more recent: I think it was in System III UNIX circa 1981, but it may have been in PWB UNIX before that. It is therefore in the Korn Shell, and in the POSIX shells, including specifically Bash.
It is usually documented in the shell's man page in a section called Parameter Expansion. For example, the bash
manual says:
${parameter:?word}
Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.
I should probably add that the colon command simply has its arguments evaluated and then succeeds. It is the original shell comment notation (before '#
' to end of line). For a long time, Bourne shell scripts had a colon as the first character. The C Shell would read a script and use the first character to determine whether it was for the C Shell (a '#
' hash) or the Bourne shell (a ':
' colon). Then the kernel got in on the act and added support for '#!/path/to/program
' and the Bourne shell got '#
' comments, and the colon convention went by the wayside. But if you come across a script that starts with a colon, now you will know why.
Any thoughts on this discussion? https://github.com/koalaman/shellcheck/issues/380#issuecomment-145872749
The gist of the discussion is:
… However, when I
shellcheck
it (with version 0.4.1), I get this message:In script.sh line 13: : ${FOO:?"The environment variable 'FOO' must be set and non-empty"} ^-- SC2086: Double quote to prevent globbing and word splitting.
Any advice on what I should do in this case?
The short answer is "do as shellcheck
suggests":
: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"
To illustrate why, study the following. Note that the :
command doesn't echo its arguments (but the shell does evaluate the arguments). We want to see the arguments, so the code below uses printf "%s\n"
in place of :
.
$ mkdir junk
$ cd junk
$ > abc
$ > def
$ > ghi
$
$ x="*"
$ printf "%s\n" ${x:?You must set x} # Careless; not recommended
abc
def
ghi
$ unset x
$ printf "%s\n" ${x:?You must set x} # Careless; not recommended
bash: x: You must set x
$ printf "%s\n" "${x:?You must set x}" # Careful: should be used
bash: x: You must set x
$ x="*"
$ printf "%s\n" "${x:?You must set x}" # Careful: should be used
*
$ printf "%s\n" ${x:?"You must set x"} # Not quite careful enough
abc
def
ghi
$ x=
$ printf "%s\n" ${x:?"You must set x"} # Not quite careful enough
bash: x: You must set x
$ unset x
$ printf "%s\n" ${x:?"You must set x"} # Not quite careful enough
bash: x: You must set x
$
Note how the value in $x
is expanded to first *
and then a list of file names when the overall expression is not in double quotes. This is what shellcheck
is recommending should be fixed. I have not verified that it doesn't object to the form where the expression is enclosed in double quotes, but it is a reasonable assumption that it would be OK.
Also check complete.cases
:
> final[complete.cases(final), ]
gene hsap mmul mmus rnor cfam
2 ENSG00000199674 0 2 2 2 2
6 ENSG00000221312 0 1 2 3 2
na.omit
is nicer for just removing all NA
's. complete.cases
allows partial selection by including only certain columns of the dataframe:
> final[complete.cases(final[ , 5:6]),]
gene hsap mmul mmus rnor cfam
2 ENSG00000199674 0 2 2 2 2
4 ENSG00000207604 0 NA NA 1 2
6 ENSG00000221312 0 1 2 3 2
Your solution can't work. If you insist on using is.na
, then you have to do something like:
> final[rowSums(is.na(final[ , 5:6])) == 0, ]
gene hsap mmul mmus rnor cfam
2 ENSG00000199674 0 2 2 2 2
4 ENSG00000207604 0 NA NA 1 2
6 ENSG00000221312 0 1 2 3 2
but using complete.cases
is quite a lot more clear, and faster.
You could use String.prototype.indexOf
to accomplish that. Try something like this:
$('.type').keyup(function() {_x000D_
var v = $(this).val();_x000D_
if (v.indexOf('> <') !== -1) {_x000D_
console.log('contains > <');_x000D_
}_x000D_
console.log(v);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea class="type"></textarea>
_x000D_
Update
Modern browsers also have a String.prototype.includes
method.
You can use the the ResultSetMetaData (http://java.sun.com/javase/6/docs/api/java/sql/ResultSetMetaData.html) object for that, like this:
ResultSet rs = stmt.executeQuery("SELECT * FROM table");
ResultSetMetaData rsmd = rs.getMetaData();
String firstColumnName = rsmd.getColumnName(1);
The trim from jQuery is convenient if you are already using that framework.
$.trim(' your string ');
I tend to use jQuery often, so trimming strings with it is natural for me. But it's possible that there is backlash against jQuery out there? :)
s[i:j:k]
is, according to the documentation, "slice of s from i to j with step k". When i
and j
are absent, the whole sequence is assumed and thus s[::k]
means "every k-th item".
First, let's initialize a list:
>>> s = range(20)
>>> s
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Let's take every 3rd item from s
:
>>> s[::3]
[0, 3, 6, 9, 12, 15, 18]
Let's take every 3rd item from s[2:]
:
>>> s[2:]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> s[2::3]
[2, 5, 8, 11, 14, 17]
Let's take every 3rd item from s[5:12]
:
>>> s[5:12]
[5, 6, 7, 8, 9, 10, 11]
>>> s[5:12:3]
[5, 8, 11]
Let's take every 3rd item from s[:10]
:
>>> s[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> s[:10:3]
[0, 3, 6, 9]
Sub CheckValues1()
Dim rwIndex As Integer
Dim colIndex As Integer
For rwIndex = 1 To 10
For colIndex = 1 To 5
If Cells(rwIndex, colIndex).Value <> 0 Then _
Cells(rwIndex, colIndex).Value = 0
Next colIndex
Next rwIndex
End Sub
Found this snippet on http://www.java2s.com/Code/VBA-Excel-Access-Word/Excel/Checksvaluesinarange10rowsby5columns.htm It seems to be quite useful as a function to illustrate the means to check values in cells in an ordered fashion.
Just imagine it as being a 2d Array of sorts and apply the same logic to loop through cells.
The below options works for me:
-Dcom.sun.management.jmxremote=true
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.rmi.port=9010
-Dcom.sun.management.jmxremote.local.only=false
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Djava.rmi.server.hostname={host name}
and remember to open 9010 port in the server
sudo ufw allow 9010/udp
sudo ufw allow 9010/tcp
sudo ufw reload
As of jquery ui version 1.8.16 below is how I got it working.
$('#element').dialog({
buttons: {
"Save": {
text: 'Save',
class: 'btn primary',
click: function () {
// do stuff
}
}
});
Key Points:
ngModel in angular2 is valid only if the FormsModule is available as a part of your AppModule.
ng-model
is syntatically wrong.
So, to fix your error.
Step 1: Importing FormsModule
import {FormsModule} from '@angular/forms'
Step 2: Add it to imports array of your AppModule as
imports :[ ... , FormsModule ]
Step 3: Change ng-model
as ngModel with banana boxes as
<input id="name" type="text" [(ngModel)]="name" />
Note: Also, you can handle the two way databinding separately as well as below
<input id="name" type="text" [ngModel]="name" (ngModelChange)="valueChange($event)"/>
valueChange(value){
}
a) The year is 365.242199 days.
b) If every year was 365 days, in 100 years we would lose 24.2199 days. That's why we add 24 days per century (every 4 years EXCEPT when divisible by 100)
c) But still we lose 0.21299 days/century. So in 4 centuries we lose 0.8796 days. That's why we add 1 day per 4 centuries (every fourth century we DO count a leap year).
d) But that means we lose -0.1204 days (we go forward) per quadricentennial (4 centuries). So in 8 quadricentennial (3200 years) we DO NOT count a leap year.
e) But that means we lose 0.0368 days per 3200 years. So in 24x3200 years (=76800years) we lose 0.8832 days. That's why we DO count a leap year.
and so on... (by then we will have destroyed the planet, so it doesn't matter)
What I cannot understand though, is why we don't count a leap year every 500 years instead of 400. In that way we would converge more rapidly to the correct time (we would lose 2.3 hours/500 years).
Just a simple line of code in the head section can refresh the page
<meta http-equiv="refresh" content="30">
although its not a javascript function, its the simplest way to accomplish the above task hopefully.
Use the command as
java -classpath ".;C:\MyLibs\a\*;D:\MyLibs\b\*" <your-class-name>
The above command will set the mentioned paths to classpath only once for executing the class named TestClass.
If you want to execute more then one classes, then you can follow this
set classpath=".;C:\MyLibs\a\*;D:\MyLibs\b\*"
After this you can execute as many classes as you want just by simply typing
java <your-class-name>
The above command will work till you close the command prompt. But after closing the command prompt, if you will reopen the command prompt and try to execute some classes, then you have to again set the classpath with the help of any of the above two mentioned methods.(First method for executing one class and second one for executing more classes)
If you want to set the classpth only once so that it could work for everytime, then do as follows
1. Right click on "My Computer" icon
2. Go to the "properties"
3. Go to the "Advanced System Settings" or "Advance Settings"
4. Go to the "Environment Variable"
5. Create a new variable at the user variable by giving the information as below
a. Variable Name- classpath
b. Variable Value- .;C:\program files\jdk 1.6.0\bin;C:\MyLibs\a\';C:\MyLibs\b\*
6.Apply this and you are done.
Remember this will work every time. You don't need to explicitly set the classpath again and again.
NOTE: If you want to add some other libs after some day, then don't forget to add a semi-colon at the end of the "variable-value" of the "Environment Variable" and then type the path of your new libs after the semi-colon. Because semi-colon separates the paths of different directories.
Hope this will help you.
The short version is, call stmt.setFetchSize(50);
and conn.setAutoCommit(false);
to avoid reading the entire ResultSet
into memory.
Here's what the docs say:
Getting results based on a cursor
By default the driver collects all the results for the query at once. This can be inconvenient for large data sets so the JDBC driver provides a means of basing a ResultSet on a database cursor and only fetching a small number of rows.
A small number of rows are cached on the client side of the connection and when exhausted the next block of rows is retrieved by repositioning the cursor.
Note:
Cursor based ResultSets cannot be used in all situations. There a number of restrictions which will make the driver silently fall back to fetching the whole ResultSet at once.
The connection to the server must be using the V3 protocol. This is the default for (and is only supported by) server versions 7.4 and later.-
The Connection must not be in autocommit mode. The backend closes cursors at the end of transactions, so in autocommit mode the backend will have closed the cursor before anything can be fetched from it.-
The Statement must be created with a ResultSet type of ResultSet.TYPE_FORWARD_ONLY. This is the default, so no code will need to be rewritten to take advantage of this, but it also means that you cannot scroll backwards or otherwise jump around in the ResultSet.-
The query given must be a single statement, not multiple statements strung together with semicolons.
Example 5.2. Setting fetch size to turn cursors on and off.
Changing code to cursor mode is as simple as setting the fetch size of the Statement to the appropriate size. Setting the fetch size back to 0 will cause all rows to be cached (the default behaviour).
// make sure autocommit is off
conn.setAutoCommit(false);
Statement st = conn.createStatement();
// Turn use of the cursor on.
st.setFetchSize(50);
ResultSet rs = st.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
System.out.print("a row was returned.");
}
rs.close();
// Turn the cursor off.
st.setFetchSize(0);
rs = st.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
System.out.print("many rows were returned.");
}
rs.close();
// Close the statement.
st.close();
This could be useful when implementing multiprocessing and parallel/ distributed computing in Python.
YouTube tutorial on using techila package
Techila is a distributed computing middleware, which integrates directly with Python using the techila package. The peach function in the package can be useful in parallelizing loop structures. (Following code snippet is from the Techila Community Forums)
techila.peach(funcname = 'theheavyalgorithm', # Function that will be called on the compute nodes/ Workers
files = 'theheavyalgorithm.py', # Python-file that will be sourced on Workers
jobs = jobcount # Number of Jobs in the Project
)
If you want to configure a bean before your application is running fully, you can use @Autowired
:
@Autowired
private void configureBean(MyBean: bean) {
bean.setConfiguration(myConfiguration);
}
To find all the matching strings, use String's scan
method.
str = "A 54mpl3 string w1th 7 numb3rs scatter36 ar0und"
str.scan(/\d+/)
#=> ["54", "3", "1", "7", "3", "36", "0"]
If you want, MatchData
, which is the type of the object returned by the Regexp match
method, use:
str.to_enum(:scan, /\d+/).map { Regexp.last_match }
#=> [#<MatchData "54">, #<MatchData "3">, #<MatchData "1">, #<MatchData "7">, #<MatchData "3">, #<MatchData "36">, #<MatchData "0">]
The benefit of using MatchData
is that you can use methods like offset
:
match_datas = str.to_enum(:scan, /\d+/).map { Regexp.last_match }
match_datas[0].offset(0)
#=> [2, 4]
match_datas[1].offset(0)
#=> [7, 8]
See these questions if you'd like to know more:
Reading about special variables $&
, $'
, $1
, $2
in Ruby will be helpful too.
Since react-router v5.1 with hooks:
import { useParams } from 'react-router';
export default function DetailsPage() {
const { id } = useParams();
}
getdate()
is the direct equivalent, but you should always use UTC datetimes
getutcdate()
whether your app operates across timezones or not - otherwise you run the risk of screwing up date math at the spring/fall transitions
What? Use file open, seek position then stream erase line using null.
Gotch it? Simple,stream,no array that eat memory,fast.
This work on vb.. Example search line culture=id where culture are namevalue and id are value and we want to change it to culture=en
Fileopen(1, "text.ini")
dim line as string
dim currentpos as long
while true
line = lineinput(1)
dim namevalue() as string = split(line, "=")
if namevalue(0) = "line name value that i want to edit" then
currentpos = seek(1)
fileclose()
dim fs as filestream("test.ini", filemode.open)
dim sw as streamwriter(fs)
fs.seek(currentpos, seekorigin.begin)
sw.write(null)
sw.write(namevalue + "=" + newvalue)
sw.close()
fs.close()
exit while
end if
msgbox("org ternate jua bisa, no line found")
end while
that's all..use #d
In most of the general cases 'Length' and 'Count' are used.
Array:
int[] myArray = new int[size];
int noOfElements = myArray.Length;
Typed List Array:
List <int> myArray = new List<int>();
int noOfElements = myArray.Count;
You should look into using the MAC address on the network card (if it exists). Those are usually unique but can be fabricated. I've used software that generates its license file based on your network adapter MAC address, so it's considered a fairly reliable way to distinguish between computers.
I think the main complaints about sqlite scaling is:
HashMap
is unordered per the second line of the documentation:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
Perhaps you can do as aix suggests and use a LinkedHashMap
, or another ordered collection. This link can help you find the most appropriate collection to use.
Actually, depth first (or indeed breadth first) search isn't quite enough. You need a sightly more complex algorithm.
For instance, suppose there is graph with nodes {a,b,c,d} and edges {(a,b),(b,c),(b,d),(d,c)} where an edge (x,y) is an edge from x to y. (looks something like this, with all edges directed downwards.)
(a)
|
|
(b)
/ \
(d) |
| |
\ /
(c)
Then doing depth first search may visit node (a), then (b), then (c), then backtrack to (b), then visit (d), and finally visit (c) again and conclude there is a cycle -- when there isn't. A similar thing happens with breadth first.
What you need to do is keep track of which nodes your in the middle of visiting. In the example above, when the algorithm reaches (d) it has finished visiting (c) but not (a) or (b). So revisiting a finished node is fine, but visiting an unfinished node means you have a cycle. The usual way to do this is colour each node white(not yet visited), grey(visiting descendants) or black(finished visiting).
here is some pseudo code!
define visit(node n):
if n.colour == grey: //if we're still visiting this node or its descendants
throw exception("Cycle found")
n.colour = grey //to indicate this node is being visited
for node child in n.children():
if child.colour == white: //if the child is unexplored
visit(child)
n.colour = black //to show we're done visiting this node
return
then running visit(root_node) will throw an exception if and only if there is a cycle (initially all nodes should be white).
I have created the following, and it's working on my system. Please try this:
package.json:
{
"name": "test app",
"version": "1.0.0",
"scripts": {
"start": "node script1.js"
}
}
script1.js:
console.log('testing')
From your command line run the following command:
npm start
Additional use case
My package.json file has generally the following scripts, which enable me to watch my files for typescript, sass compilations and running a server as well.
"scripts": {
"start": "concurrently \"sass --watch ./style/sass:./style/css\" \"npm run tsc:w\" \"npm run lite\" ",
"tsc": "tsc",
"tsc:w": "tsc -w",
"lite": "lite-server",
"typings": "typings",
"postinstall": "typings install"
}
The command is called :saveas
, but unfortunately it will not delete your old file, you'll have to do that manually. see :help saveas
for more info.
EDIT:
Most vim installations have an integrated file explorer, which you can use for such operations. Try :Explore
in command mode (I would actually map that to a function key, it's very handy). You can rename files with R
or delete them with D
, for example. But pressing <F1>
in the explorer will give you a better overview.
The aliases you give are for the output of the query - they are not available within the query itself.
You can either repeat the expression:
SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast
FROM users
WHERE CONCAT(firstname, ' ', lastname) = "Bob Michael Jones"
or wrap the query
SELECT * FROM (
SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast
FROM users) base
WHERE firstLast = "Bob Michael Jones"
<textarea style="resize:none" name="name" cols="num" rows="num"></textarea>
Just an example
If you could show the actual page, we, possibly, could help you better.
If you want to trigger the button only after the iframe is loaded, you might want to check if it has been loaded or use the iframe.onload:
<iframe .... onload='buttonWhatever(); '></iframe>
<script type="text/javascript">
function buttonWhatever() {
$("#<%=Button1.ClientID%>").click(function (event) {
$('#<%=TextBox1.ClientID%>').change(function () {
$('#various3').attr('href', $(this).val());
});
$("#<%=Button2.ClientID%>").click();
});
function showStickySuccessToast() {
$().toastmessage('showToast', {
text: 'Finished Processing!',
sticky: false,
position: 'middle-center',
type: 'success',
closeText: '',
close: function () { }
});
}
}
</script>
you can try checking out your fields as you are rendering email field which is not available in your ajax
$.ajax({_x000D_
url: "url",_x000D_
type: 'GET',_x000D_
success: function(data) {_x000D_
var new_data = {_x000D_
"data": data_x000D_
};_x000D_
console.log(new_data);_x000D_
}_x000D_
});
_x000D_
hai sir
There is one event which is default associate with any webcontrol. For example, in case of Button click event, in case of Check box CheckChangedEvent is there. So in case of AutoPostBack true these events are called by default and event handle at server sid
Angularjs Dependency Injection framework is responsible for injecting the dependancies of you app module to your controllers. This is possible through its injector.
You need to first identify the ng-app and get the associated injector. The below query works to find your ng-app in the DOM and retrieve the injector.
angular.element('*[ng-app]').injector()
In chrome, however, you can point to target ng-app as shown below. and use the $0
hack and issue angular.element($0).injector()
Once you have the injector, get any dependency injected service as below
injector = angular.element($0).injector();
injector.get('$mdToast');
cutycapt saves webpages to most image formats(jpg,png..) download it from your synaptic, it works much better than wkhtmltopdf
Try:
var myMappings = {
"Name": "10%",
"Phone": "10%",
"Address": "50%",
"Zip": "10%",
"Comments": "20%"
}
// Access is like this
myMappings["Name"] // Returns "10%"
myMappings.Name // The same thing as above
// To loop through...
for(var title in myMappings) {
// Do whatever with myMappings[title]
}
Other answers are correct -- whether a character is invisible or not depends on what font you use. This seems to be a pretty good list to me of characters that are truly invisible (not even space). It contains some chars that the other lists are missing.
'\u2060', // Word Joiner
'\u2061', // FUNCTION APPLICATION
'\u2062', // INVISIBLE TIMES
'\u2063', // INVISIBLE SEPARATOR
'\u2064', // INVISIBLE PLUS
'\u2066', // LEFT - TO - RIGHT ISOLATE
'\u2067', // RIGHT - TO - LEFT ISOLATE
'\u2068', // FIRST STRONG ISOLATE
'\u2069', // POP DIRECTIONAL ISOLATE
'\u206A', // INHIBIT SYMMETRIC SWAPPING
'\u206B', // ACTIVATE SYMMETRIC SWAPPING
'\u206C', // INHIBIT ARABIC FORM SHAPING
'\u206D', // ACTIVATE ARABIC FORM SHAPING
'\u206E', // NATIONAL DIGIT SHAPES
'\u206F', // NOMINAL DIGIT SHAPES
'\u200B', // Zero-Width Space
'\u200C', // Zero Width Non-Joiner
'\u200D', // Zero Width Joiner
'\u200E', // Left-To-Right Mark
'\u200F', // Right-To-Left Mark
'\u061C', // Arabic Letter Mark
'\uFEFF', // Byte Order Mark
'\u180E', // Mongolian Vowel Separator
'\u00AD' // soft-hyphen
The idea of MD5 is that is a one-way hashing, so it can't be once the original value has been passed through the hashing algorithm (if at all).
You could (potentially) create a database table with a pairing of the original and the MD5 values but I guess that's highly impractical and poses a major security risk.
Do you want something as simple like:
#include <unistd.h>
sleep(3);//sleeps for 3 second
It may be more useful to use a http client library like such as this
There are more things like access denied , document moved etc to handle when dealing with http.
(though, it is unlikely in this case)
In your code you are using min
and not minlength
. Please also notice that this will not validate if a number is > 0 but its length.
Use [] instead of () as below example.
SqlDataAdapter adapter = new SqlDataAdapter(sql, ConfigurationManager.ConnectionStrings["FADB_ConnectionString"].ConnectionString);
DataTable data = new DataTable();
DataSet ds = new DataSet();
There are many ways to perform your task, but the most elegant are, I believe, using css. Here are basic steps
This works pretty well if there a few divs, since more elements you want to toggle, more css rules should be written. Here is more general solution, binding action, base on following steps: 1. find all elements using some selector (usually it looks like '.menu-container .menu-item') 2. find one of found elements, which is current visible, hide it 3. make visible another element, the one you desire to be visible under new circumstances.
javascript it a rather timtoady language )
Since Spring 3.0 you can use @Primary
annotation. As per documentation:
Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the element's primary attribute in Spring XML.
You should use it on Bean definition like this:
@Bean
@Primary
public ExampleBean exampleBean(@Autowired EntityManager em) {
return new ExampleBeanImpl(em);
}
or like this:
@Primary
@Service
public class ExampleService implements BaseServive {
}
If you are calling a RESTful service from a Service Provider (e.g Facebook, Twitter), you can do it with any flavour of your choice:
If you don't want to use external libraries, you can use java.net.HttpURLConnection
or javax.net.ssl.HttpsURLConnection
(for SSL), but that is call encapsulated in a Factory type pattern in java.net.URLConnection
.
To receive the result, you will have to connection.getInputStream()
which returns you an InputStream
. You will then have to convert your input stream to string and parse the string into it's representative object (e.g. XML, JSON, etc).
Alternatively, Apache HttpClient (version 4 is the latest). It's more stable and robust than java's default URLConnection
and it supports most (if not all) HTTP protocol (as well as it can be set to Strict mode). Your response will still be in InputStream
and you can use it as mentioned above.
Documentation on HttpClient: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html
add {3,5}
to your expression which means length between 3 to 5
/^([a-zA-Z0-9_-]){3,5}$/
If you don’t know the location or version of installed Oracle product, you can find it from the inventory which is usually recorded in /etc/oraInst.loc
> cat /etc/oraInst.loc
inventory_loc=/export/oracle/oraInventory **--> Inventory location**
inst_group=dba
> cd /export/oracle/oraInventory
> cd ContentsXML
Here look for a file inventory.xml
> cat inventory.xml
<?xml version="1.0" standalone="yes" ?>
<!-- Copyright (c) 1999, 2010, Oracle. All rights reserved. -->
<!-- Do not modify the contents of this file by hand. -->
<INVENTORY>
<VERSION_INFO>
<SAVED_WITH>11.2.0.2.0</SAVED_WITH>
<MINIMUM_VER>2.1.0.6.0</MINIMUM_VER>
</VERSION_INFO>
<HOME_LIST>
<HOME NAME="OraDB_11G" LOC="/export/oracle/product/11.2.0.2" TYPE="O" IDX="2">
Once you know the install location
export ORACLE_HOME=full path to install location
export ORACLE_HOME=/export/oracle/product/11.2.0.2
export PATH=$ORACLE_HOME/bin:$PATH
A simple "sqlplus" will give you the version of the client installed.
> sqlplus
SQL*Plus: Release 11.2.0.1.0 Production on Fri Mar 23 14:51:09 2012
Copyright (c) 1982, 2010, Oracle. All rights reserved.
Enter user-name:
In the above example, the version of Oracle client is 11.2.0.1
Registry location variable in windows is INST_LOC
Start > Run > regedit > HKLM > Software > Oracle
Check the Inst_loc entry value which will be the software installed location.
You can use command prompt or you can navigate/explore to the oracle home location and then cd to bin directory to lauch sqlplus which will give you the client version information.
It is because you haven't qualified Cells(1, 1)
with a worksheet object, and the same holds true for Cells(10, 2)
. For the code to work, it should look something like this:
Dim ws As Worksheet
Set ws = Sheets("SheetName")
Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents
Alternately:
With Sheets("SheetName")
Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With
EDIT: The Range object will inherit the worksheet from the Cells objects when the code is run from a standard module or userform. If you are running the code from a worksheet code module, you will need to qualify Range
also, like so:
ws.Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents
or
With Sheets("SheetName")
.Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With
Based on Jakub's answer you can configure the following git aliases for convenience:
accept-ours = "!f() { git checkout --ours -- \"${@:-.}\"; git add -u \"${@:-.}\"; }; f"
accept-theirs = "!f() { git checkout --theirs -- \"${@:-.}\"; git add -u \"${@:-.}\"; }; f"
They optionally take one or several paths of files to resolve and default to resolving everything under the current directory if none are given.
Add them to the [alias]
section of your ~/.gitconfig
or run
git config --global alias.accept-ours '!f() { git checkout --ours -- "${@:-.}"; git add -u "${@:-.}"; }; f'
git config --global alias.accept-theirs '!f() { git checkout --theirs -- "${@:-.}"; git add -u "${@:-.}"; }; f'
Thanks to Chris for the starting point here is a improvement which addresses the resizing of the images used, the use of first-child is just to indicate you could use a variety of icons within the list to give you full control.
ul li:first-child:before {
content: '';
display: inline-block;
height: 25px;
width: 35px;
background-image: url('../images/Money.png');
background-size: contain;
background-repeat: no-repeat;
margin-left: -35px;
}
This seems to work well in all modern browsers, you will need to ensure that the width and the negative margin left have the same value, hope it helps
Thanks to @RubberDuck's comment and @Emil's answer I was able to figure out what the problem was. The IDs of most elements in my XML file were exactly the same. So, I renamed each and every one of them. Also, my XML file contained capital letters. The filename should be in [a-z0-9_] so I renamed my files too and the problem was solved.
Add below alias to your ~/.bash_profile
, then run, source ~/.bash_profile
; now anytime you need to see the updated files in the last commit, run, showfiles
from your git repository.
alias showfiles='git show --pretty="format:" --name-only'
You'd use font-weight: bold
.
Do you want to make the entire document bold? Or just parts of it?
$ DOCS="/cygdrive/c/Users/my\ dir/Documents"
Here's your first problem. This puts an actual backslash character into $DOCS
, as you can see by running this command:
$ echo "$DOCS"
/cygdrive/c/Users/my\ `
When defining DOCS
, you do need to escape the space character. You can quote the string (using either single or double quotes) or you can escape just the space character with a backslash. You can't do both. (On most Unix-like systems, you can have a backslash in a file or directory name, though it's not a good idea. On Cygwin or Windows, \
is a directory delimiter. But I'm going to assume the actual name of the directory is my dir
, not my\ dir
.)
$ cd $DOCS
This passes two arguments to cd
. The first is cygdrive/c/Users/my\
, and the second is dir/Documents
. It happens that cd
quietly ignores all but its first argument, which explains the error message:
-bash: cd: /cygdrive/c/Users/my\: No such file or directory
To set $DOCS
to the name of your Documents
directory, do any one of these:
$ DOCS="/cygdrive/c/Users/my dir/Documents"
$ DOCS='/cygdrive/c/Users/my dir/Documents'
$ DOCS=/cygdrive/c/Users/my\ dir/Documents
Once you've done that, to change to your Documents
directory, enclose the variable reference in double quotes (that's a good idea for any variable reference in bash, unless you're sure the value doesn't have any funny characters):
$ cd "$DOCS"
You might also consider giving that directory a name without any spaces in it -- though that can be hard to do in general on Windows.
If you know the index of the tab you want to select, you can do it like so:
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
TabLayout.Tab tab = tabLayout.getTabAt(someIndex);
tab.select();
This technique works even if you're using the TabLayout by itself without a ViewPager (which is atypical, and probably bad practice, but I've seen it done).
on this web http://quirksmode.org/css/css2/columns.html i found that easy way
<table>
<col style="background-color: #6374AB; color: #ffffff" />
<col span="2" style="background-color: #07B133; color: #ffffff;" />
<tr>..
This program is an efficient one. I have added one more check-in if to get the square root of a number and check is it divisible or not if it's then its not a prime number. this will solve all the problems efficiently.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T; // number of test cases
T = sc.nextInt();
long[] number = new long[T];
if(1<= T && T <= 30){
for(int i =0;i<T;i++){
number[i]=sc.nextInt(); // read all the numbers
}
for(int i =0;i<T;i++){
if(isPrime(number[i]))
System.out.println("Prime");
else
System.out.println("Not prime");
}
}
else
return;
}
// is prime or not
static boolean isPrime(long num){
if(num==1)
return false;
if(num <= 3)
return true;
if(num % 2 == 0 || num % 3 == 0 || num % (int)Math.sqrt(num) == 0)
return false;
for(int i=4;i<(int)Math.sqrt(num);i++){
if(num%i==0)
return false;
}
return true;
}
POJO : It is a java file(class) which doesn't extend or implement any other java file(class).
Bean: It is a java file(class) in which all variables are private, methods are public and appropriate getters and setters are used for accessing variables.
Normal class: It is a java file(class) which may consist of public/private/default/protected variables and which may or may not extend or implement another java file(class).
You can do this in pretty concise way using ResponseEntity
like this:
@GetMapping
ResponseEntity<Void> redirect() {
return ResponseEntity.status(HttpStatus.FOUND)
.location(URI.create("http://www.yahoo.com"))
.build();
}
Docs: https://www.timkay.com/solo/
solo is a very simple script (10 lines) that prevents a program from running more than one copy at a time. It is useful with cron to make sure that a job doesn't run before a previous one has finished.
Example
* * * * * solo -port=3801 ./job.pl blah blah
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();
}
Another approach for a delayed component:
Delayed.jsx
:
import React from 'react';
import PropTypes from 'prop-types';
class Delayed extends React.Component {
constructor(props) {
super(props);
this.state = {hidden : true};
}
componentDidMount() {
setTimeout(() => {
this.setState({hidden: false});
}, this.props.waitBeforeShow);
}
render() {
return this.state.hidden ? '' : this.props.children;
}
}
Delayed.propTypes = {
waitBeforeShow: PropTypes.number.isRequired
};
export default Delayed;
Usage:
import Delayed from '../Time/Delayed';
import React from 'react';
const myComp = props => (
<Delayed waitBeforeShow={500}>
<div>Some child</div>
</Delayed>
)
java.lang
does not contain a class called StringUtils
. Several third-party libs do, such as Apache Commons Lang or the Spring framework. Make sure you have the relevant jar in your project classpath and import the correct class.
So if I get it right, on click of a button, you want to open up a modal that lists the values entered by the users followed by submitting it.
For this, you first change your input type="submit"
to input type="button"
and add data-toggle="modal" data-target="#confirm-submit"
so that the modal gets triggered when you click on it:
<input type="button" name="btn" value="Submit" id="submitBtn" data-toggle="modal" data-target="#confirm-submit" class="btn btn-default" />
Next, the modal dialog:
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Confirm Submit
</div>
<div class="modal-body">
Are you sure you want to submit the following details?
<!-- We display the details entered by the user here -->
<table class="table">
<tr>
<th>Last Name</th>
<td id="lname"></td>
</tr>
<tr>
<th>First Name</th>
<td id="fname"></td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a href="#" id="submit" class="btn btn-success success">Submit</a>
</div>
</div>
</div>
</div>
Lastly, a little bit of jQuery:
$('#submitBtn').click(function() {
/* when the button in the form, display the entered values in the modal */
$('#lname').text($('#lastname').val());
$('#fname').text($('#firstname').val());
});
$('#submit').click(function(){
/* when the submit button in the modal is clicked, submit the form */
alert('submitting');
$('#formfield').submit();
});
You haven't specified what the function validateForm()
does, but based on this you should restrict your form from being submitted. Or you can run that function on the form's button #submitBtn
click and then load the modal after the validations have been checked.
Alternative solution is to modify your current Visual Studio installation in the Visual Studio Installer
Win+R %ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vs_installer.exe
adding the Blend for Visual Studio SDK for .NET
'Individual component' under 'SDKs, libraries, and frameworks':
after adding this component System.Windows.Interactivity
should appear in its regular location Add Reference/Assemblies/Extensions
.
It appears this would only work for VS2017 or earlier. For later versions, please refer to other answers.
from ..gen_py.lib import MyService
or
from main.gen_py.lib import MyService
Make sure you have a (at least empty) __init__.py
file on each directory.
Try this:
if [ $STATUS -ne 200 -a "$STRING" != "$VALUE" ]; then
The above solution for the JsonCreationConverter<T>
is all over the internet, but has a flaw that manifests itself in rare occasions. The new JsonReader created in the ReadJson method does not inherit any of the original reader's configuration values (Culture, DateParseHandling, DateTimeZoneHandling, FloatParseHandling, etc...). These values should be copied over before using the new JsonReader in serializer.Populate().
This is the best I could come up with to fix some of the problems with the above implementation, but I still think there are some things being overlooked:
Update I updated this to have a more explicit method that makes a copy of an existing reader. This just encapsulates the process of copying over individual JsonReader settings. Ideally this function would be maintained in the Newtonsoft library itself, but for now, you can use the following:
/// <summary>Creates a new reader for the specified jObject by copying the settings
/// from an existing reader.</summary>
/// <param name="reader">The reader whose settings should be copied.</param>
/// <param name="jToken">The jToken to create a new reader for.</param>
/// <returns>The new disposable reader.</returns>
public static JsonReader CopyReaderForObject(JsonReader reader, JToken jToken)
{
JsonReader jTokenReader = jToken.CreateReader();
jTokenReader.Culture = reader.Culture;
jTokenReader.DateFormatString = reader.DateFormatString;
jTokenReader.DateParseHandling = reader.DateParseHandling;
jTokenReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
jTokenReader.FloatParseHandling = reader.FloatParseHandling;
jTokenReader.MaxDepth = reader.MaxDepth;
jTokenReader.SupportMultipleContent = reader.SupportMultipleContent;
return jTokenReader;
}
This should be used as follows:
public override object ReadJson(JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
// Populate the object properties
using (JsonReader jObjectReader = CopyReaderForObject(reader, jObject))
{
serializer.Populate(jObjectReader, target);
}
return target;
}
Older solution follows:
/// <summary>Base Generic JSON Converter that can help quickly define converters for specific types by automatically
/// generating the CanConvert, ReadJson, and WriteJson methods, requiring the implementer only to define a strongly typed Create method.</summary>
public abstract class JsonCreationConverter<T> : JsonConverter
{
/// <summary>Create an instance of objectType, based properties in the JSON object</summary>
/// <param name="objectType">type of object expected</param>
/// <param name="jObject">contents of JSON object that will be deserialized</param>
protected abstract T Create(Type objectType, JObject jObject);
/// <summary>Determines if this converted is designed to deserialization to objects of the specified type.</summary>
/// <param name="objectType">The target type for deserialization.</param>
/// <returns>True if the type is supported.</returns>
public override bool CanConvert(Type objectType)
{
// FrameWork 4.5
// return typeof(T).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
// Otherwise
return typeof(T).IsAssignableFrom(objectType);
}
/// <summary>Parses the json to the specified type.</summary>
/// <param name="reader">Newtonsoft.Json.JsonReader</param>
/// <param name="objectType">Target type.</param>
/// <param name="existingValue">Ignored</param>
/// <param name="serializer">Newtonsoft.Json.JsonSerializer to use.</param>
/// <returns>Deserialized Object</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
//Create a new reader for this jObject, and set all properties to match the original reader.
JsonReader jObjectReader = jObject.CreateReader();
jObjectReader.Culture = reader.Culture;
jObjectReader.DateParseHandling = reader.DateParseHandling;
jObjectReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
jObjectReader.FloatParseHandling = reader.FloatParseHandling;
// Populate the object properties
serializer.Populate(jObjectReader, target);
return target;
}
/// <summary>Serializes to the specified type</summary>
/// <param name="writer">Newtonsoft.Json.JsonWriter</param>
/// <param name="value">Object to serialize.</param>
/// <param name="serializer">Newtonsoft.Json.JsonSerializer to use.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
Input elements do behave differently from other elements, which would do just about what you want if you give them float: left
(see http://jsfiddle.net/hEvYj/5/). I do not think that is possible without calculating it in some way with JavaScript (i.e. add 5px to the width per letter in the box).
Python uses not
instead of !
for negation.
Try
if not var:
print "learnt stuff"
instead
Got a solution that runs. Don't know if it is optimal though. What I do is to split the string according to http://blogs.oracle.com/aramamoo/2010/05/how_to_split_comma_separated_string_and_pass_to_in_clause_of_select_statement.html
Using:
select regexp_substr(' 1, 2 , 3 ','[^,]+', 1, level) from dual
connect by regexp_substr('1 , 2 , 3 ', '[^,]+', 1, level) is not null;
So my final code looks like this ($bp_gr1'
are strings like 1,2,3
):
UPDATE TAB1
SET BUDGPOST_GR1 =
CASE
WHEN ( BUDGPOST IN (SELECT REGEXP_SUBSTR ( '$BP_GR1',
'[^,]+',
1,
LEVEL )
FROM DUAL
CONNECT BY REGEXP_SUBSTR ( '$BP_GR1',
'[^,]+',
1,
LEVEL )
IS NOT NULL) )
THEN
'BP_GR1'
WHEN ( BUDGPOST IN (SELECT REGEXP_SUBSTR ( ' $BP_GR2',
'[^,]+',
1,
LEVEL )
FROM DUAL
CONNECT BY REGEXP_SUBSTR ( '$BP_GR2',
'[^,]+',
1,
LEVEL )
IS NOT NULL) )
THEN
'BP_GR2'
WHEN ( BUDGPOST IN (SELECT REGEXP_SUBSTR ( ' $BP_GR3',
'[^,]+',
1,
LEVEL )
FROM DUAL
CONNECT BY REGEXP_SUBSTR ( '$BP_GR3',
'[^,]+',
1,
LEVEL )
IS NOT NULL) )
THEN
'BP_GR3'
WHEN ( BUDGPOST IN (SELECT REGEXP_SUBSTR ( '$BP_GR4',
'[^,]+',
1,
LEVEL )
FROM DUAL
CONNECT BY REGEXP_SUBSTR ( '$BP_GR4',
'[^,]+',
1,
LEVEL )
IS NOT NULL) )
THEN
'BP_GR4'
ELSE
'SAKNAR BUDGETGRUPP'
END;
Is there a way to make it run faster?
In general, fixing corrupt objects can be pretty difficult. However, in this case, we're confident that the problem is an aborted transfer, meaning that the object is in a remote repository, so we should be able to safely remove our copy and let git get it from the remote, correctly this time.
The temporary object file, with zero size, can obviously just be removed. It's not going to do us any good. The corrupt object which refers to it, d4a0e75...
, is our real problem. It can be found in .git/objects/d4/a0e75...
. As I said above, it's going to be safe to remove, but just in case, back it up first.
At this point, a fresh git pull
should succeed.
...assuming it was going to succeed in the first place. In this case, it appears that some local modifications prevented the attempted merge, so a stash
, pull
, stash pop
was in order. This could happen with any merge, though, and didn't have anything to do with the corrupted object. (Unless there was some index cleanup necessary, and the stash did that in the process... but I don't believe so.)
alias chkconfig=sysv-rc-conf
chkconfig --list
syntax
sysv-rc-conf command line usage:
sysv-rc-conf --list [service name]
sysv-rc-conf [--level <runlevels>] <service name> <on|off>
Try this:
arr3 = Split(Join(arr1, ",") & "," & Join(arr2, ","), ",")
If you want to see the array as an array, you can say
alert(JSON.stringify(aCustomers));
instead of all those document.write
s.
However, if you want to display them cleanly, one per line, in your popup, do this:
alert(aCustomers.join("\n"));
How about using foreach loop:
Cursor cursor;
for (Cursor c : CursorUtils.iterate(cursor)) {
//c.doSth()
}
However my version of CursorUtils should be less ugly, but it automatically closes the cursor:
public class CursorUtils {
public static Iterable<Cursor> iterate(Cursor cursor) {
return new IterableWithObject<Cursor>(cursor) {
@Override
public Iterator<Cursor> iterator() {
return new IteratorWithObject<Cursor>(t) {
@Override
public boolean hasNext() {
t.moveToNext();
if (t.isAfterLast()) {
t.close();
return false;
}
return true;
}
@Override
public Cursor next() {
return t;
}
@Override
public void remove() {
throw new UnsupportedOperationException("CursorUtils : remove : ");
}
@Override
protected void onCreate() {
t.moveToPosition(-1);
}
};
}
};
}
private static abstract class IteratorWithObject<T> implements Iterator<T> {
protected T t;
public IteratorWithObject(T t) {
this.t = t;
this.onCreate();
}
protected abstract void onCreate();
}
private static abstract class IterableWithObject<T> implements Iterable<T> {
protected T t;
public IterableWithObject(T t) {
this.t = t;
}
}
}
For Unit Tests, the System variable is not instantiated yet when I do "mvn clean install" because there is no server running the application. So in order to set the System properties, I need to do it in pom.xml. Like so:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.21.0</version>
<configuration>
<systemPropertyVariables>
<propertyName>propertyValue</propertyName>
<MY_ENV_VAR>newValue</MY_ENV_VAR>
<ENV_TARGET>olqa</ENV_TARGET>
<buildDirectory>${project.build.directory}</buildDirectory>
</systemPropertyVariables>
</configuration>
</plugin>
To restore a single database:
1. Backup the 'users' database
$ mongodump --db users
2. Restore the 'users' database to a new database called 'users2'
$ mongorestore --db users2 dump/users
To restore all databases:
1. Backup all databases
$ mongodump
2. Restore all databases
$ mongorestore dump
I would prefer it without enumerate and instead use "range" like this:
for item in range(0, len(alist)):
if 123 in alist[item]:
alist[item] = 2014
For those who are new to python it might be more readable and a little smarter to recap.
Regards P.
After doing the git rm --cached
command, try adding myfile
to the .gitignore
file (create one if it does not exist). This should tell git to ignore myfile
.
The .gitignore
file is versioned, so you'll need to commit it and push it to the remote repository.
Try this piece of code, rather than ObjectInputStream
.
BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
while (true)
{
String cominginText = "";
try
{
cominginText = in.readLine ();
System.out.println (cominginText);
}
catch (IOException e)
{
//error ("System: " + "Connection to server lost!");
System.exit (1);
break;
}
}
If you would migrate your project to Spring Boot 1.4, you could use new annotation @MockBean
for faking MyDependentObject
. With that feature you could remove Mockito's @Mock
and @InjectMocks
annotations from your test.
I didn't know about the join function - Nice! I had written a function that I placed in the code section (report properties->code tab:
Public Function ShowParmValues(ByVal parm as Parameter) as string
Dim s as String
For i as integer = 0 to parm.Count-1
s &= CStr(parm.value(i)) & IIF( i < parm.Count-1, ", ","")
Next
Return s
End Function
Construct a Calendar object and use the method add(Calendar.DATE, 1);
I have also faced this problem. Finally I got a solution. Use this bellow code. Hope: problem will be solve.
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
I've compared all suggested solutions (and a few new ones) with perfplot (a small project of mine).
For large enough arrays, it turns out that
numpy.sum(numpy.array(a) == 1)
is slightly faster than the other solutions.
numpy.bincount(a)
is what you want.
Code to reproduce the plots:
from collections import Counter
from collections import defaultdict
import numpy
import operator
import pandas
import perfplot
def counter(a):
return Counter(a)
def count(a):
return dict((i, a.count(i)) for i in set(a))
def bincount(a):
return numpy.bincount(a)
def pandas_value_counts(a):
return pandas.Series(a).value_counts()
def occur_dict(a):
d = {}
for i in a:
if i in d:
d[i] = d[i]+1
else:
d[i] = 1
return d
def count_unsorted_list_items(items):
counts = defaultdict(int)
for item in items:
counts[item] += 1
return dict(counts)
def operator_countof(a):
return dict((i, operator.countOf(a, i)) for i in set(a))
perfplot.show(
setup=lambda n: list(numpy.random.randint(0, 100, n)),
n_range=[2**k for k in range(20)],
kernels=[
counter, count, bincount, pandas_value_counts, occur_dict,
count_unsorted_list_items, operator_countof
],
equality_check=None,
logx=True,
logy=True,
)
2.
from collections import Counter
from collections import defaultdict
import numpy
import operator
import pandas
import perfplot
def counter(a):
return Counter(a)
def count(a):
return dict((i, a.count(i)) for i in set(a))
def bincount(a):
return numpy.bincount(a)
def pandas_value_counts(a):
return pandas.Series(a).value_counts()
def occur_dict(a):
d = {}
for i in a:
if i in d:
d[i] = d[i]+1
else:
d[i] = 1
return d
def count_unsorted_list_items(items):
counts = defaultdict(int)
for item in items:
counts[item] += 1
return dict(counts)
def operator_countof(a):
return dict((i, operator.countOf(a, i)) for i in set(a))
perfplot.show(
setup=lambda n: list(numpy.random.randint(0, 100, n)),
n_range=[2**k for k in range(20)],
kernels=[
counter, count, bincount, pandas_value_counts, occur_dict,
count_unsorted_list_items, operator_countof
],
equality_check=None,
logx=True,
logy=True,
)
For those who may be running WAMP 3.1.4 with Apache 2.4.35 on Windows 10 (64-bit)
If you're having issues with external devices connecting to your localhost, and receiving a 403 Forbidden error, it may be an issue with your httpd.conf and the httpd-vhosts.conf files and the "Require local" line they both have within them.
[Before] httpd-vhosts.conf
<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot "${INSTALL_DIR}/www"
<Directory "${INSTALL_DIR}/www/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require local <--- This is the offending line.
</Directory>
</VirtualHost>
[After] httpd-vhosts.conf
<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot "${INSTALL_DIR}/www"
<Directory "${INSTALL_DIR}/www/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
</Directory>
</VirtualHost>
Additionally, you'll need to update your httpd.conf file as follows:
[Before] httpd.conf
DocumentRoot "${INSTALL_DIR}/www"
<Directory "${INSTALL_DIR}/www/">
# onlineoffline tag - don't remove
Require local #<--- This is the offending line.
</Directory>
[After] httpd.conf
DocumentRoot "${INSTALL_DIR}/www"
<Directory "${INSTALL_DIR}/www/">
# onlineoffline tag - don't remove
# Require local
</Directory>
Make sure to restart your WAMP server via (System tray at bottom-right of screen --> left-click WAMP icon --> "Restart all Services").
Then refresh your machine's browser on localhost to ensure you've still got proper connectivity there, and then refresh your other external devices that you were previously attempting to connect.
Disclaimer: If you're in a corporate setting, this is untested from a security perspective; please ensure you're keenly aware of your local development environment's access protocols before implementing any sweeping changes.
super is a lower bound, and extends is an upper bound.
According to http://download.oracle.com/javase/tutorial/extra/generics/morefun.html :
The solution is to use a form of bounded wildcard we haven't seen yet: wildcards with a lower bound. The syntax ? super T denotes an unknown type that is a supertype of T (or T itself; remember that the supertype relation is reflexive). It is the dual of the bounded wildcards we've been using, where we use ? extends T to denote an unknown type that is a subtype of T.
Depends on what you need, you have a couple of choices, you can do:
// this will replace the first occurrence of "www." and return "testwww.com"
"www.testwww.com".replace("www.", "");
// this will slice the first four characters and return "testwww.com"
"www.testwww.com".slice(4);
// this will replace the www. only if it is at the beginning
"www.testwww.com".replace(/^(www\.)/,"");
You cannot set a maximum value (other than choosing a datatype which cannot hold large numbers, but there are none that have the limit you're asking for). You can check that with LAST_INSERT_ID() after inserting to get the id of the newly created member, and if it is too big handle it in your application code (e.g., delete and reject the member).
Why do you want an upper limit?
this is what i came up with as i was having issues with @asp8811 answer(maybe my own difficulties)
' this will do the put the first 2 sheets in a pdf ' Note each ws should be controlled with page breaks for printing which is a bit fiddly ' this will explicitly put the pdf in the current dir
Sub luxation2()
Dim Filename As String
Filename = "temp201"
Dim shtAry()
ReDim shtAry(1) ' this is an array of length 2
For i = 1 To 2
shtAry(i - 1) = Sheets(i).Name
Debug.Print Sheets(i).Name
Next i
Sheets(shtAry).Select
Debug.Print ThisWorkbook.Path & "\"
ActiveSheet.ExportAsFixedFormat xlTypePDF, ThisWorkbook.Path & "/" & Filename & ".pdf", , , False
End Sub
It is not an import problem. You simply call .dropDuplicates()
on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...)
is pyspark.sql.dataframe.DataFrame
, after you apply .collect()
it is a plain Python list
, and lists don't provide dropDuplicates
method. What you want is something like this:
(df1 = sqlContext
.createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
.dropDuplicates())
df1.collect()
See the (quite) recent answer on the matplotlib repository, in which the following solution is suggested:
If you want to set the xticklabels:
ax.set_xticks([1,4,5])
ax.set_xticklabels([1,4,5], fontsize=12)
If you want to only increase the fontsize of the xticklabels, using the default values and locations (which is something I personally often need and find very handy):
ax.tick_params(axis="x", labelsize=12)
To do it all at once:
plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold",
horizontalalignment="left")`
In Swift:
var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy"
var dateString = formatter.stringFromDate(YourNSDateInstanceHERE)
Please don't use techniques described in other answers here. They are either not working with css3 animations size changes, floating layout changes or changes that don't come from jQuery land. You can use a resize-detector, a event-based approach, that doesn't waste your CPU time.
https://github.com/marcj/css-element-queries
It contains a ResizeSensor class you can use for that purpose.
new ResizeSensor(jQuery('#mainContent'), function(){
console.log('main content dimension changed');
});
Disclaimer: I wrote this library
The Material Design Typography page has demos for some of these fonts and suggestions on choosing fonts and styles.
For code sleuths: fonts.xml
is the definitive and ever-expanding list of Android fonts.
Set the android:fontFamily
and android:textStyle
attributes, e.g.
<!-- Roboto Bold -->
<TextView
android:fontFamily="sans-serif"
android:textStyle="bold" />
to the desired values from this table:
Font | android:fontFamily | android:textStyle
-------------------------|-----------------------------|-------------------
Roboto Thin | sans-serif-thin |
Roboto Light | sans-serif-light |
Roboto Regular | sans-serif |
Roboto Bold | sans-serif | bold
Roboto Medium | sans-serif-medium |
Roboto Black | sans-serif-black |
Roboto Condensed Light | sans-serif-condensed-light |
Roboto Condensed Regular | sans-serif-condensed |
Roboto Condensed Medium | sans-serif-condensed-medium |
Roboto Condensed Bold | sans-serif-condensed | bold
Noto Serif | serif |
Noto Serif Bold | serif | bold
Droid Sans Mono | monospace |
Cutive Mono | serif-monospace |
Coming Soon | casual |
Dancing Script | cursive |
Dancing Script Bold | cursive | bold
Carrois Gothic SC | sans-serif-smallcaps |
(Noto Sans is a fallback font; you can't specify it directly)
Note: this table is derived from fonts.xml
. Each font's family name and style is listed in fonts.xml, e.g.
<family name="serif-monospace">
<font weight="400" style="normal">CutiveMono.ttf</font>
</family>
serif-monospace
is thus the font family, and normal
is the style.
Based on the log of fonts.xml and the former system_fonts.xml, you can see when each font was added:
The following works for me:
Map<String, String> propertyMap = getJsonAsMap(json);
where getJsonAsMap
is defined like so:
public HashMap<String, String> getJsonAsMap(String json)
{
try
{
ObjectMapper mapper = new ObjectMapper();
TypeReference<Map<String,String>> typeRef = new TypeReference<Map<String,String>>() {};
HashMap<String, String> result = mapper.readValue(json, typeRef);
return result;
}
catch (Exception e)
{
throw new RuntimeException("Couldnt parse json:" + json, e);
}
}
Note that this will fail if you have child objects in your json (because they're not a String
, they're another HashMap
), but will work if your json is a key value list of properties like so:
{
"client_id": "my super id",
"exp": 1481918304,
"iat": "1450382274",
"url": "http://www.example.com"
}
In my scenario, there was no process blocking the database under sp_who2. However, we discovered because the database is much larger than our other databases that pending processes were still running which is why the database under the availability group still displayed as red/offline after we tried to 'resume data'by right clicking the paused database.
To check if you still have processes running just execute this command: select percent complete from sys.dm_exec_requests where percent_complete > 0
This warning is about unsafe use of strcpy. Try IOBname[ii]='\0';
instead.
This will also work if the pattern you want to match is a variable.
dbh = new DbHelper(this);
SQLiteDatabase db = dbh.getWritableDatabase();
Cursor c = db.query(
"TableName",
new String[]{"ColumnName"},
"ColumnName LIKE ?",
new String[]{_data+"%"},
null,
null,
null
);
while(c.moveToNext()){
// your calculation goes here
}
I had a similar issue with Pandas, you need to use the iterrows() function to iterate through a Pandas dataset Pandas documentation for iterrows
data = pd.read_csv('foo.csv')
for index,item in data.iterrows():
print('{} {}'.format(item["gravatar_id"], item["position"]))
note that you need to handle the index in the dataset that is also returned by the function.
You need to use a pointer to a member function, not just a pointer to a function.
class A {
int f() { return 1; }
public:
int (A::*x)();
A() : x(&A::f) {}
};
int main() {
A a;
std::cout << (a.*a.x)();
return 0;
}
The javax.mail-api
artifact is only good for compiling against.
You actually need to run code, so you need a complete implementation of JavaMail API. Use this:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
NOTE: The version number will probably differ. Check the latest version here.
please see :==
private int group1Id = 1;
int homeId = Menu.FIRST;
int profileId = Menu.FIRST +1;
int searchId = Menu.FIRST +2;
int dealsId = Menu.FIRST +3;
int helpId = Menu.FIRST +4;
int contactusId = Menu.FIRST +5;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(group1Id, homeId, homeId, "").setIcon(R.drawable.home_menu);
menu.add(group1Id, profileId, profileId, "").setIcon(R.drawable.profile_menu);
menu.add(group1Id, searchId, searchId, "").setIcon(R.drawable.search_menu);
menu.add(group1Id, dealsId, dealsId, "").setIcon(R.drawable.deals_menu);
menu.add(group1Id, helpId, helpId, "").setIcon(R.drawable.help_menu);
menu.add(group1Id, contactusId, contactusId, "").setIcon(R.drawable.contactus_menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
// write your code here
Toast msg = Toast.makeText(MainHomeScreen.this, "Menu 1", Toast.LENGTH_LONG);
msg.show();
return true;
case 2:
// write your code here
return true;
case 3:
// write your code here
return true;
case 4:
// write your code here
return true;
case 5:
// write your code here
return true;
case 6:
// write your code here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Looking at the controller, and learing a bit more about how MVC actually works, I was able to make sense of this.
My view was one of the auto-generated ones, and contained this line of code:
@Html.DropDownList("PriorityID", string.Empty)
To add html attributes, I needed to do something like this:
@Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class="dropdown" })
Thanks again to @Laurent for your help, I realise the question wasn't as clear as it could have been...
UPDATE:
A better way of doing this would be to use DropDownListFor where possible, that way you don't rely on a magic string for the name attribute
@Html.DropDownListFor(x => x.PriorityID, (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class = "dropdown" })
If you've ever backed up your settings (Tools -> Import and Export Settings), you can restore the settings file to get back to a prior state. This is the only thing that I've found to work.
The following code performs a HEAD
request to check whether the website is available or not.
public static boolean isReachable(String targetUrl) throws IOException
{
HttpURLConnection httpUrlConnection = (HttpURLConnection) new URL(
targetUrl).openConnection();
httpUrlConnection.setRequestMethod("HEAD");
try
{
int responseCode = httpUrlConnection.getResponseCode();
return responseCode == HttpURLConnection.HTTP_OK;
} catch (UnknownHostException noInternetConnection)
{
return false;
}
}
actually during the installation process.it will prompt u to enter the password..At the last step of installation, a window will appear showing cloning database files..After copying,there will be a option..like password managament..there we hav to set our password..and user name will be default..
BigDecimal bd = new BigDecimal(300000);
NumberFormat formatter = NumberFormat.getInstance(new Locale("en_US"));
System.out.println(formatter.format(bd.longValue()));
EDIT
To get custom grouping separator such as space, do this:
DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
symbols.setGroupingSeparator(' ');
DecimalFormat formatter = new DecimalFormat("###,###.##", symbols);
System.out.println(formatter.format(bd.longValue()));
Be careful. For this you need @GET (not @PUT).
If you (or a helpful admin) runs Set-ExecutionPolicy
as administrator, the policy will be set for all users. (I would suggest "remoteSigned" rather than "unrestricted" as a safety measure.)
NB.: On a 64-bit OS you need to run Set-ExecutionPolicy
for 32-bit and 64-bit PowerShell separately.
Several options, in order of preference:
HKey_Current_User\Software\Microsoft\Windows\CurrentVersion\Run
registry key. The only problem here is it requires write access to the registry, which isn't always available.HKey_Local_Machine\Software\Microsoft\Windows\CurrentVersion\Run
registry key. The only problem here is it requires write access to the registry, which isn't always available.This answer is older now. Since I wrote this, Windows 10 was released, which changes how the Start Menu folders work... including the Startup
folder. It's not yet clear to me how easy it is to just add or remove a file in that folder without also referencing the internal database Windows uses for these locations.
You can open Xcode Help -> Run and debug -> Network debugging for more info. Hope it helps.
You cannot use the same name for multiple captures. Thus you cannot use a quantifier on expressions with named captures.
So either don’t use named captures:
(?:(\b\w+\b)\s*=\s*("[^"]*"|'[^']*'|[^"'<>\s]+)\s+)+
Or don’t use the quantifier on this expression:
(?<name>\b\w+\b)\s*=\s*(?<value>"[^"]*"|'[^']*'|[^"'<>\s]+)
This does also allow attribute values like bar=' baz='quux
:
foo="bar=' baz='quux"
Well the drawback will be that you have to strip the leading and trailing quotes afterwards.
Having sequential ID's makes it a LOT easier for a hacker or data miner to compromise your site and data. Keep that in mind when choosing a PK for a website.
use "temp" in lieu of "tmp"
"/temp/test.png"
it worked for me after i realized the tmp is a temporary folder that didn't exist on my computer, but my temp was my temporary folder
///
EDIT:
I also created a new folder "tmp" in my C: drive and everything worked perfectly. The book may have missed mentioning that small step
check out http://webchat.freenode.net/?channels=node.js to chat with some of the node.js community
You don't need absolute+relative for this. It is very much possible using relative position for both container and data. This is how you do it.
Assume height of your data is going to be x
. Your container is relative and footer is also relative. All you have to do is add to your data
bottom: -webkit-calc(-100% + x);
Your data will always be at the bottom of your container. Works even if you have container with dynamic height.
HTML will be like this
<div class="container">
<div class="data"></div>
</div>
CSS will be like this
.container{
height:400px;
width:600px;
border:1px solid red;
margin-top:50px;
margin-left:50px;
display:block;
}
.data{
width:100%;
height:40px;
position:relative;
float:left;
border:1px solid blue;
bottom: -webkit-calc(-100% + 40px);
bottom:calc(-100% + 40px);
}
Hope this helps.
UPDATE 2
@Override
protected void onResume() {
super.onResume();
mUserNameEdit.requestFocus();
mUserNameEdit.postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
InputMethodManager keyboard = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(mUserNameEdit, 0);
}
},200); //use 300 to make it run when coming back from lock screen
}
I tried very hard and found out a solution ... whenever a new activity starts then keyboard cant open but we can use Runnable in onResume and it is working fine so please try this code and check...
UPDATE 1
add this line in your AppLogin.java
mUserNameEdit.requestFocus();
and this line in your AppList.java
listview.requestFocus()'
after this check your application if it is not working then add this line in your AndroidManifest.xml
file
<activity android:name=".AppLogin" android:configChanges="keyboardHidden|orientation"></activity>
<activity android:name=".AppList" android:configChanges="keyboard|orientation"></activity>
ORIGINAL ANSWER
InputMethodManager imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);
for hide keyboard
imm.hideSoftInputFromWindow(ed.getWindowToken(), 0);
for show keyboard
imm.showSoftInput(ed, 0);
for focus on EditText
ed.requestFocus();
where ed is EditText
Table definition
CREATE TABLE "NAMES" ("NAME" VARCHAR2(10 BYTE))) ;
Let's insert values into this table
INSERT INTO NAMES VALUES('PETER');
INSERT INTO NAMES VALUES('PAUL');
INSERT INTO NAMES VALUES('MARY');
Procedure starts from here
DECLARE
MAXNUM INTEGER;
CNTR INTEGER := 1;
C_NAME NAMES.NAME%TYPE;
NSTR VARCHAR2(50);
BEGIN
SELECT MAX(ROWNUM) INTO MAXNUM FROM NAMES;
LOOP
SELECT NAME INTO C_NAME FROM
(SELECT ROWNUM RW, NAME FROM NAMES ) P WHERE P.RW = CNTR;
NSTR := NSTR ||','||C_NAME;
CNTR := CNTR + 1;
EXIT WHEN CNTR > MAXNUM;
END LOOP;
dbms_output.put_line(SUBSTR(NSTR,2));
END;
Result
PETER,PAUL,MARY
To remove the license key:
In my case on a Windows 7 machine I could find this license key in C:\Users\you\.IntelliJIdea13\config\idea13.key
mappedby
speaks for itself, it tells hibernate not to map this field. it's already mapped by this field [name="field"].
field is in the other entity (name of the variable in the class not the table in the database)
..
If you don't do that, hibernate will map this two relation as it's not the same relation
so we need to tell hibernate to do the mapping in one side only and co-ordinate between them.
Had the same issue; validated HTML & found I was missing a name="email"
attribute from an <input />
. Always validate the HTML to be positive your HTML is valid. After I added it, validate()
worked perfectly.
To convert a
Kotlin
source file to aJava
source file you need to (when you in Android Studio):
Press Cmd-Shift-A on a Mac, or press Ctrl-Shift-A on a Windows machine.
Type the action you're looking for: Kotlin Bytecode
and choose Show Kotlin Bytecode
from menu.
Decompile
button on the top of Kotlin Bytecode
panel.My problem was that I had a @Url.Action and I had sent through a value for the same property twice
mov cx,3
loopstart:
do stuff
dec cx ;Note: decrementing cx and jumping on result is
jnz loopstart ;much faster on Intel (and possibly AMD as I haven't
;tested in maybe 12 years) rather than using loop loopstart
you refer to Android resources
, which are already defined in Android system, with @android:id/..
while to access resources that you have defined/created in your project, you use @id/..
More Info
As per your clarifications in the chat, you said you have a problem like this :
If we use
android:id="@id/layout_item_id"
it doesn't work. Instead@+id/
works so what's the difference here? And that was my original question.
Well, it depends on the context, when you're using the XML attribute of android:id
, then you're specifying a new id, and are instructing the parser (or call it the builder) to create a new entry in R.java
, thus you have to include a +
sign.
While in the other case, like android:layout_below="@id/myTextView"
, you're referring to an id that has already been created, so parser links this to the already created id in R.java
.
More Info Again
As you said in your chat, note that android:layout_below="@id/myTextView"
won't recognize an element with id myTextView
if it is written after the element you're using it in.
set escape on
... node_name = 'Geometric Vectors \& Matrices' ...
or alternatively:
set define off
... node_name = 'Geometric Vectors & Matrices' ...
The first allows you to use the backslash to escape the &.
The second turns off & "globally" (no need to add a backslash anywhere). You can turn it on again by set define on
and from that line on the ampersands will get their special meaning back, so you can turn it off for some parts of the script and not for others.
This line will retrieve the whole HTML code of the frame. By using other methods instead of innerHTML
you can traverse DOM of the inner document.
document.getElementById('iframe').contentWindow.document.body.innerHTML
Thing to remember is that this will work only if the frame source is on the same domain. If it is from a different domain, cross-site-scripting (XSS) protection will kick in.
You can't increase the array's length if it is not declared in heap memory (see below code which first array input is asked by user and then it asks how much you want to increase array and also copy previous array elements):
#include<stdio.h>
#include<stdlib.h>
int * increasesize(int * p,int * q,int x)
{
int i;
for(i=0;i<x;i++)
{
q[i]=p[i];
}
free(p);
p=q;
return p;
}
void display(int * q,int x)
{
int i;
for(i=0;i<x;i++)
{
printf("%d \n",q[i]);
}
}
int main()
{
int x,i;
printf("enter no of element to create array");
scanf("%d",&x);
int * p=(int *)malloc(x*sizeof(int));
printf("\n enter number in the array\n");
for(i=0;i<x;i++)
{
scanf("%d",&p[i]);
}
int y;
printf("\nenter the new size to create new size of array");
scanf("%d",&y);
int * q=(int *)malloc(y*sizeof(int));
display(increasesize(p,q,x),y);
free(q);
}
There are basically two most popular answers. The first one basically says
Optimistic needs a three-tier architectures where you do not necessarily maintain a connection to the database for your session whereas Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking you need either a direct connection to the database.
optimistic (versioning) is faster because of no locking but (pessimistic) locking performs better when contention is high and it is better to prevent the work rather than discard it and start over.
or
Optimistic locking works best when you have rare collisions
As it is put on this page.
I created my answer to explain how "keep connection" is related to "low collisions".
To understand which strategy is best for you, think not about the Transactions Per Second your DB has but the duration of a single transaction. Normally, you open trasnaction, performa operation and close the transaction. This is a short, classical transaction ANSI had in mind and fine to get away with locking. But, how do you implement a ticket reservation system where many clients reserve the same rooms/seats at the same time?
You browse the offers, fill in the form with lots of available options and current prices. It takes a lot of time and options can become obsolete, all the prices invalid between you started to fill the form and press "I agree" button because there was no lock on the data you have accessed and somebody else, more agile, has intefered changing all the prices and you need to restart with new prices.
You could lock all the options as you read them, instead. This is pessimistic scenario. You see why it sucks. Your system can be brought down by a single clown who simply starts a reservation and goes smoking. Nobody can reserve anything before he finishes. Your cash flow drops to zero. That is why, optimistic reservations are used in reality. Those who dawdle too long have to restart their reservation at higher prices.
In this optimistic approach you have to record all the data that you read (as in mine Repeated Read) and come to the commit point with your version of data (I want to buy shares at the price you displayed in this quote, not current price). At this point, ANSI transaction is created, which locks the DB, checks if nothing is changed and commits/aborts your operation. IMO, this is effective emulation of MVCC, which is also associated with Optimistic CC and also assumes that your transaction restarts in case of abort, that is you will make a new reservation. A transaction here involves a human user decisions.
I am far from understanding how to implement the MVCC manually but I think that long-running transactions with option of restart is the key to understanding the subject. Correct me if I am wrong anywhere. My answer was motivated by this Alex Kuznecov chapter.
Another approach to solve this is to use the following module.
node_extra_ca_certs_mozilla_bundle
This module can work without any code modification by generating a PEM file that includes all root and intermediate certificates trusted by Mozilla. You can use the following environment variable (Works with Nodejs v7.3+),
To generate the PEM file to use with the above environment variable. You can install the module using:
npm install --save node_extra_ca_certs_mozilla_bundle
and then launch your node script with an environment variable.
NODE_EXTRA_CA_CERTS=node_modules/node_extra_ca_certs_mozilla_bundle/ca_bundle/ca_intermediate_root_bundle.pem node your_script.js
Other ways to use the generated PEM file are available at:
https://github.com/arvind-agarwal/node_extra_ca_certs_mozilla_bundle
NOTE: I am the author of the above module.
$ irb --simple-prompt
class TestClass
def method1
end
def method2
end
def method3
end
end
tc_list = TestClass.instance_methods(false)
#[:method1, :method2, :method3]
puts tc_list
#method1
#method2
#method3
In short there's no way to recover the passphrase for a pair of SSH keys. Why? Because it was intended this way in the first place for security reasons. The answers the other people gave you are all correct ways to CHANGE the password of your keys, not to recover them. So if you've forgotten your passphrase, the best you can do is create a new pair of SSH keys. Here's how to generate SSH keys and add it to your GitHub account.
For People, looking for answers w.r.t to 'map' function and dynamic data, here is a working example.
<img src={"http://examole.com/randomview/images" + each_actor['logo']} />
This gives the URL as "http://examole.com/randomview/images/2/dp_pics/182328.jpg" (random example)
You can also see this message if you forget to include "EntityFramework.SqlServer.dll".
It appears to be a newly added file in EF6. Initially I hadn't included it in my merge module and ran into the problem listed here.
Run the below commands as admin to install NuGet
using Powershell:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Install-PackageProvider -Name NuGet
You can't.
ANYTHING that can be read by the browser can also be read by humans. If you want something hidden, don't send it to the user's browser.
You can add all sorts of gimmicks and tricks to disable right-click and disable ctrl+U
All a user has to do is add view-source:
to the url and they will see the source right away.
Example
view-source:https://stackoverflow.com
Here is my solution. I first create random numbers with random.uniform, format them in to string with double precision and then convert them back to float. You can adjust the precision by changing '.2f' to '.3f' etc..
import random
from decimal import Decimal
GndSpeedHigh = float(format(Decimal(random.uniform(5, 25)), '.2f'))
GndSpeedLow = float(format(Decimal(random.uniform(2, GndSpeedHigh)), '.2f'))
GndSpeedMean = float(Decimal(format(GndSpeedHigh + GndSpeedLow) / 2, '.2f')))
print(GndSpeedMean)
After some experimenting, I made some mods to mehow's code as follows:
I also noted that the project must have trust for the VBA project object model enabled.
' DEPENDENCIES
' 1. Add reference:
' Tools > References > Microsoft Visual Basic for Applications Extensibility 5.3
' 2. Enable VBA project access:
' Backstage / Options / Trust Centre / Trust Center Settings / Trust access to the VBA project object model
Public Function ClearImmediateWindow()
On Error GoTo ErrorHandler
Dim myVBE As VBE
Dim winImm As VBIDE.Window
Dim winActive As VBIDE.Window
Set myVBE = Application.VBE
Set winActive = myVBE.ActiveWindow
Set winImm = myVBE.Windows("Immediate")
' Make sure the Immediate window is visible
winImm.Visible = True
' Switch the focus to the Immediate window
winImm.SetFocus
' Send the key sequence to select the window contents and delete it:
' Ctrl+Home to move cursor to the top then Ctrl+Shift+End to move while
' selecting to the end then Delete
SendKeys "^{Home}", False
SendKeys "^+{End}", False
SendKeys "{Del}", False
' Return the focus to the user's original window
' (comment out next line if your code disappears instead!)
'winActive.SetFocus
' Release object variables memory
Set myVBE = Nothing
Set winImm = Nothing
Set winActive = Nothing
' Avoid the error handler and exit this procedure
Exit Function
ErrorHandler:
MsgBox "Error " & Err.Number & vbCrLf & vbCrLf & Err.Description, _
vbCritical + vbOKOnly, "There was an unexpected error."
Resume Next
End Function
CSS support has binding to javascript, as a side note.
if (CSS.supports("( -moz-user-select:unset )")) {_x000D_
console.log("FIREFOX!!!")_x000D_
}
_x000D_
https://developer.mozilla.org/en-US/docs/Web/CSS/Mozilla_Extensions
From JDK 14+ which includes JEP 305 we can do Pattern Matching for instanceof
Patterns basically test that a value has a certain type, and can extract information from the value when it has the matching type.
Before Java 14
if (obj instanceof String) {
String str = (String) obj; // need to declare and cast again the object
.. str.contains(..) ..
}else{
str = ....
}
Java 14 enhancements
if (!(obj instanceof String str)) {
.. str.contains(..) .. // no need to declare str object again with casting
} else {
.. str....
}
We can also combine the type check and other conditions together
if (obj instanceof String str && str.length() > 4) {.. str.contains(..) ..}
The use of pattern matching in instanceof
should reduce the overall number of explicit casts in Java programs.
PS: instanceOf
will only match when the object is not null, then only it can be assigned to str
.
The JUnit way is to do this at run-time is org.junit.Assume
.
@Before
public void beforeMethod() {
org.junit.Assume.assumeTrue(someCondition());
// rest of setup.
}
You can do it in a @Before
method or in the test itself, but not in an @After
method. If you do it in the test itself, your @Before
method will get run. You can also do it within @BeforeClass
to prevent class initialization.
An assumption failure causes the test to be ignored.
Edit: To compare with the @RunIf
annotation from junit-ext, their sample code would look like this:
@Test
public void calculateTotalSalary() {
assumeThat(Database.connect(), is(notNull()));
//test code below.
}
Not to mention that it is much easier to capture and use the connection from the Database.connect()
method this way.
Disable JetBrains Inspections and get the ESLint plugin.
The only thing that File | Invalidate caches and restart
does for me is reset it long enough to trick me into thinking the error is gone. Once the inspections run again the error comes back like a gift that keeps on giving.
I saved myself all that frustration by disabling all JetBrains inspections (Editor
> Inspections
> uncheck JavaScript
) Then I installed the ESLint plugin.
The inspection that causes "Unresolved function method" can be turned off by going to JetBrains inspections (Editor
> Inspections
> JavaScript
) and searching for "Unresolved Javascript" and turning off "Unresolved Javascript function" and "Unresolved Javascript variable"
I killed them all and have edited my code hassle free ever since.
If you set id in your database to be primary key and autoincrement, then this line of code is wrong:
user.setId(1);
Try with this:
public static void main(String[] args){
UserBean user = new UserBean();
user.setUserName("name1");
user.setPassword("passwd1");
em.persist(user);
}
Try this:
public class Person {
public int Id { get; set; }
public string Name { get; set; }
}
And then:
var list = new[] {
new Person { Id = 1, Name = "Name1" },
new Person { Id = 2, Name = "Name2" },
new Person { Id = 3, Name = "Name3" }
};
var selectList = new SelectList(list, "Id", "Name", 2);
ViewData["People"] = selectList;
Html.DropDownList("PeopleClass", (SelectList)ViewData["People"])
With MVC RC2, I get:
<select id="PeopleClass" name="PeopleClass">
<option value="1">Name1</option>
<option selected="selected" value="2">Name2</option>
<option value="3">Name3</option>
</select>
let myVar = {a: {b: {c: 1}}};
console.log(JSON.stringify( myVar, null, 4 ))
Great for deep inspection of data objects. This approach works on nested arrays and nested objects with arrays.
Incidentally, if your span
class is even-numbered (e.g. span8
) you can add an offset
class to center it – for span8
that would be offset2
(assuming the default 12-column grid), for span6
it would be offset3
and so on (basically, half the number of remaining columns if you subtract the span
-number from the total number of columns in the grid).
UPDATE
Bootstrap 3 renamed a lot of classes so all the span*
classes should be col-md-*
and the offset
classes should be col-md-offset-*
, assuming you're using the medium-sized responsive grid.
I created a quick demo here, hope it helps: http://codepen.io/anon/pen/BEyHd.
I solved the problem in this way:
and no more error.
Instead of using a std::string, you could use a std::wstring.
EDIT: Sorry this is not more explanatory, but I have to run.
Use std::wstring::c_str()
// pop back stack all the way
final FragmentManager fm = getSherlockActivity().getSupportFragmentManager();
int entryCount = fm.getBackStackEntryCount();
while (entryCount-- > 0) {
fm.popBackStack();
}
I believe the 2GB limit is for 32-bit Java. I thought v1.6 was always 64 bit, but try forcing 64 bit mode just to see: add the -d64 option.
The equivalent to the accepted answer in jQuery 1.11:
$(window).on("beforeunload", function () {
return "Please don't leave me!";
});
altCognito's answer used the unload
event, which happens too late for JavaScript to abort the navigation.
do-while is better if the compiler isn't competent at optimization. do-while has only a single conditional jump, as opposed to for and while which have a conditional jump and an unconditional jump. For CPUs which are pipelined and don't do branch prediction, this can make a big difference in the performance of a tight loop.
Also, since most compilers are smart enough to perform this optimization, all loops found in decompiled code will usually be do-while (if the decompiler even bothers to reconstruct loops from backward local gotos at all).
Creator of the change-case extension here. I've updated the extension to support spanning lines.
To map the upper case command to a keybinding (e.g. CTRL+T+U), click File -> Preferences -> Keyboard shortcuts, and insert the following into the json config:
{
"key": "ctrl+t ctrl+u",
"command": "extension.changeCase.upper",
"when": "editorTextFocus"
}
EDIT:
With the November 2016 (release notes) update of VSCode, there is built-in support for converting to upper case and lower case via the commands editor.action.transformToUppercase
and editor.action.transformToLowercase
. These don't have default keybindings. They also work with multi-line blocks.
The change-case extension is still useful for other text transformations, e.g. camelCase, PascalCase, snake_case, kebab-case, etc.
Here is an example:
MySqlConnection con = new MySqlConnection(
"Server=ServerName;Database=DataBaseName;UID=username;Password=password");
MySqlCommand cmd = new MySqlCommand(
" INSERT Into Test (lat, long) VALUES ('"+OSGconv.deciLat+"','"+
OSGconv.deciLon+"')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
I was wasting my time on this for hours. Fortunately, I found the solution. If you are using bootstrap admin templates (AdminLTE), this problem may show up. Thing is we have to use adminLTE framework plugins.
example: ifChecked
event:
$('input').on('ifChecked', function(event){
alert(event.type + ' callback');
});
For more information click here.
Hope it helps you too.
I found this question while looking for a similar solution. I modified the answer that @Dale gave to suit my purposes. I wanted something that was a little more flexible and had some error trapping. Just thought I might put it here for anyone looking for the same thing.
@echo off
setLocal EnableDelayedExpansion
GOTO checkvars
:checkvars
IF "%1"=="" GOTO syntaxerror
IF NOT "%1"=="-f" GOTO syntaxerror
IF %2=="" GOTO syntaxerror
IF NOT EXIST %2 GOTO nofile
IF "%3"=="" GOTO syntaxerror
IF NOT "%3"=="-n" GOTO syntaxerror
IF "%4"=="" GOTO syntaxerror
set param=%4
echo %param%| findstr /xr "[1-9][0-9]* 0" >nul && (
goto proceed
) || (
echo %param% is NOT a valid number
goto syntaxerror
)
:proceed
set limit=%4
set file=%2
set lineCounter=1+%limit%
set filenameCounter=0
set name=
set extension=
for %%a in (%file%) do (
set "name=%%~na"
set "extension=%%~xa"
)
for /f "usebackq tokens=*" %%a in (%file%) do (
if !lineCounter! gtr !limit! (
set splitFile=!name!_part!filenameCounter!!extension!
set /a filenameCounter=!filenameCounter! + 1
set lineCounter=1
echo Created !splitFile!.
)
cls
echo Adding Line !splitFile! - !lineCounter!
echo %%a>> !splitFile!
set /a lineCounter=!lineCounter! + 1
)
echo Done!
goto end
:syntaxerror
Echo Syntax: %0 -f Filename -n "Number Of Rows Per File"
goto end
:nofile
echo %2 does not exist
goto end
:end
You can use the following command:
svn status -q
According to svnbook:
With --quiet (-q), it prints only summary information about locally modified items.
WARNING: The output of this command only shows your modification. So I suggest to do a svn up
to get latest version of the file and then use svn status -q
to get the files you have modified.
My search led me here so might as well add my two cents worth of idea. If you are using Monkey friendly Twitter Bootstrap modal then you can do something like this:
var dialog = new BootstrapDialog({
id: 'myDialog',
title: 'Title',
closable: false,
// whatever you like configuration here...
});
dialog.realize();
if (isContentAYoutubeVideo()) {
dialog.getModalDialog().css('width', '80%'); // set the width to whatever you like
}
dialog.open();
Hope this helps.
It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.
4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.
If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.
There is no v4.5 shown in the gui, and typically you don't need to manually specify v4.5 since it's an in-place update. However, you can set it explicitly with appcmd like this:
appcmd set apppool /apppool.name: [App Pool Name] /managedRuntimeVersion:v4.5
Appcmd is located in %windir%\System32\inetsrv
. This helped me to fix an issue with Web Deploy, where it was throwing an ERROR_APPPOOL_VERSION_MISMATCH error after upgrading from v4.0 to v4.5.
Google java http client has nice API for http requests. You can easily add JSON support etc. Although for simple request it might be overkill.
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import java.io.IOException;
import java.io.InputStream;
public class Network {
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public void getRequest(String reqUrl) throws IOException {
GenericUrl url = new GenericUrl(reqUrl);
HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(url);
HttpResponse response = request.execute();
System.out.println(response.getStatusCode());
InputStream is = response.getContent();
int ch;
while ((ch = is.read()) != -1) {
System.out.print((char) ch);
}
response.disconnect();
}
}
Another option is to pass the single quote as an awk variable:
awk -v q=\' 'BEGIN {FS=" ";} {printf "%s%s%s ", q, $1, q}'
Simpler example with string concatenation:
# Prints 'test me', *including* the single quotes.
$ awk -v q=\' '{print q $0 q }' <<<'test me'
'test me'
//c++0x too
std::map<int,int> mapints;
std::vector<int> vints;
for(auto const& imap: mapints)
vints.push_back(imap.first);
Both are fine, but only the first one will allow you to inspect the Exception itself.
Both swallow the Exception, and you should only catch exceptions to do something meaningfull. Hiding a problem is not meaningful!
For all to those having problems with this i did this tutorial:
How to install Imagemagick and Php module Imagick on ubuntu?
i did this 7 simple steps:
Update libraries, and packages
apt-get update
Remove obsolete things
apt-get autoremove
For the libraries of ImageMagick
apt-get install libmagickwand-dev
for the core class Imagick
apt-get install imagemagick
For create the binaries, and conections in beetween
pecl install imagick
Append the extension to your php.ini
echo "extension=imagick.so" >> /etc/php5/apache2/php.ini
Restart Apache
service apache2 restart
I found a problem. PHP searches for .so files in a folder called /usr/lib/php5/20100525, and the imagick.so is stored in a folder called /usr/lib/php5/20090626. So you have to copy the file to that folder.
if what you need is the width and height of the frame in the circle, why not pass the DrawFrame width and height into the DrawCircle constructor:
public DrawCircle(int w, int h){
this.w = w;
this.h = h;
diBig = 300;
diSmall = 10;
maxRad = (diBig/2) - diSmall;
xSq = 50;
ySq = 50;
xPoint = 200;
yPoint = 200;
}
you could also add a couple new methods to DrawCircle:
public void setWidth(int w)
this.w = w;
public void setHeight(int h)
this.h = h;
or even:
public void setDimension(Dimension d) {
w=d.width;
h=d.height;
}
if you go down this route, you will need to update DrawFrame to make a local var of the DrawCircle on which to call these methods.
edit:
when changing the DrawCircle constructor as described at the top of my post, dont forget to add the width and height to the call to the constructor in DrawFrame:
public class DrawFrame extends JFrame {
public DrawFrame() {
int width = 400;
int height = 400;
setTitle("Frame");
setSize(width, height);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
Container contentPane = getContentPane();
//pass in the width and height to the DrawCircle contstructor
contentPane.add(new DrawCircle(width, height));
}
}
It took me a while to locate why the sample application works but mine don't.
The library (Foundation.Framework) that the author refer to is the system library (from OS) where the iphone sdk (I am using 3.0) is not support any more.
Therefore the sample application (from about.com, http://www.appsamuck.com/day1.html) works but ours don't.
ast.literal_eval
(located in ast.py
) parses the tree with ast.parse
first, then it evaluates the code with quite an ugly recursive function, interpreting the parse tree elements and replacing them with their literal equivalents. Unfortunately the code is not at all expandable, so to add Decimal
to the code you need to copy all the code and start over.
For a slightly easier approach, you can use ast.parse
module to parse the expression, and then the ast.NodeVisitor
or ast.NodeTransformer
to ensure that there is no unwanted syntax or unwanted variable accesses. Then compile with compile
and eval
to get the result.
The code is a bit different from literal_eval
in that this code actually uses eval
, but in my opinion is simpler to understand and one does not need to dig too deep into AST trees. It specifically only allows some syntax, explicitly forbidding for example lambdas, attribute accesses (foo.__dict__
is very evil), or accesses to any names that are not deemed safe. It parses your expression fine, and as an extra I also added Num
(float and integer), list and dictionary literals.
Also, works the same on 2.7 and 3.3
import ast
import decimal
source = "(Decimal('11.66985'), Decimal('1e-8'),"\
"(1,), (1,2,3), 1.2, [1,2,3], {1:2})"
tree = ast.parse(source, mode='eval')
# using the NodeTransformer, you can also modify the nodes in the tree,
# however in this example NodeVisitor could do as we are raising exceptions
# only.
class Transformer(ast.NodeTransformer):
ALLOWED_NAMES = set(['Decimal', 'None', 'False', 'True'])
ALLOWED_NODE_TYPES = set([
'Expression', # a top node for an expression
'Tuple', # makes a tuple
'Call', # a function call (hint, Decimal())
'Name', # an identifier...
'Load', # loads a value of a variable with given identifier
'Str', # a string literal
'Num', # allow numbers too
'List', # and list literals
'Dict', # and dicts...
])
def visit_Name(self, node):
if not node.id in self.ALLOWED_NAMES:
raise RuntimeError("Name access to %s is not allowed" % node.id)
# traverse to child nodes
return self.generic_visit(node)
def generic_visit(self, node):
nodetype = type(node).__name__
if nodetype not in self.ALLOWED_NODE_TYPES:
raise RuntimeError("Invalid expression: %s not allowed" % nodetype)
return ast.NodeTransformer.generic_visit(self, node)
transformer = Transformer()
# raises RuntimeError on invalid code
transformer.visit(tree)
# compile the ast into a code object
clause = compile(tree, '<AST>', 'eval')
# make the globals contain only the Decimal class,
# and eval the compiled object
result = eval(clause, dict(Decimal=decimal.Decimal))
print(result)
By what you wrote, you are missing a critical piece of understanding: the difference between a class and an object. __init__
doesn't initialize a class, it initializes an instance of a class or an object. Each dog has colour, but dogs as a class don't. Each dog has four or fewer feet, but the class of dogs doesn't. The class is a concept of an object. When you see Fido and Spot, you recognise their similarity, their doghood. That's the class.
When you say
class Dog:
def __init__(self, legs, colour):
self.legs = legs
self.colour = colour
fido = Dog(4, "brown")
spot = Dog(3, "mostly yellow")
You're saying, Fido is a brown dog with 4 legs while Spot is a bit of a cripple and is mostly yellow. The __init__
function is called a constructor, or initializer, and is automatically called when you create a new instance of a class. Within that function, the newly created object is assigned to the parameter self
. The notation self.legs
is an attribute called legs
of the object in the variable self
. Attributes are kind of like variables, but they describe the state of an object, or particular actions (functions) available to the object.
However, notice that you don't set colour
for the doghood itself - it's an abstract concept. There are attributes that make sense on classes. For instance, population_size
is one such - it doesn't make sense to count the Fido because Fido is always one. It does make sense to count dogs. Let us say there're 200 million dogs in the world. It's the property of the Dog class. Fido has nothing to do with the number 200 million, nor does Spot. It's called a "class attribute", as opposed to "instance attributes" that are colour
or legs
above.
Now, to something less canine and more programming-related. As I write below, class to add things is not sensible - what is it a class of? Classes in Python make up of collections of different data, that behave similarly. Class of dogs consists of Fido and Spot and 199999999998 other animals similar to them, all of them peeing on lampposts. What does the class for adding things consist of? By what data inherent to them do they differ? And what actions do they share?
However, numbers... those are more interesting subjects. Say, Integers. There's a lot of them, a lot more than dogs. I know that Python already has integers, but let's play dumb and "implement" them again (by cheating and using Python's integers).
So, Integers are a class. They have some data (value), and some behaviours ("add me to this other number"). Let's show this:
class MyInteger:
def __init__(self, newvalue)
# imagine self as an index card.
# under the heading of "value", we will write
# the contents of the variable newvalue.
self.value = newvalue
def add(self, other):
# when an integer wants to add itself to another integer,
# we'll take their values and add them together,
# then make a new integer with the result value.
return MyInteger(self.value + other.value)
three = MyInteger(3)
# three now contains an object of class MyInteger
# three.value is now 3
five = MyInteger(5)
# five now contains an object of class MyInteger
# five.value is now 5
eight = three.add(five)
# here, we invoked the three's behaviour of adding another integer
# now, eight.value is three.value + five.value = 3 + 5 = 8
print eight.value
# ==> 8
This is a bit fragile (we're assuming other
will be a MyInteger), but we'll ignore now. In real code, we wouldn't; we'd test it to make sure, and maybe even coerce it ("you're not an integer? by golly, you have 10 nanoseconds to become one! 9... 8....")
We could even define fractions. Fractions also know how to add themselves.
class MyFraction:
def __init__(self, newnumerator, newdenominator)
self.numerator = newnumerator
self.denominator = newdenominator
# because every fraction is described by these two things
def add(self, other):
newdenominator = self.denominator * other.denominator
newnumerator = self.numerator * other.denominator + self.denominator * other.numerator
return MyFraction(newnumerator, newdenominator)
There's even more fractions than integers (not really, but computers don't know that). Let's make two:
half = MyFraction(1, 2)
third = MyFraction(1, 3)
five_sixths = half.add(third)
print five_sixths.numerator
# ==> 5
print five_sixths.denominator
# ==> 6
You're not actually declaring anything here. Attributes are like a new kind of variable. Normal variables only have one value. Let us say you write colour = "grey"
. You can't have another variable named colour
that is "fuchsia"
- not in the same place in the code.
Arrays solve that to a degree. If you say colour = ["grey", "fuchsia"]
, you have stacked two colours into the variable, but you distinguish them by their position (0, or 1, in this case).
Attributes are variables that are bound to an object. Like with arrays, we can have plenty colour
variables, on different dogs. So, fido.colour
is one variable, but spot.colour
is another. The first one is bound to the object within the variable fido
; the second, spot
. Now, when you call Dog(4, "brown")
, or three.add(five)
, there will always be an invisible parameter, which will be assigned to the dangling extra one at the front of the parameter list. It is conventionally called self
, and will get the value of the object in front of the dot. Thus, within the Dog's __init__
(constructor), self
will be whatever the new Dog will turn out to be; within MyInteger
's add
, self
will be bound to the object in the variable three
. Thus, three.value
will be the same variable outside the add
, as self.value
within the add
.
If I say the_mangy_one = fido
, I will start referring to the object known as fido
with yet another name. From now on, fido.colour
is exactly the same variable as the_mangy_one.colour
.
So, the things inside the __init__
. You can think of them as noting things into the Dog's birth certificate. colour
by itself is a random variable, could contain anything. fido.colour
or self.colour
is like a form field on the Dog's identity sheet; and __init__
is the clerk filling it out for the first time.
Any clearer?
EDIT: Expanding on the comment below:
You mean a list of objects, don't you?
First of all, fido
is actually not an object. It is a variable, which is currently containing an object, just like when you say x = 5
, x
is a variable currently containing the number five. If you later change your mind, you can do fido = Cat(4, "pleasing")
(as long as you've created a class Cat
), and fido
would from then on "contain" a cat object. If you do fido = x
, it will then contain the number five, and not an animal object at all.
A class by itself doesn't know its instances unless you specifically write code to keep track of them. For instance:
class Cat:
census = [] #define census array
def __init__(self, legs, colour):
self.colour = colour
self.legs = legs
Cat.census.append(self)
Here, census
is a class-level attribute of Cat
class.
fluffy = Cat(4, "white")
spark = Cat(4, "fiery")
Cat.census
# ==> [<__main__.Cat instance at 0x108982cb0>, <__main__.Cat instance at 0x108982e18>]
# or something like that
Note that you won't get [fluffy, sparky]
. Those are just variable names. If you want cats themselves to have names, you have to make a separate attribute for the name, and then override the __str__
method to return this name. This method's (i.e. class-bound function, just like add
or __init__
) purpose is to describe how to convert the object to a string, like when you print it out.
try adding this to your js function:
var outputvar = document.getElementById("your_div_id_inside_html_form");
outputvar.innerHTML='<input id=id_to_send_to_php value='+your_js_var+'>';
Later in html:
<div id="id_you_choosed_for_outputvar"></div>
this div will contain the js var to be passed through a form to another js function or to php, remember to place it inside your html form!. This solution is working fine for me.
In your specific geolocation case you can try adding the following to function showPosition(position):
var outputlon = document.getElementById("lon1");
outputlon.innerHTML = '<input id=lon value='+lon+'>';
var outputlat = document.getElementById("lat1");
outputlat.innerHTML = '<input id=lat value='+lat+'>';
later add these div to your html form:
<div id=lat1></div>
<div id=lon1></div>
In these div you'll get latitude and longitude as input values for your php form, you would better hide them using css (show only the marker on a map if used) in order to avoid users to change them before to submit, and set your database to accept float values with lenght 10,7.
Hope this will help.
Add a time stamp <img src="picture.jpg?t=<?php echo time();?>">
will always give your file a random number at the end and stop it caching
I just came out with this:
input[type="checkbox"] {display:none;}_x000D_
input[type="checkbox"] + label:before {content:"?";}_x000D_
input:checked + label:before {content:"?";}_x000D_
label:hover {color:blue;}
_x000D_
<input id="check" type="checkbox" /><label for="check">Checkbox</label>
_x000D_
Of course, thanks to this, you can change the value of content
to your needs and use an image if you wish or use another font...
The main interest here is that:
The checkbox size stays proportional to the text size
You can control the aspect, the color, the size of the checkbox
No extra HTML needed !
Only 3 lines of CSS needed (the last one is just to give you ideas)
Edit:
As pointed out in the comment, the checkbox won't be accessible by key navigation. You should probably add tabindex=0
as a property for your label to make it focusable.
You want to do the check for undefined
first. If you do it the other way round, it will generate an error if the array is undefined.
if (array === undefined || array.length == 0) {
// array empty or does not exist
}
This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null
values, other types of objects with a length
property, etc. It is also not very idiomatic JavaScript.
The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length
property.
if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ? do not attempt to process array
}
To break it down:
Array.isArray()
, unsurprisingly, checks whether its argument is an array. This weeds out values like null
, undefined
and anything else that is not an array.
Note that this will also eliminate array-like objects, such as the arguments
object and DOM NodeList
objects. Depending on your situation, this might not be the behavior you're after.
The array.length
condition checks whether the variable's length
property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0
or array.length !== 0
are not required here.
The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.
In those cases, I tend to go for the following, more idiomatic JavaScript:
if (!array || !array.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or, more frequently, its inverse:
if (array && array.length) {
// array and array.length are truthy
// ? probably OK to process array
}
With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:
if (!array?.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or the opposite:
if (array?.length) {
// array and array.length are truthy
// ? probably OK to process array
}
<?php
function check_keys_exists($keys_str = "", $arr = array()){
$return = false;
if($keys_str != "" and !empty($arr)){
$keys = explode(',', $keys_str);
if(!empty($keys)){
foreach($keys as $key){
$return = array_key_exists($key, $arr);
if($return == false){
break;
}
}
}
}
return $return;
}
//run demo
$key = 'a,b,c';
$array = array('a'=>'aaaa','b'=>'ccc','c'=>'eeeee');
var_dump( check_keys_exists($key, $array));
Alternatively, if you wish to specify the background color value in rgb notation then try
document.getElementById("yourid").style.backgroundColor = 'rgb(' + a + ',' + b + ',' + c + ')';
where a,b,c are the color values
Example:
document.getElementById("yourid").style.backgroundColor = 'rgb(224,224,224)';
If you want pure css, without the letter "x"....
Here are some awesome experimental icons that include an "x" in a circle that is made with CSS: http://nicolasgallagher.com/pure-css-gui-icons/demo/
If you really want to remove all of the repository, leaving only the working directory then it should be as simple as this.
rm -rf .git
The usual provisos about rm -rf
apply. Make sure you have an up to date backup and are absolutely sure that you're in the right place before running the command. etc., etc.
I have seen comments in INI files, so yes. Please refer to this Wikipedia article. I could not find an official specification, but that is the correct syntax for comments, as many game INI files had this as I remember.
Edit
The API returns the Value and the Comment (forgot to mention this in my reply), just construct and example INI file and call the API on this (with comments) and you can see how this is returned.
I too had the same problem in VWD 2010 and, by chance, I had two controls. One was available in code behind and one wasn't accessible. I thought that the order of statements in the controls was causing the issue. I put 'runat' before 'SelectedDate' and that seemed to fix it. When I put 'runat' after 'SelectedDate' it still worked! Unfortunately, I now don't know why it didn't work and haven't got the original that didn't work.
These now all work:-
<asp:Calendar ID="calDateFrom" SelectedDate="08/02/2011" SelectionMode="Day" runat="server"></asp:Calendar>
<asp:Calendar runat="server" SelectionMode="Day" SelectedDate="08/15/2011 12:00:00 AM" ID="Calendar1" VisibleDate="08/03/2011 12:00:00 AM"></asp:Calendar>
<asp:Calendar SelectionMode="Day" SelectedDate="08/31/2011 12:00:00 AM" runat="server" ID="calDateTo"></asp:Calendar>
I've moved what I've done from the question to an answer where more people are likely to see it.
What I've done is to have the creation endpoints at the nested endpoint, The canonical endpoint for modifying or querying an item is not at the nested resource.
So in this example (just listing the endpoints that change a resource)
POST
/companies/
creates a new company returns a link to the created company.POST
/companies/{companyId}/departments
when a department is put creates the new department returns a link to /departments/{departmentId}
PUT
/departments/{departmentId}
modifies a departmentPOST
/departments/{deparmentId}/employees
creates a new employee returns a link to /employees/{employeeId}
So there are root level resources for each of the collections. However the create is in the owning object.
Convert one of them to a double first. This form works in many languages:
real_result = (int_numerator + 0.0) / int_denominator
This behaviour is implementation specific. To guarantee the correctness of the iterator you should use "it = numbers.erase(it);" statement if you need to delete the element and simply incerement iterator in other case.
Try the below method in a singleton class:
-(NSString *)typeOfDevice
{
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
CGSize result = [[UIScreen mainScreen] bounds].size;
if(result.height == 480)
{
return @"Iphone";
}
if(result.height == 568)
{
return @"Iphone 5";
}
}
else{
return @"Ipad";;
}
return @"Iphone";
}
I would still recommend Firebug. Not only it can debug JS within your JSP files, it can enhance debugging experience with addons like JS Deminifier
(if your production JS is minified), FireQuery
, FireRainbow
and more.
There is also Firebug lite which is nothing but a bookmarklet. It lets you do limited things but still is useful.
Chrome as a developer console built-in that would let you modify javascript.
Using these tools, you should be able to inject your own JS too.
[[NSBundle mainBundle] pathForResource:@"marqueeMusic" ofType:@"html"];
It may be late but if the file from pathForResource
is nil
you should add it in the Build Phases > Copy Bundle Resources
.
The original order is in fact backwards. Certs should be followed by the issuing cert until the last cert is issued by a known root per IETF's RFC 5246 Section 7.4.2
This is a sequence (chain) of certificates. The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it.
See also SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch for troubleshooting techniques.
But I still don't know why they wrote the spec so that the order matters.