First what you have to do, before changing web.xml is to make sure your ManagedBean implements Serializable
:
@ManagedBean
@ViewScoped
public class Login implements Serializable {
}
Especially if you use MyFaces
I'm sending files(array) using formData in vuejs
for me below code is working
if(this.requiredDocumentForUploads.length > 0) {
this.requiredDocumentForUploads.forEach(file => {
var name = file.attachment_type // attachment_type is using for naming
if(document.querySelector("[name=" + name + "]").files.length > 0) {
formData.append("requiredDocumentForUploadsNew[" + name + "]", document.querySelector("[name=" + name + "]").files[0])
}
})
}
<select ng-model="output">
<option ng-repeat="(key,val) in dictionary" value="{{key}}">{{val}}</option>
</select>
if not exists (select * from sysobjects where name='cars' and xtype='U')
create table cars (
Name varchar(64) not null
)
go
The above will create a table called cars
if the table does not already exist.
Change the wrapping from "onload
" to "No wrap - in <body>
"
The function defined has a different scope.
nvm was designed for Linux. nvmw, which is completely different broke around node v0.10.30. Try NVM for Windows.
Without using 'length' you can do it like this:
if ($('input[type=checkbox]').is(":checked")) {
//any one is checked
}
else {
//none is checked
}
I could not get anything to work I ended up just using powershell to start bat scripts .. sometimes even start cmd /c does not work not sure why .. I even tried stuff like start cmd /c notepad & exit
start-Process "c:\BACKUP\PRIVATE\MobaXterm_Portable\MobaXterm_Portable.bat" -WindowStyle Hidden
@@IDENTITY
Is a system function that returns the last-inserted identity value.
foo="hello world"
echo ${foo%?}
hello worl
I used the command line client prompt and to clear the screen I typed:-
system cls
In my case a has to add my classes, when building the SessionFactory
, with addAnnotationClass
Configuration configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration
.addAnnotatedClass(MyEntity1.class)
.addAnnotatedClass(MyEntity2.class)
.buildSessionFactory(builder.build());
I use IEnum<string>.ToArray<string>().Length
and it works fine.
JavaScript has associative arrays.
Here is a working snippet.
<script type="text/javascript">
var myArray = [];
myArray['thank'] = 'you';
myArray['no'] = 'problem';
console.log(myArray);
</script>
_x000D_
They are simply called objects.
Just set the opacity for the inner table. You can do inline CSS if you want it just for a specific table element, so it doesn't apply to the entire table.
style="opacity: 0%;"
print_r(json_decode('{"t":"\u00ed"}')); // -> stdClass Object ( [t] => í )
This is the problem
double a[] = null;
Since a
is null
, NullPointerException
will arise every time you use it until you initialize it. So this:
a[i] = var;
will fail.
A possible solution would be initialize it when declaring it:
double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7
IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.
java.lang.NullPointerException
This exception means there's a variable with null
value being used. How to solve? Just make sure the variable is not null
before being used.
at twoten.TwoTenB.(TwoTenB.java:29)
This line has two parts:
<init>
method in class TwoTenB
declared in package twoten
. When you encounter an error message with SomeClassName.<init>
, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).a[i] = var;
.From this line, other lines will be similar to tell you where the error arose. So when reading this:
at javapractice.JavaPractice.main(JavaPractice.java:32)
It means that you were trying to instantiate a TwoTenB
object reference inside the main
method of your class JavaPractice
declared in javapractice
package.
From a post by Robert Martin in comp.object:
Association represents the ability of one instance to send a message to another instance. This is typically implemented with a pointer or reference instance variable, although it might also be implemented as a method argument, or the creation of a local variable.
//[Example:]
//|A|----------->|B|
class A
{
private:
B* itsB;
};
Aggregation [...] is the typical whole/part relationship. This is exactly the same as an association with the exception that instances cannot have cyclic aggregation relationships (i.e. a part cannot contain its whole).
//[Example:]
//|Node|<>-------->|Node|
class Node
{
private:
vector<Node*> itsNodes;
};
The fact that this is aggregation means that the instances of Node cannot form a cycle. Thus, this is a Tree of Nodes not a graph of Nodes.
Composition [...] is exactly like Aggregation except that the lifetime of the 'part' is controlled by the 'whole'. This control may be direct or transitive. That is, the 'whole' may take direct responsibility for creating or destroying the 'part', or it may accept an already created part, and later pass it on to some other whole that assumes responsibility for it.
//[Example:]
//|Car|<#>-------->|Carburetor|
class Car
{
public:
virtual ~Car() {delete itsCarb;}
private:
Carburetor* itsCarb
};
UPDATE: As TimK pointed out, this isn't needed with jquery 1.5.2 any more. But if you want to add custom headers or allow the use of credentials (username, password, or cookies, etc), read on.
I think I found the answer! (4 hours and a lot of cursing later)
//This does not work!!
Access-Control-Allow-Headers: *
You need to manually specify all the headers you will accept (at least that was the case for me in FF 4.0 & Chrome 10.0.648.204).
jQuery's $.ajax method sends the "x-requested-with" header for all cross domain requests (i think its only cross domain).
So the missing header needed to respond to the OPTIONS request is:
//no longer needed as of jquery 1.5.2
Access-Control-Allow-Headers: x-requested-with
If you are passing any non "simple" headers, you will need to include them in your list (i send one more):
//only need part of this for my custom header
Access-Control-Allow-Headers: x-requested-with, x-requested-by
So to put it all together, here is my PHP:
// * wont work in FF w/ Allow-Credentials
//if you dont need Allow-Credentials, * seems to work
header('Access-Control-Allow-Origin: http://www.example.com');
//if you need cookies or login etc
header('Access-Control-Allow-Credentials: true');
if ($this->getRequestMethod() == 'OPTIONS')
{
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Max-Age: 604800');
//if you need special headers
header('Access-Control-Allow-Headers: x-requested-with');
exit(0);
}
Non-recursive solution, no imports:
def factorial(x):
return eval(' * '.join(map(str, range(1, x + 1))))
Your use case would be :
$ArrayCollectionOfActiveUsers = $customer->users->filter(function($user) {
return $user->getActive() === TRUE;
});
if you add ->first() you'll get only the first entry returned, which is not what you want.
@ Sjwdavies You need to put () around the variable you pass to USE. You can also shorten as in_array return's a boolean already:
$member->getComments()->filter( function($entry) use ($idsToFilter) {
return in_array($entry->getId(), $idsToFilter);
});
Pretty easy to overlook like I did, but don't forget to use UITapGestureRecognizer
rather than UIGestureRecognizer
.
You want to do $arrayOfString[0].Title -eq $myPbiject.item(0).Title
-match
is for regex matching ( the second argument is a regex )
There are pretty good solutions here but they don't help to understand why the problem actually happens.
But it's very simple, you just need to understand how logic OR ||
works. Whole expression will evaluate to true
when either of its sides evaluates to true
.
Now let's look at your case. Assume whole details.Payment[0].Status
is Status
and it's a number for brevity. Then we have Status != 0 || Status != 1 || ...
.
Imagine Status = 1
:
( 1 != 0 || 1 != 1 || ... ) =
( true || false || ... ) =
( true || ... ) = ... = true
Now imagine Status = 0
:
( 0 != 0 || 0 != 1 || ... ) =
( false || true || ... ) =
( true || ... ) = ... = true
As you it doesn't even matter what you have as ...
as logical OR
of first two expressions gives you true
which will be the result of the full expression.
What you actually need is logical AND
&&
that will be true only if both its sides are true
.
If you are running against IIS rather than the VS webdev server, ensure that Index.aspx is one of your default files and that directory browsing is turned off.
Not PHP I'm afraid, but Zope and Plone use something similar to SASS called DTML to achieve this. It's incredibly useful in CMS's.
Upfront Systems has a good example of its use in Plone.
I solved with this loop, where repeat is an integer that represents the loops's number
repeat=10
for n in $(seq $repeat);
do
command1
command2
done
Use iloc
:
df = df.iloc[3:]
will give you a new df without the first three rows.
First, do not use DataOutputStream
unless it’s really necessary. Second:
Socket socket = new Socket("host", port);
OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write(message);
Of course this lacks any error checking but this should get you going. The JDK API Javadoc is your friend and can help you a lot.
Yes, you could append ;Connection Timeout=30
to your connection string and specify the value you wish.
The timeout value set in the Connection Timeout
property is a time expressed in seconds. If this property isn't set, the timeout value for the connection is the default value (15 seconds).
Moreover, setting the timeout value to 0
, you are specifying that your attempt to connect waits an infinite time. As described in the documentation, this is something that you shouldn't set in your connection string:
A value of 0 indicates no limit, and should be avoided in a ConnectionString because an attempt to connect waits indefinitely.
It is possible, but only if the struct you're initializing is a POD (plain old data) struct. It cannot contain any methods, constructors, or even default values.
The solution I came up with is fragile; it relies on django's naming convention for foreign keys.
USE information_schema;
tee mysql_output
SELECT * FROM TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_SCHEMA = 'database_name';
notee
Then, in the shell,
grep 'refs_tablename_id' mysql_output
find . -name 'Lemon*.mp3' -print0 | xargs -0 -i mplayer '{}'
This helped in my case to delete different files with spaces. It should work too with mplayer. The necessary trick is the quotes. (Tested on Linux Xubuntu 14.04.)
We were having similar issues with Font Awesome on a static "cookie-less" domain when reading fonts from the "cookie domain" (www.domain.tld) and this post was our hero. See here: How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?
For the copy/paste-r types (and to give some props) I pieced this together from all the contributions and added it to the top of the .htaccess file of the site root:
<IfModule mod_headers.c>
<IfModule mod_rewrite.c>
SetEnvIf Origin "http(s)?://(.+\.)?(othersite\.com|mywebsite\.com)(:\d{1,5})?$" CORS=$0
Header set Access-Control-Allow-Origin "%{CORS}e" env=CORS
Header merge Vary "Origin"
</IfModule>
</IfModule>
Super Secure, Super Elegant. Love it: You don't have to open up your servers bandwidth to resource thieves / hot-link-er types.
Props to:@Noyo @DaveRandom @pratap-koritala
(I tried to leave this as a comment to the accepted answer, but I can't do that yet)
Every derived table (AKA sub-query) must indeed have an alias. I.e. each query in brackets must be given an alias (AS whatever
), which can the be used to refer to it in the rest of the outer query.
SELECT ID FROM (
SELECT ID, msisdn FROM (
SELECT * FROM TT2
) AS T
) AS T
In your case, of course, the entire query could be replaced with:
SELECT ID FROM TT2
I've spend more than a day trying to make JMX to work from outside localhost. It seems that SUN/Oracle failed to provide a good documentation on this.
Be sure that the following command returns you a real IP or HOSTNAME. If it does return something like 127.0.0.1, 127.0.1.1 or localhost it will not work and you will have to update /etc/hosts
file.
hostname -i
Here is the command needed to enable JMX even from outside
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.port=1100
-Djava.rmi.server.hostname=myserver.example.com
Where as you assumed, myserver.example.com must match what hostname -i
returns.
Obviously, you need to be sure that the firewall does not block you, but I'm almost sure that this is not your problem, the problem being the last parameter that is not documented.
@bku_drytt's solution didn't do it for me.
I solved it by additionally changing every occurence of 14.0
to 12.0
and v140
to v120
manually in the .vcxproj files.
Then it compiled!
// service: (nothing special here)
myApp.service('myService', function() {
return { someVariable:'abc123' };
});
// ctrl:
myApp.controller('MyCtrl', function($scope, myService) {
$scope.someVariable = myService.someVariable;
// watch the service and update this ctrl...
$scope.$watch(function(){
return myService.someVariable;
}, function(newValue){
$scope.someVariable = newValue;
});
});
In Visual Studio UML sequence this can also be described as fragments which is nicely documented here: https://msdn.microsoft.com/en-us/library/dd465153.aspx
Something like the following will allow for multiple transitions simultaneously:
-webkit-transition: color .2s linear, text-shadow .2s linear;
-moz-transition: color .2s linear, text-shadow .2s linear;
-o-transition: color .2s linear, text-shadow .2s linear;
transition: color .2s linear, text-shadow .2s linear;
Example: http://jsbin.com/omogaf/2
Try starting MySQL and Apache in Xampp. Verify Port Number assigned to Apache (By default it should be 80). Now load localhost/phpmyadmin
. It solved my problem.
How about using a grid? it's 2019 and support is reasonable
body {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.content {_x000D_
display: grid;_x000D_
background-color: bisque;_x000D_
height: 100vh;_x000D_
place-items: center;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<div class="content">_x000D_
<form action="#" method="POST">_x000D_
<fieldset>_x000D_
<legend>Information:</legend>_x000D_
<label for="name">Name:</label>_x000D_
<input type="text" id="name" name="user_name">_x000D_
</fieldset>_x000D_
<button type="button" formmethod="POST" formaction="#">Submit</button>_x000D_
</form>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Instead of using pull-right
class, it is better to use text-right
class in the column, because pull-right
creates problems sometimes while resizing the page.
Try to execute below command in your terminal :
mysql -h localhost -P 3306 -u root -p
If you successfully connect to your database, then same thing has to happen with Mysql Workbench
.
If you are unable to connect then I think 3306
port is acquired by another process.
Find which process running on 3306
port. If required, give admin privileges using sudo
.
netstat -lnp | grep 3306
Kill/stop that process and restart your MySQL server. You are good to go.
Execute below command to find my.cnf
file in macbook.
mysql --help | grep cnf
You can change MySQL
port to any available port in your system. But after that, make sure you restart MySQL
server.
From CLI:
$ su - postgres
$ psql template1
template1=# CREATE USER tester WITH PASSWORD 'test_password';
template1=# GRANT ALL PRIVILEGES ON DATABASE "test_database" to tester;
template1=# \q
PHP (as tested on localhost, it works as expected):
$connString = 'port=5432 dbname=test_database user=tester password=test_password';
$connHandler = pg_connect($connString);
echo 'Connected to '.pg_dbname($connHandler);
Probably something like this? (UNTESTED)
Sub Sample()
Dim strWB4, strMyMacro
strMyMacro = "Sheet1.my_macro_name"
'
'~~> Rest of Code
'
'loop through the folder and get the file names
For Each Fil In FLD.Files
Set x4WB = x1.Workbooks.Open(Fil)
x4WB.Application.Visible = True
x1.Run strMyMacro
x4WB.Close
Do Until IsWorkBookOpen(Fil) = False
DoEvents
Loop
Next
'
'~~> Rest of Code
'
End Sub
'~~> Function to check if the file is open
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
There are two different methods for iPad and iPhone platforms, so you need to implement both:
segue.
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
// Selection handler (for horizontal iPad)
[self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
// Segue (for iPhone and vertical iPad)
[self performSegueWithIdentifier:"showDetail" sender:self];
Use git log
to find the revision you want to rollback to, and take note of the commit hash. After that, you have 2 options:
If you plan to commit anything after that revision, I recommend you to checkout to a new branch: git checkout -b <new_branch_name> <hash>
If you don't plan to commit anything after that revision, you can simply checkout without a branch: git checkout <hash>
- NOTE: This will put your repository in a 'detached HEAD' state, which means its currently not attached to any branch - then you'll have some extra work to merge new commits to an actual branch.
Example:
$ git log
commit 89915b4cc0810a9c9e67b3706a2850c58120cf75
Author: Jardel Weyrich <suppressed>
Date: Wed Aug 18 20:15:01 2010 -0300
Added a custom extension.
commit 4553c1466c437bdd0b4e7bb35ed238cb5b39d7e7
Author: Jardel Weyrich <suppressed>
Date: Wed Aug 18 20:13:48 2010 -0300
Missing constness.
$ git checkout 4553c1466c437bdd0b4e7bb35ed238cb5b39d7e7
Note: moving to '4553c1466c437bdd0b4e7bb35ed238cb5b39d7e7'
which isn't a local branch
If you want to create a new branch from this checkout, you may do so
(now or later) by using -b with the checkout command again. Example:
git checkout -b <new_branch_name>
HEAD is now at 4553c14... Missing constness.
That way you don't lose any informations, thus you can move to a newer revision when it becomes stable.
Be sure to put tilde and forward slash(~/) when CDN is the root directory. I think it's an issue in IIS
Answered my own question:
IPv6 addresses are normally written as eight groups of four hexadecimal digits, where each group is separated by a colon (:).
So that's 39 characters max.
AFAIK, there is no a interactive option for output to file, there is a previous SO question related with this: Printing mongodb shell output to File
However, you can log all the shell session if you invoked the shell with tee command:
$ mongo | tee file.txt
MongoDB shell version: 2.4.2
connecting to: test
> printjson({this: 'is a test'})
{ "this" : "is a test" }
> printjson({this: 'is another test'})
{ "this" : "is another test" }
> exit
bye
Then you'll get a file with this content:
MongoDB shell version: 2.4.2
connecting to: test
> printjson({this: 'is a test'})
{ "this" : "is a test" }
> printjson({this: 'is another test'})
{ "this" : "is another test" }
> exit
bye
To remove all the commands and keep only the json output, you can use a command similar to:
tail -n +3 file.txt | egrep -v "^>|^bye" > output.json
Then you'll get:
{ "this" : "is a test" }
{ "this" : "is another test" }
int size=5;
int ar[size ]={O};
/* This operation gives an error -
variable sized array may not be
initialised. Then just try this.
*/
int size=5,i;
int ar[size];
for(i=0;i<size;i++)
{
ar[i]=0;
}
ListView.FocusedItem.Index
or you can use foreach loop like this
int index= -1;
foreach (ListViewItem itm in listView1.SelectedItems)
{
if (itm.Selected)
{
index= itm.Index;
}
}
I know it's late, but I thought it would be nice to clarify things: PyCharm and Conda and pip work well together.
Just manage Conda from the command line. PyCharm will automatically notice changes once they happen, just like it does with pip.
Create a new Conda environment:
conda create --name foo pandas bokeh
This environment lives under conda_root/envs/foo
. Your python interpreter is conda_root/envs/foo/bin/pythonX.X
and your all your site-packages are in conda_root/envs/foo/lib/pythonX.X/site-packages
. This is same directory structure as in a pip virtual environement. PyCharm sees no difference.
Now to activate your new environment from PyCharm go to file > settings > project > interpreter, select Add local in the project interpreter field (the little gear wheel) and hunt down your python interpreter. Congratulations! You now have a Conda environment with pandas and bokeh!
Now install more packages:
conda install scikit-learn
OK... go back to your interpreter in settings. Magically, PyCharm now sees scikit-learn!
And the reverse is also true, i.e. when you pip install another package in PyCharm, Conda will automatically notice. Say you've installed requests. Now list the Conda packages in your current environment:
conda list
The list now includes requests and Conda has correctly detected (3rd column) that it was installed with pip.
This is definitely good news for people like myself who are trying to get away from the pip/virtualenv installation problems when packages are not pure python.
NB: I run PyCharm pro edition 4.5.3 on Linux. For Windows users, replace in command line with in the GUI (and forward slashes with backslashes). There's no reason it shouldn't work for you too.
EDIT: PyCharm5 is out with Conda support! In the community edition too.
The advantages of CXF:
The advantages of Axis2:
In Summary: From above advantage items, it brings us to a good thoughts to compare Axis2 and CXF on their own merits. they all have different well-developed areas in a certain field, CXF is very configurable, integratable and has rich tool kits supported and close to Java community, Axis2 has taken an approach that makes it in many ways resemble an application server in miniature. it is across multiple programming languages. because its Independence, Axis2 lends itself towards web services that stand alone, independent of other applications, and offers a wide variety of functionality.
As a developer, we need to accord our perspective to choose the right one, whichever framework you choose, you’ll have the benefit of an active and stable open source community. In terms of performance, I did a test based the same functionality and configed in the same web container, the result shows that CXF performed little bit better than Axis2, the single case may not exactly reflect their capabilities and performance.
In some research articles, it reveals that Axis2's proprietary ADB databinding is a bit faster than CXF since it don’t have additional feature(WS-Security). Apache AXIS2 is relatively most used framework but Apache CXF scores over other Web Services Framework comparatively considering ease of development, current industry trend, performance, overall scorecard and other features (unless there is Web Services Orchestration support is explicitly needed, which is not required here)
The user
parameter of your callback is an array with find
. Use findOne
instead of find
when querying for a single instance.
User.findOne({username: oldUsername}, function (err, user) {
user.username = newUser.username;
user.password = newUser.password;
user.rights = newUser.rights;
user.save(function (err) {
if(err) {
console.error('ERROR!');
}
});
});
Download the Visual C++ Redistributable 2015
Updated links to VC++ file:
If you're using python 3.4.1 then you get a different answer to your question.
list = [1,2,3]
id(list[0])
id(list[1])
id(list[2])
returns:
1705950792
1705950808 # increased by 16
1705950824 # increased by 16
The integers -5
to 256
have a constant id, and on finding it multiple times its id does not change, unlike all other numbers before or after it that have different id's every time you find it.
The numbers from -5
to 256
have id's in increasing order and differ by 16
.
The number returned by id()
function is a unique id given to each item stored in memory and it is analogy wise the same as the memory location in C.
Mathcha is a sophisticated mathematics editor, but it can be used to render individual equations and save them as pure html, which you can then add to your documents as inline html OR you can save as SVG and insert as an image. https://www.mathcha.io/
Self plug: I have just released a new Java HTML parser: jsoup. I mention it here because I think it will do what you are after.
Its party trick is a CSS selector syntax to find elements, e.g.:
String html = "<html><head><title>First parse</title></head>"
+ "<body><p>Parsed HTML into a doc.</p></body></html>";
Document doc = Jsoup.parse(html);
Elements links = doc.select("a");
Element head = doc.select("head").first();
See the Selector javadoc for more info.
This is a new project, so any ideas for improvement are very welcome!
The issue was that the file I was trying to import was so large that IntelliJ wouldn't run any CodeInsights on it.
Setting the idea.max.intellisense.filesize
option to a higher value as per the instructions on this answer resolved my issue.
You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:
/**
* Used to stitch together functional operators into a chain.
* @method pipe
* @return {Observable} the Observable result of all of the operators having
* been called in the order they were passed in.
*
* @example
*
* import { map, filter, scan } from 'rxjs/operators';
*
* Rx.Observable.interval(1000)
* .pipe(
* filter(x => x % 2 === 0),
* map(x => x + x),
* scan((acc, x) => acc + x)
* )
* .subscribe(x => console.log(x))
*/
Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan()
, but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe()
to make a chain of those operators (see example above).
Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do()
. You can think of it as if observable was an array over time, then tap()
would be an equivalent to Array.forEach()
.
Another Simple way i found in Netbeans right click on your project>libraris click add jar/folder add your comm.jar and you done.
if you dont have comm.jar download it from >>> http://llk.media.mit.edu/projects/picdev/software/javaxcomm.zip
For that, you need to update the redis configuration file.By default, there is no any password for redis.
01) open redis configuration file
sudo vi /etc/redis/redis.conf
find requirepass field under SECURITY section and uncomment that field.Then set your password instead of "foobared"
# requirepass foobared
It should be like,
requirepass YOUR_PASSWORD
Then restart redis and start redis-cli.
If you need to check whether you have set the password correctly, you can run below commads in redis-cli.
sithara@sithara-X555UJ ~ $ redis-cli
127.0.0.1:6379> set key1 18
(error) NOAUTH Authentication required.
127.0.0.1:6379> auth admin
OK
127.0.0.1:6379> get key1
(nil)
127.0.0.1:6379> exit
sithara@sithara-X555UJ ~ $ redis-cli
127.0.0.1:6379> set key1 18
(error) NOAUTH Authentication required.
127.0.0.1:6379> auth admin
OK
127.0.0.1:6379> set key2 check
OK
127.0.0.1:6379> get key2
"check"
127.0.0.1:6379> get key1
(nil)
127.0.0.1:6379> set key1 20
OK
127.0.0.1:6379> get key1
"20"
127.0.0.1:6379> exit
`
It happens when you have a file with the same name as Makefile target name in the directory where the Makefile is present.
Perhaps you could use something like this:
import urllib2
def internet_on():
try:
urllib2.urlopen('http://216.58.192.142', timeout=1)
return True
except urllib2.URLError as err:
return False
Currently, 216.58.192.142 is one of the IP addresses for google.com. Change http://216.58.192.142
to whatever site can be expected to respond quickly.
This fixed IP will not map to google.com forever. So this code is not robust -- it will need constant maintenance to keep it working.
The reason why the code above uses a fixed IP address instead of fully qualified domain name (FQDN) is because a FQDN would require a DNS lookup. When the machine does not have a working internet connection, the DNS lookup itself may block the call to urllib_request.urlopen
for more than a second. Thanks to @rzetterberg for pointing this out.
If the fixed IP address above is not working, you can find a current IP address for google.com (on unix) by running
% dig google.com +trace
...
google.com. 300 IN A 216.58.192.142
A common solution is to upgrade magento setup by running this command
php bin/magento setup:upgrade && php bin/magento setup:di:compile
Otherwise just check var/report/{error number}
For a small range, the simplest thing is to have a map array, where, eg, the 80th entry would have the value 82 in it, to use your example. For a much larger, sparse range, probably the way to go is a binary search.
With a query language you could query for values some distance either side of your input number and then sort through the resulting reduced list. But SQL doesn't have a good concept of "next" or "previous", to give you a "clean" solution.
You are accessing an object that is not defined.
The solution is check for null or undefined (to see whether the object exists) and only then iterate.
You use the "as" statement to avoid the possibility of an exception, e.g. you can handle the cast failure gracefully via logic. Only use the cast when you are sure that the object is of the desired type. I almost always use the "as" and then check for null.
If you want to validate your date(YYYY-MM-DD)
along with the comparison it will be use full for you...
function validateDate()
{
var newDate = new Date();
var presentDate = newDate.getDate();
var presentMonth = newDate.getMonth();
var presentYear = newDate.getFullYear();
var dateOfBirthVal = document.forms[0].dateOfBirth.value;
if (dateOfBirthVal == null)
return false;
var validatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/;
dateValues = dateOfBirthVal.match(validatePattern);
if (dateValues == null)
{
alert("Date of birth should be null and it should in the format of yyyy-mm-dd")
return false;
}
var birthYear = dateValues[1];
birthMonth = dateValues[3];
birthDate= dateValues[5];
if ((birthMonth < 1) || (birthMonth > 12))
{
alert("Invalid date")
return false;
}
else if ((birthDate < 1) || (birthDate> 31))
{
alert("Invalid date")
return false;
}
else if ((birthMonth==4 || birthMonth==6 || birthMonth==9 || birthMonth==11) && birthDate ==31)
{
alert("Invalid date")
return false;
}
else if (birthMonth == 2){
var isleap = (birthYear % 4 == 0 && (birthYear % 100 != 0 || birthYear % 400 == 0));
if (birthDate> 29 || (birthDate ==29 && !isleap))
{
alert("Invalid date")
return false;
}
}
else if((birthYear>presentYear)||(birthYear+70<presentYear))
{
alert("Invalid date")
return false;
}
else if(birthYear==presentYear)
{
if(birthMonth>presentMonth+1)
{
alert("Invalid date")
return false;
}
else if(birthMonth==presentMonth+1)
{
if(birthDate>presentDate)
{
alert("Invalid date")
return false;
}
}
}
return true;
}
As others suggested, you can serialize and deserialize the whole list at once, which is simpler and seems to comply perfectly with what you intend to do.
In that case the serialization code becomes
ObjectOutputStream oos = null;
FileOutputStream fout = null;
try{
fout = new FileOutputStream("G:\\address.ser", true);
oos = new ObjectOutputStream(fout);
oos.writeObject(myClassList);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if(oos != null){
oos.close();
}
}
And deserialization becomes (assuming that myClassList is a list and hoping you will use generics):
ObjectInputStream objectinputstream = null;
try {
FileInputStream streamIn = new FileInputStream("G:\\address.ser");
objectinputstream = new ObjectInputStream(streamIn);
List<MyClass> readCase = (List<MyClass>) objectinputstream.readObject();
recordList.add(readCase);
System.out.println(recordList.get(i));
} catch (Exception e) {
e.printStackTrace();
} finally {
if(objectinputstream != null){
objectinputstream .close();
}
}
You can also deserialize several objects from a file, as you intended to:
ObjectInputStream objectinputstream = null;
try {
streamIn = new FileInputStream("G:\\address.ser");
objectinputstream = new ObjectInputStream(streamIn);
MyClass readCase = null;
do {
readCase = (MyClass) objectinputstream.readObject();
if(readCase != null){
recordList.add(readCase);
}
} while (readCase != null)
System.out.println(recordList.get(i));
} catch (Exception e) {
e.printStackTrace();
} finally {
if(objectinputstream != null){
objectinputstream .close();
}
}
Please do not forget to close stream objects in a finally clause (note: it can throw exception).
EDIT
As suggested in the comments, it should be preferable to use try with resources and the code should get quite simpler.
Here is the list serialization :
try(
FileOutputStream fout = new FileOutputStream("G:\\address.ser", true);
ObjectOutputStream oos = new ObjectOutputStream(fout);
){
oos.writeObject(myClassList);
} catch (Exception ex) {
ex.printStackTrace();
}
Word up, I as well got tired of writing out enumerations based on Id / Name db table columns, copying and pasting stuff from queries in SSMS.
Below is a super dirty stored procedure that takes as input a table name, the column name you want to use for the c# enumeration name, and the column name that you want to use for the c# enumeration value.
Most of theses table names I work with a) end with "s" b) have a [TABLENAME]Id column and c) have a [TABLENAME]Name column, so there are a couple if statements that will assume that structure, in which case, the column name parameters are not required.
A little context for these examples - "Stonk" here doesn't really mean "stock" but kinda, the way I'm using "stonk" it means "a thing that has some numbers associated to it for a time period" But that's not important, it's just an example of table with this Id / Name schema. It looks like this:
CREATE TABLE StonkTypes (
StonkTypeId TINYINT IDENTITY(1,1) PRIMARY KEY NOT NULL,
StonkTypeName VARCHAR(200) NOT NULL CONSTRAINT UQ_StonkTypes_StonkTypeName UNIQUE (StonkTypeName)
)
After I create the proc, this statement:
EXEC CreateCSharpEnum 'StonkTypes'
Selects this string:
public enum StonkTypes { Stonk = 1, Bond = 2, Index = 3, Fund = 4, Commodity = 5,
PutCallRatio = 6, }
Which I can copy and paste into a C# file.
I have a Stonks table and it has StonkId and StonkName columns so this exec:
EXEC CreateCSharpEnum 'Stonks'
Spits out:
public enum Stonks { SP500 = 1, DowJonesIndustrialAverage = 2, ..... }
But for that enum I want to use the "Symbol" column for the enum name values so this:
EXEC CreateCSharpEnum 'Stonks', 'Symbol'
Does the trick and renders:
public enum Stonks { SPY = 1, DIA = 2, ..... }
Without further ado, here is this dirty piece of craziness. Yeah, very dirty, but I'm kind of pleased with myself - it's SQL code that constructs SQL code that constructs C# code. Couple layers involved.
CREATE OR ALTER PROCEDURE CreateCSharpEnum
@TableName VARCHAR(MAX),
@EnumNameColumnName VARCHAR(MAX) = NULL,
@EnumValueColumnName VARCHAR(MAX) = NULL
AS
DECLARE @LastCharOfTableName VARCHAR(1)
SELECT @LastCharOfTableName = RIGHT(@TableName, 1)
PRINT 'Last char = [' + @LastCharOfTableName + ']'
DECLARE @TableNameWithoutS VARCHAR(MAX)
IF UPPER(@LastCharOfTableName) = 'S'
SET @TableNameWithoutS = LEFT(@TableName, LEN(@TableName) - 1)
ELSE
SET @TableNameWithoutS = @TableName
PRINT 'Table name without trailing s = [' + @TableNameWithoutS + ']'
IF @EnumNameColumnName IS NULL
BEGIN
SET @EnumNameColumnName = @TableNameWithoutS + 'Name'
END
PRINT 'name col name = [' + @EnumNameColumnName + ']'
IF @EnumValueColumnName IS NULL
SET @EnumValueColumnName = @TableNameWithoutS + 'Id'
PRINT 'value col name = [' + @EnumValueColumnName + ']'
-- replace spaces and punctuation
SET @EnumNameColumnName = 'REPLACE(' + @EnumNameColumnName + ', '' '', '''')'
SET @EnumNameColumnName = 'REPLACE(' + @EnumNameColumnName + ', ''&'', '''')'
SET @EnumNameColumnName = 'REPLACE(' + @EnumNameColumnName + ', ''.'', '''')'
SET @EnumNameColumnName = 'REPLACE(' + @EnumNameColumnName + ', ''('', '''')'
SET @EnumNameColumnName = 'REPLACE(' + @EnumNameColumnName + ', '')'', '''')'
PRINT 'name col name with replace sql = [' + @EnumNameColumnName + ']'
DECLARE @SqlStr VARCHAR(MAX) = 'SELECT ' + @EnumNameColumnName
+ ' + '' = '''
+ ' + LTRIM(RTRIM(STR(' + @EnumValueColumnName + '))) + '','' FROM ' + @TableName + ' ORDER BY ' + @EnumValueColumnName
PRINT 'sql that gets rows for enum body = [' + @SqlStr + ']'
CREATE TABLE #EnumRowsTemp (s VARCHAR(MAX))
INSERT
INTO #EnumRowsTemp
EXEC(@SqlStr)
--SELECT * FROM #EnumRowsTemp
DECLARE @csharpenumbody VARCHAR(MAX)
SELECT @csharpenumbody = COALESCE(@csharpenumbody + ' ', '') + s FROM #EnumRowsTemp
--PRINT @csharpenumbody
DECLARE @csharpenum VARCHAR(MAX) = 'public enum ' + @TableName + ' { ' + @csharpenumbody + ' }'
PRINT @csharpenum
SELECT @csharpenum
DROP TABLE #EnumRowsTemp
Please, be critical. One funky thing I didn't understand, how come I have to create and drop this #EnumRowsTemp table and not just "SELECT INTO #EnumRowsTemp" to create the temp table on the fly? I don't know the answer, I tried that and it didn't work. That's probably the least of the problems of this code...
As dirty as it may be... I hope this saves some of you fellow dorks a little bit of time.
As of PHP 7, this task can be performed simply by using the Null coalescing operator like this :
echo !empty($address['street2']) ?? 'Empty';
You can also write a wrapper method to wrap unchecked exceptions, and even enhance wrapper with additional parameter representing another functional interface (with the same return type R). In this case you can pass a function that would be executed and returned in case of exceptions. See example below:
private void run() {
List<String> list = Stream.of(1, 2, 3, 4).map(wrapper(i ->
String.valueOf(++i / 0), i -> String.valueOf(++i))).collect(Collectors.toList());
System.out.println(list.toString());
}
private <T, R, E extends Exception> Function<T, R> wrapper(ThrowingFunction<T, R, E> function,
Function<T, R> onException) {
return i -> {
try {
return function.apply(i);
} catch (ArithmeticException e) {
System.out.println("Exception: " + i);
return onException.apply(i);
} catch (Exception e) {
System.out.println("Other: " + i);
return onException.apply(i);
}
};
}
@FunctionalInterface
interface ThrowingFunction<T, R, E extends Exception> {
R apply(T t) throws E;
}
You can use "iPhone Configuration Utility" to manage provisioning profiles.
Ubuntu reporsitories can be more useful
https://wiki.ubuntu.com/LucidLynx/ReleaseNotes#Sun%20Java%20moved%20to%20the%20Partner%20repository
The onselect
must be onclick
. This will work for keyboard users.
I would also recommend adding <label>
tags to the text of "Day", "Month", and "Year" to make them easier to click on. Example code:
<input id="day" name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')"/><label for="day">Day</label>
I would also recommend removing the spaces between the attribute onclick
and the value, although it can be parsed by browsers:
<input name="calendarSelection" type="radio" onclick = "go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')"/>Day
Should be:
<input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')"/>Day
You can use find
with tabs-to-spaces
package for this.
First, install tabs-to-spaces
npm install -g tabs-to-spaces
then, run this command from the root directory of your project;
find . -name '*' -exec t2s --spaces 2 {} \;
This will replace every tab
character with 2 spaces
in every file.
For right to left (entry animation) and left to right (exit animation):
styles.xml:
<style name="CustomDialog" parent="@android:style/Theme.Dialog">
<item name="android:windowAnimationStyle">@style/CustomDialogAnimation</item>
</style>
<style name="CustomDialogAnimation">
<item name="android:windowEnterAnimation">@anim/translate_left_side</item>
<item name="android:windowExitAnimation">@anim/translate_right_side</item>
</style>
Create two files in res/anim/:
translate_right_side.xml:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0%" android:toXDelta="100%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="600"/>
translate_left_side.xml:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="600"
android:fromXDelta="100%"
android:toXDelta="0%"/>
In you Fragment/Activity:
Dialog dialog = new Dialog(getActivity(), R.style.CustomDialog);
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:top="-6dp"
android:left="-6dp"
android:right="-6dp"
android:bottom="0dp">
<shape android:shape="rectangle">
<solid android:color="#88FFFF00"/>
<stroke
android:width="5dp"
android:color="#FF000000"/>
</shape>
</item>
</layer-list>
Add the below to your manifest:
<activity android:name=".AppPreferenceActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="com.scytec.datamobile.vd.gui.android.AppPreferenceActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
??!
is a trigraph that translates to |
. So it says:
!ErrorHasOccured() || HandleError();
which, due to short circuiting, is equivalent to:
if (ErrorHasOccured())
HandleError();
Guru of the Week (deals with C++ but relevant here), where I picked this up.
Possible origin of trigraphs or as @DwB points out in the comments it's more likely due to EBCDIC being difficult (again). This discussion on the IBM developerworks board seems to support that theory.
From ISO/IEC 9899:1999 §5.2.1.1, footnote 12 (h/t @Random832):
The trigraph sequences enable the input of characters that are not defined in the Invariant Code Set as described in ISO/IEC 646, which is a subset of the seven-bit US ASCII code set.
In my case of legacy application, the issue occurred when I added below entry in web.config file under the node <system.webServer>
<modules runAllManagedModulesForAllRequests="true"></modules>
When I removed it, the issue resolved.
The problem as I understand it is as follows. You have several libraries, some static, some dynamic and some both static and dynamic. gcc's default behavior is to link "mostly dynamic". That is, gcc links to dynamic libraries when possible but otherwise falls back to static libraries. When you use the -static option to gcc the behavior is to only link static libraries and exit with an error if no static library can be found, even if there is an appropriate dynamic library.
Another option, which I have on several occasions wished gcc had, is what I call -mostly-static and is essentially the opposite of -dynamic (the default). -mostly-static would, if it existed, prefer to link against static libraries but would fall back to dynamic libraries.
This option does not exist but it can be emulated with the following algorithm:
Constructing the link command line with out including -static.
Iterate over the dynamic link options.
Accumulate library paths, i.e. those options of the form -L<lib_dir> in a variable <lib_path>
For each dynamic link option, i.e. those of the form -l<lib_name>, run the command gcc <lib_path> -print-file-name=lib<lib_name>.a and capture the output.
If the command prints something other than what you passed, it will be the full path to the static library. Replace the dynamic library option with the full path to the static library.
Rinse and repeat until you've processed the entire link command line. Optionally the script can also take a list of library names to exclude from static linking.
The following bash script seems to do the trick:
#!/bin/bash
if [ $# -eq 0 ]; then
echo "Usage: $0 [--exclude <lib_name>]. . . <link_command>"
fi
exclude=()
lib_path=()
while [ $# -ne 0 ]; do
case "$1" in
-L*)
if [ "$1" == -L ]; then
shift
LPATH="-L$1"
else
LPATH="$1"
fi
lib_path+=("$LPATH")
echo -n "\"$LPATH\" "
;;
-l*)
NAME="$(echo $1 | sed 's/-l\(.*\)/\1/')"
if echo "${exclude[@]}" | grep " $NAME " >/dev/null; then
echo -n "$1 "
else
LIB="$(gcc $lib_path -print-file-name=lib"$NAME".a)"
if [ "$LIB" == lib"$NAME".a ]; then
echo -n "$1 "
else
echo -n "\"$LIB\" "
fi
fi
;;
--exclude)
shift
exclude+=(" $1 ")
;;
*) echo -n "$1 "
esac
shift
done
echo
For example:
mostlyStatic gcc -o test test.c -ldl -lpthread
on my system returns:
gcc -o test test.c "/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/libdl.a" "/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/libpthread.a"
or with an exclusion:
mostlyStatic --exclude dl gcc -o test test.c -ldl -lpthread
I then get:
gcc -o test test.c -ldl "/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/libpthread.a"
Use the DataGridView.ReadOnly
property
The code in the MSDN example illustrates the use of this property in a DataGridView
control intended primarily for display. In this example, the visual appearance of the control is customized in several ways and the control is configured for limited interactivity.
Observe these settings in the sample code:
// Set property values appropriate for read-only
// display and limited interactivity
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToOrderColumns = true;
dataGridView1.ReadOnly = true;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.MultiSelect = false;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
dataGridView1.AllowUserToResizeColumns = false;
dataGridView1.ColumnHeadersHeightSizeMode =
DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
dataGridView1.AllowUserToResizeRows = false;
dataGridView1.RowHeadersWidthSizeMode =
DataGridViewRowHeadersWidthSizeMode.DisableResizing;
If you want a simplest one-liner solution, then go for the accepted answer that uses regex.
However, if you want a faster solution then here's a function you can have.
console.log(isAlphaNumeric('a')); // true
console.log(isAlphaNumericString('HelloWorld96')); // true
console.log(isAlphaNumericString('Hello World!')); // false
/**
* Function to check if a character is alpha-numeric.
*
* @param {string} c
* @return {boolean}
*/
function isAlphaNumeric(c) {
const CHAR_CODE_A = 65;
const CHAR_CODE_Z = 90;
const CHAR_CODE_AS = 97;
const CHAR_CODE_ZS = 122;
const CHAR_CODE_0 = 48;
const CHAR_CODE_9 = 57;
let code = c.charCodeAt(0);
if (
(code >= CHAR_CODE_A && code <= CHAR_CODE_Z) ||
(code >= CHAR_CODE_AS && code <= CHAR_CODE_ZS) ||
(code >= CHAR_CODE_0 && code <= CHAR_CODE_9)
) {
return true;
}
return false;
}
/**
* Function to check if a string is fully alpha-numeric.
*
* @param {string} s
* @returns {boolean}
*/
function isAlphaNumericString(s) {
for (let i = 0; i < s.length; i++) {
if (!isAlphaNumeric(s[i])) {
return false;
}
}
return true;
}
_x000D_
string removeSpaces(string word) {
string newWord;
for (int i = 0; i < word.length(); i++) {
if (word[i] != ' ') {
newWord += word[i];
}
}
return newWord;
}
This code basically takes a string and iterates through every character in it. It then checks whether that string is a white space, if it isn't then the character is added to a new string.
The function move.CompleteMove(events)
that you use within your class probably doesn't contain a return
statement. So nothing is returned to self.values
(==> None). Use return
in move.CompleteMove(events)
to return whatever you want to store in self.values
and it should work. Hope this helps.
Thanks everyone, you all helped me learn a lot. This is what I came up with using some of your suggestions
#this is apparently a better way of getting multiple inputs at the same time than the
#way I was doing it
text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
numa = int(split_text[0])
numb = int(split_text[1])
#standing variables
total = 0
if numb > 0:
repeat = numb
else:
repeat = -numb
#for loops work better than while loops and are cheaper
#output the total
for count in range(repeat):
total += numa
#check to make sure the output is accurate
if numb < 0:
total = -total
print total
Thanks for all the help everyone.
You can also use =OFFSET([@column];-1;0)
if you are in a named table.
you need to use YYYY-MM-DD format to insert date in mysql
if some reason two versions of jQuery are loaded (which is not recommended), calling $.noConflict(true)
from the second version will return the globally scoped jQuery variables to those of the first version.
Sometimes it could be issue with older version (or not stable) of JQuery files
Solution use $.noConflict();
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.dataTables.js" type="text/javascript"></script>
<script>
$.noConflict();
jQuery( document ).ready(function( $ ) {
$('#myTable').DataTable();
});
// Code that uses other library's $ can follow here.
</script>
You would need to create a generic class named MyProp. Then, you will need to add implicit or explicit cast operators so you can get and set the value as if it were the type specified in the generic type parameter. These cast operators can do the extra work that you need.
You can also try this simple one-liner code. Just call the alert method on onclick attribute.
<button id="some_id1" onclick="alert(this.id)"></button>
For copy any text in Android:
TextView text = findViewById(R.id.text_id);
ImageView icons = findViewById(R.id.copy_icon);
icons.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("text whatever you want", text.getText().toString());
clipboardManager.setPrimaryClip(clipData);
Toast.makeText(context, "Text Copied", Toast.LENGTH_SHORT).show();
}
});
Contrary to what pointy says, the blur()
method does exist and is a part of the w3c standard. The following exaple will work in every modern browser (including IE):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Javascript test</title>
<script type="text/javascript" language="javascript">
window.onload = function()
{
var field = document.getElementById("field");
var link = document.getElementById("link");
var output = document.getElementById("output");
field.onfocus = function() { output.innerHTML += "<br/>field.onfocus()"; };
field.onblur = function() { output.innerHTML += "<br/>field.onblur()"; };
link.onmouseover = function() { field.blur(); };
};
</script>
</head>
<body>
<form name="MyForm">
<input type="text" name="field" id="field" />
<a href="javascript:void(0);" id="link">Blur field on hover</a>
<div id="output"></div>
</form>
</body>
</html>
Note that I used link.onmouseover
instead of link.onclick
, because otherwise the click itself would have removed the focus.
This link contains a good checklist why core dumps are not generated:
exit()
instead of using the core dump handler."Hello, this is Mike (example)".replace(/ *\([^)]*\) */g, "");
Result:
"Hello, this is Mike"
If you have a class file at build/com/foo/Hello.class
, you can check what java version it is compiled at using the command:
javap -v build/com/foo/Hello.class | grep "major"
Example usage:
$ javap -v build/classes/java/main/org/aguibert/liberty/Book.class | grep major
major version: 57
According to the table in the OP, major version 57 means the class file was compiled to JDK 13 bytecode level
Linux kernel 5.0 source comments
I knew that x86 specifics are under arch/x86
, and that syscall stuff goes under arch/x86/entry
. So a quick git grep rdi
in that directory leads me to arch/x86/entry/entry_64.S:
/*
* 64-bit SYSCALL instruction entry. Up to 6 arguments in registers.
*
* This is the only entry point used for 64-bit system calls. The
* hardware interface is reasonably well designed and the register to
* argument mapping Linux uses fits well with the registers that are
* available when SYSCALL is used.
*
* SYSCALL instructions can be found inlined in libc implementations as
* well as some other programs and libraries. There are also a handful
* of SYSCALL instructions in the vDSO used, for example, as a
* clock_gettimeofday fallback.
*
* 64-bit SYSCALL saves rip to rcx, clears rflags.RF, then saves rflags to r11,
* then loads new ss, cs, and rip from previously programmed MSRs.
* rflags gets masked by a value from another MSR (so CLD and CLAC
* are not needed). SYSCALL does not save anything on the stack
* and does not change rsp.
*
* Registers on entry:
* rax system call number
* rcx return address
* r11 saved rflags (note: r11 is callee-clobbered register in C ABI)
* rdi arg0
* rsi arg1
* rdx arg2
* r10 arg3 (needs to be moved to rcx to conform to C ABI)
* r8 arg4
* r9 arg5
* (note: r12-r15, rbp, rbx are callee-preserved in C ABI)
*
* Only called from user space.
*
* When user can change pt_regs->foo always force IRET. That is because
* it deals with uncanonical addresses better. SYSRET has trouble
* with them due to bugs in both AMD and Intel CPUs.
*/
and for 32-bit at arch/x86/entry/entry_32.S:
/*
* 32-bit SYSENTER entry.
*
* 32-bit system calls through the vDSO's __kernel_vsyscall enter here
* if X86_FEATURE_SEP is available. This is the preferred system call
* entry on 32-bit systems.
*
* The SYSENTER instruction, in principle, should *only* occur in the
* vDSO. In practice, a small number of Android devices were shipped
* with a copy of Bionic that inlined a SYSENTER instruction. This
* never happened in any of Google's Bionic versions -- it only happened
* in a narrow range of Intel-provided versions.
*
* SYSENTER loads SS, ESP, CS, and EIP from previously programmed MSRs.
* IF and VM in RFLAGS are cleared (IOW: interrupts are off).
* SYSENTER does not save anything on the stack,
* and does not save old EIP (!!!), ESP, or EFLAGS.
*
* To avoid losing track of EFLAGS.VM (and thus potentially corrupting
* user and/or vm86 state), we explicitly disable the SYSENTER
* instruction in vm86 mode by reprogramming the MSRs.
*
* Arguments:
* eax system call number
* ebx arg1
* ecx arg2
* edx arg3
* esi arg4
* edi arg5
* ebp user stack
* 0(%ebp) arg6
*/
glibc 2.29 Linux x86_64 system call implementation
Now let's cheat by looking at a major libc implementations and see what they are doing.
What could be better than looking into glibc that I'm using right now as I write this answer? :-)
glibc 2.29 defines x86_64 syscalls at sysdeps/unix/sysv/linux/x86_64/sysdep.h
and that contains some interesting code, e.g.:
/* The Linux/x86-64 kernel expects the system call parameters in
registers according to the following table:
syscall number rax
arg 1 rdi
arg 2 rsi
arg 3 rdx
arg 4 r10
arg 5 r8
arg 6 r9
The Linux kernel uses and destroys internally these registers:
return address from
syscall rcx
eflags from syscall r11
Normal function call, including calls to the system call stub
functions in the libc, get the first six parameters passed in
registers and the seventh parameter and later on the stack. The
register use is as follows:
system call number in the DO_CALL macro
arg 1 rdi
arg 2 rsi
arg 3 rdx
arg 4 rcx
arg 5 r8
arg 6 r9
We have to take care that the stack is aligned to 16 bytes. When
called the stack is not aligned since the return address has just
been pushed.
Syscalls of more than 6 arguments are not supported. */
and:
/* Registers clobbered by syscall. */
# define REGISTERS_CLOBBERED_BY_SYSCALL "cc", "r11", "cx"
#undef internal_syscall6
#define internal_syscall6(number, err, arg1, arg2, arg3, arg4, arg5, arg6) \
({ \
unsigned long int resultvar; \
TYPEFY (arg6, __arg6) = ARGIFY (arg6); \
TYPEFY (arg5, __arg5) = ARGIFY (arg5); \
TYPEFY (arg4, __arg4) = ARGIFY (arg4); \
TYPEFY (arg3, __arg3) = ARGIFY (arg3); \
TYPEFY (arg2, __arg2) = ARGIFY (arg2); \
TYPEFY (arg1, __arg1) = ARGIFY (arg1); \
register TYPEFY (arg6, _a6) asm ("r9") = __arg6; \
register TYPEFY (arg5, _a5) asm ("r8") = __arg5; \
register TYPEFY (arg4, _a4) asm ("r10") = __arg4; \
register TYPEFY (arg3, _a3) asm ("rdx") = __arg3; \
register TYPEFY (arg2, _a2) asm ("rsi") = __arg2; \
register TYPEFY (arg1, _a1) asm ("rdi") = __arg1; \
asm volatile ( \
"syscall\n\t" \
: "=a" (resultvar) \
: "0" (number), "r" (_a1), "r" (_a2), "r" (_a3), "r" (_a4), \
"r" (_a5), "r" (_a6) \
: "memory", REGISTERS_CLOBBERED_BY_SYSCALL); \
(long int) resultvar; \
})
which I feel are pretty self explanatory. Note how this seems to have been designed to exactly match the calling convention of regular System V AMD64 ABI functions: https://en.wikipedia.org/wiki/X86_calling_conventions#List_of_x86_calling_conventions
Quick reminder of the clobbers:
cc
means flag registers. But Peter Cordes comments that this is unnecessary here.memory
means that a pointer may be passed in assembly and used to access memoryFor an explicit minimal runnable example from scratch see this answer: How to invoke a system call via syscall or sysenter in inline assembly?
Make some syscalls in assembly manually
Not very scientific, but fun:
x86_64.S
.text
.global _start
_start:
asm_main_after_prologue:
/* write */
mov $1, %rax /* syscall number */
mov $1, %rdi /* stdout */
mov $msg, %rsi /* buffer */
mov $len, %rdx /* len */
syscall
/* exit */
mov $60, %rax /* syscall number */
mov $0, %rdi /* exit status */
syscall
msg:
.ascii "hello\n"
len = . - msg
Make system calls from C
Here's an example with register constraints: How to invoke a system call via syscall or sysenter in inline assembly?
aarch64
I've shown a minimal runnable userland example at: https://reverseengineering.stackexchange.com/questions/16917/arm64-syscalls-table/18834#18834 TODO grep kernel code here, should be easy.
Perfect Solution that goes further to the goal
Goal: Disable the blinking curser when EditText
is not in focus, and enable the blinking curser when EditText
is in focus. Below also opens keyboard when EditText
is clicked, and hides it when you press done in the keyboard.
1) Set in your xml under your EditText
:
android:cursorVisible="false"
2) Set onClickListener:
iEditText.setOnClickListener(editTextClickListener);
OnClickListener editTextClickListener = new OnClickListener()
{
public void onClick(View v)
{
if (v.getId() == iEditText.getId())
{
iEditText.setCursorVisible(true);
}
}
};
3) then onCreate
, capture the event when done is pressed using OnEditorActionListener
to your EditText
, and then setCursorVisible(false)
.
//onCreate...
iEditText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
iEditText.setCursorVisible(false);
if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(iEditText.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
}
return false;
}
});
You have to use NSURLConnectionDelegate
to allow HTTPS connections and there are new callbacks with iOS8.
Deprecated:
connection:canAuthenticateAgainstProtectionSpace:
connection:didCancelAuthenticationChallenge:
connection:didReceiveAuthenticationChallenge:
Instead those, you need to declare:
connectionShouldUseCredentialStorage:
- Sent to determine whether the URL loader should use the credential storage for authenticating the connection.
connection:willSendRequestForAuthenticationChallenge:
- Tells the delegate that the connection will send a request for an authentication challenge.
With willSendRequestForAuthenticationChallenge
you can use challenge
like you did with the deprecated methods, for example:
// Trusting and not trusting connection to host: Self-signed certificate
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
IETF Open Standards RFC 5321 2.4. General Syntax Principles and Transaction Model
SMTP implementations MUST take care to preserve the case of mailbox local-parts. In particular, for some hosts, the user "smith" is different from the user "Smith".
Mailbox domains follow normal DNS rules and are hence not case sensitive
Just delete these lines from the root build.gradle
android {
compileSdkVersion 19
buildToolsVersion '19.1' }
Now trying and compile again. It should work.
IE8 Developer Tools are able to switch to IE7 mode
The problem I need to solve is to store contracts containing a few fields (address, book, num_of_days, borrower_addr, blk_data), blk_data is a transaction list (block number and transaction address). This question and answer helped me. I would like to share my code as below. Hope this helps.
- Schema definition. See blk_data.
var ContractSchema = new Schema(
{
address: {type: String, required: true, max: 100}, //contract address
// book_id: {type: String, required: true, max: 100}, //book id in the book collection
book: { type: Schema.ObjectId, ref: 'clc_books', required: true }, // Reference to the associated book.
num_of_days: {type: Number, required: true, min: 1},
borrower_addr: {type: String, required: true, max: 100},
// status: {type: String, enum: ['available', 'Created', 'Locked', 'Inactive'], default:'Created'},
blk_data: [{
tx_addr: {type: String, max: 100}, // to do: change to a list
block_number: {type: String, max: 100}, // to do: change to a list
}]
}
);
- Create a record for the collection in the MongoDB. See blk_data.
// Post submit a smart contract proposal to borrowing a specific book.
exports.ctr_contract_propose_post = [
// Validate fields
body('book_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
body('req_addr', 'req_addr must not be empty.').isLength({ min: 1 }).trim(),
body('new_contract_addr', 'contract_addr must not be empty.').isLength({ min: 1 }).trim(),
body('tx_addr', 'tx_addr must not be empty.').isLength({ min: 1 }).trim(),
body('block_number', 'block_number must not be empty.').isLength({ min: 1 }).trim(),
body('num_of_days', 'num_of_days must not be empty.').isLength({ min: 1 }).trim(),
// Sanitize fields.
sanitizeBody('*').escape(),
// Process request after validation and sanitization.
(req, res, next) => {
// Extract the validation errors from a request.
const errors = validationResult(req);
if (!errors.isEmpty()) {
// There are errors. Render form again with sanitized values/error messages.
res.status(400).send({ errors: errors.array() });
return;
}
// Create a Book object with escaped/trimmed data and old id.
var book_fields =
{
_id: req.body.book_id, // This is required, or a new ID will be assigned!
cur_contract: req.body.new_contract_addr,
status: 'await_approval'
};
async.parallel({
//call the function get book model
books: function(callback) {
Book.findByIdAndUpdate(req.body.book_id, book_fields, {}).exec(callback);
},
}, function(error, results) {
if (error) {
res.status(400).send({ errors: errors.array() });
return;
}
if (results.books.isNew) {
// res.render('pg_error', {
// title: 'Proposing a smart contract to borrow the book',
// c: errors.array()
// });
res.status(400).send({ errors: errors.array() });
return;
}
var contract = new Contract(
{
address: req.body.new_contract_addr,
book: req.body.book_id,
num_of_days: req.body.num_of_days,
borrower_addr: req.body.req_addr
});
var blk_data = {
tx_addr: req.body.tx_addr,
block_number: req.body.block_number
};
contract.blk_data.push(blk_data);
// Data from form is valid. Save book.
contract.save(function (err) {
if (err) { return next(err); }
// Successful - redirect to new book record.
resObj = {
"res": contract.url
};
res.status(200).send(JSON.stringify(resObj));
// res.redirect();
});
});
},
];
- Update a record. See blk_data.
// Post lender accept borrow proposal.
exports.ctr_contract_propose_accept_post = [
// Validate fields
body('book_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
body('contract_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
body('tx_addr', 'tx_addr must not be empty.').isLength({ min: 1 }).trim(),
body('block_number', 'block_number must not be empty.').isLength({ min: 1 }).trim(),
// Sanitize fields.
sanitizeBody('*').escape(),
// Process request after validation and sanitization.
(req, res, next) => {
// Extract the validation errors from a request.
const errors = validationResult(req);
if (!errors.isEmpty()) {
// There are errors. Render form again with sanitized values/error messages.
res.status(400).send({ errors: errors.array() });
return;
}
// Create a Book object with escaped/trimmed data
var book_fields =
{
_id: req.body.book_id, // This is required, or a new ID will be assigned!
status: 'on_loan'
};
// Create a contract object with escaped/trimmed data
var contract_fields = {
$push: {
blk_data: {
tx_addr: req.body.tx_addr,
block_number: req.body.block_number
}
}
};
async.parallel({
//call the function get book model
book: function(callback) {
Book.findByIdAndUpdate(req.body.book_id, book_fields, {}).exec(callback);
},
contract: function(callback) {
Contract.findByIdAndUpdate(req.body.contract_id, contract_fields, {}).exec(callback);
},
}, function(error, results) {
if (error) {
res.status(400).send({ errors: errors.array() });
return;
}
if ((results.book.isNew) || (results.contract.isNew)) {
res.status(400).send({ errors: errors.array() });
return;
}
var resObj = {
"res": results.contract.url
};
res.status(200).send(JSON.stringify(resObj));
});
},
];
You can tweak the html5mode but that is only functional for links included in html anchors of your page and how the url looks like in the browser address bar. Attempting to request a subpage without the hashtag (with or without html5mode) from anywhere outside the page will result in a 404 error. For example, the following CURL request will result in a page not found error, irrespective of html5mode:
$ curl http://foo.bar/phones
although the following will return the root/home page:
$ curl http://foo.bar/#/phones
The reason for this is that anything after the hashtag is stripped off before the request arrives at the server. So a request for http://foo.bar/#/portfolio
arrives at the server as a request for http://foo.bar
. The server will respond with a 200 OK response (presumably) for http://foo.bar
and the agent/client will process the rest.
So in cases that you want to share a url with others, you have no option but to include the hashtag.
The bind
method creates a new function from another function with one or more arguments bound to specific values, including the implicit this
argument.
This is an example of partial application. Normally we supply a function with all of its arguments which yields a value. This is known as function application. We are applying the function to its arguments.
Partial application is an example of a higher order function (HOF) because it yields a new function with a fewer number of argument.
You can use bind
to transform functions with multiple arguments into new functions.
function multiply(x, y) { _x000D_
return x * y; _x000D_
}_x000D_
_x000D_
let multiplyBy10 = multiply.bind(null, 10);_x000D_
console.log(multiplyBy10(5));
_x000D_
In the most common use case, when called with one argument the bind
method will create a new function that has the this
value bound to a specific value. In effect this transforms an instance method to a static method.
function Multiplier(factor) { _x000D_
this.factor = factor;_x000D_
}_x000D_
_x000D_
Multiplier.prototype.multiply = function(x) { _x000D_
return this.factor * x; _x000D_
}_x000D_
_x000D_
function ApplyFunction(func, value) {_x000D_
return func(value);_x000D_
}_x000D_
_x000D_
var mul = new Multiplier(5);_x000D_
_x000D_
// Produces garbage (NaN) because multiplying "undefined" by 10_x000D_
console.log(ApplyFunction(mul.multiply, 10));_x000D_
_x000D_
// Produces expected result: 50_x000D_
console.log(ApplyFunction(mul.multiply.bind(mul), 10));
_x000D_
The following example shows how using binding of this
can enable an object method to act as a callback that can easily update the state of an object.
function ButtonPressedLogger()_x000D_
{_x000D_
this.count = 0;_x000D_
this.onPressed = function() {_x000D_
this.count++;_x000D_
console.log("pressed a button " + this.count + " times");_x000D_
}_x000D_
for (let d of document.getElementsByTagName("button"))_x000D_
d.onclick = this.onPressed.bind(this);_x000D_
}_x000D_
_x000D_
new ButtonPressedLogger();
_x000D_
<button>press me</button>_x000D_
<button>no press me</button>
_x000D_
Give this a go:
<form name="postcontent" id="postcontent">
<input name="postsubmit" type="submit" id="postsubmit" value="POST"/>
<textarea id="postdata" name="postdata" placeholder="What's Up ?"></textarea>
</form>
<script>
(function() {
$("#postcontent").on('submit', function(e) {
e.preventDefault();
$.ajax({
type:"POST",
url:"add_new_post.php",
data:$("#postcontent").serialize(),
beforeSend:function(){
$(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
},success:function(response){
//alert(response);
$("#return_update_msg").html(response);
$(".post_submitting").fadeOut(1000);
}
});
});
})();
</script>
First you have to add System.Configuration
reference to your project and then use below code to get connection string.
_connectionString = ConfigurationManager.ConnectionStrings["MYSQLConnection"].ConnectionString.ToString();
I have created a javascript function that looks if he has enough space on the right side. If it has he will show it on the right side, else he will display it on the left side. Again if it has has enough space on the right side, it will show right side. it is a loop...
$(document).ready(function () {
$('body, html').css('overflow', 'hidden');
var screenWidth = $(window).width();
$('body, html').css('overflow', 'visible');
if (screenWidth > 767) {
$(".dropdown-submenu").hover(function () {
var dropdownPosition = $(this).offset().left + $(this).width() + $(this).find('ul').width();
var newPosition = $(this).offset().left - $(this).find('ul').width();
var windowPosition = $(window).width();
var oldPosition = $(this).offset().left + $(this).width();
//document.title = dropdownPosition;
if (dropdownPosition > windowPosition) {
$(this).find('ul').offset({ "left": newPosition });
} else {
$(this).find('ul').offset({ "left": oldPosition });
}
});
}
});
simple way can be -
just href="javascript:location.reload(true);
your answer is
location.reload(true);
Thanks
just enter this line in the command line :
set RANDFILE=.rnd
Lets define the dataframe from your example by
>>> df = pd.DataFrame([[206, 214], [226, 234], [245, 253], [265, 272], [283, 291]],
columns=[1, 2])
>>> df
1 2
0 206 214
1 226 234
2 245 253
3 265 272
4 283 291
Then you could manipulate the index of the second column by
>>> df[2].index = df[2].index+1
and finally re-combine the single columns
>>> pd.concat([df[1], df[2]], axis=1)
1 2
0 206.0 NaN
1 226.0 214.0
2 245.0 234.0
3 265.0 253.0
4 283.0 272.0
5 NaN 291.0
Perhaps not fast but simple to read. Consider setting variables for the column names and the actual shift required.
Edit: Generally shifting is possible by df[2].shift(1)
as already posted however would that cut-off the carryover.
You can set the fontsize directly in the call to set_xticklabels
and set_yticklabels
(as noted in previous answers). This will only affect one Axes
at a time.
ax.set_xticklabels(x_ticks, rotation=0, fontsize=8)
ax.set_yticklabels(y_ticks, rotation=0, fontsize=8)
You can also set the ticklabel
font size globally (i.e. for all figures/subplots in a script) using rcParams
:
import matplotlib.pyplot as plt
plt.rc('xtick',labelsize=8)
plt.rc('ytick',labelsize=8)
Or, equivalently:
plt.rcParams['xtick.labelsize']=8
plt.rcParams['ytick.labelsize']=8
Finally, if this is a setting that you would like to be set for all your matplotlib plots, you could also set these two rcParams
in your matplotlibrc
file:
xtick.labelsize : 8 # fontsize of the x tick labels
ytick.labelsize : 8 # fontsize of the y tick labels
Thank you very much for the replies!
Saggi Malachi, that query unfortunately sums the invoice amount in cases where there is more than one payment. Say there are two payments to a $39 invoice of $18 and $12. So rather than ending up with a result that looks like:
1 39.00 9.00
You'll end up with:
1 78.00 48.00
Charles Bretana, in the course of trimming my query down to the simplest possible query I (stupidly) omitted an additional table, customerinvoices, which provides a link between customers and invoices. This can be used to see invoices for which payments haven't made.
After much struggling, I think that the following query returns what I need it to:
SELECT DISTINCT i.invoiceid, i.amount, ISNULL(i.amount - p.amount, i.amount) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN customerinvoices ci ON i.invoiceid = ci.invoiceid
LEFT JOIN (
SELECT invoiceid, SUM(p.amount) amount
FROM invoicepayments ip
LEFT JOIN payments p ON ip.paymentid = p.paymentid
GROUP BY ip.invoiceid
) p
ON p.invoiceid = ip.invoiceid
LEFT JOIN payments p2 ON ip.paymentid = p2.paymentid
LEFT JOIN customers c ON ci.customerid = c.customerid
WHERE c.customernumber='100'
Would you guys concur?
First, we are going to create a Windows Service that runs under the System account. This service will be responsible for spawning an interactive process within the currently active User’s Session. This newly created process will display a UI and run with full admin rights. When the first User logs on to the computer, this service will be started and will be running in Session0; however the process that this service spawns will be running on the desktop of the currently logged on User. We will refer to this service as the LoaderService.
Next, the winlogon.exe process is responsible for managing User login and logout procedures. We know that every User who logs on to the computer will have a unique Session ID and a corresponding winlogon.exe process associated with their Session. Now, we mentioned above, the LoaderService runs under the System account. We also confirmed that each winlogon.exe process on the computer runs under the System account. Because the System account is the owner of both the LoaderService and the winlogon.exe processes, our LoaderService can copy the access token (and Session ID) of the winlogon.exe process and then call the Win32 API function CreateProcessAsUser to launch a process into the currently active Session of the logged on User. Since the Session ID located within the access token of the copied winlogon.exe process is greater than 0, we can launch an interactive process using that token.
Try this one. Subverting Vista UAC in Both 32 and 64 bit Architectures
res.send
is used to send the response to the client where res.end
is used to end the response you are sending.
res.send
automatically call res.end
So you don't have to call or mention it after res.send
(IN @brugernavn varchar(64)**)**,IN @password varchar(64))
The problem is the )
Try to use
ng g component plainsight/some-name.component.ts
Or try it manually, if you feel more comfortable.
One way to avoid accidentally including the same script twice is to implement a script management module in your templating system. The typical way to include a script is to use the SCRIPT tag in your HTML page.
<script type="text/javascript" src="menu_1.0.17.js"></script>
An alternative in PHP would be to create a function called insertScript.
<?php insertScript("menu.js") ?>
Another solution is to set the 'onclick' attribute to a function that returns your writeLED function.
document.getElementById('buttonLED'+id).onclick = function(){ return writeLED(1,1)};
This can also be useful for other cases when you create an element in JavaScript while it has not yet been drawn in the browser.
I use the str_count
function from the stringr
library with the escape sequence \w
that represents:
any ‘word’ character (letter, digit or underscore in the current locale: in UTF-8 mode only ASCII letters and digits are considered)
Example:
> str_count("How many words are in this sentence", '\\w+')
[1] 7
Of all other 9 answers that I was able to test, only two (by Vincent Zoonekynd, and by petermeissner) worked for all inputs presented here so far, but they also require stringr
.
But only this solution works with all inputs presented so far, plus inputs such as "foo+bar+baz~spam+eggs"
or "Combien de mots sont dans cette phrase ?"
.
Benchmark:
library(stringr)
questions <-
c(
"", "x", "x y", "x y!", "x y! z",
"foo+bar+baz~spam+eggs",
"one, two three 4,,,, 5 6",
"How many words are in this sentence",
"How many words are in this sentence",
"Combien de mots sont dans cette phrase ?",
"
Day after day, day after day,
We stuck, nor breath nor motion;
"
)
answers <- c(0, 1, 2, 2, 3, 5, 6, 7, 7, 7, 12)
score <- function(f) sum(unlist(lapply(questions, f)) == answers)
funs <-
c(
function(s) sapply(gregexpr("\\W+", s), length) + 1,
function(s) sapply(gregexpr("[[:alpha:]]+", s), function(x) sum(x > 0)),
function(s) vapply(strsplit(s, "\\W+"), length, integer(1)),
function(s) length(strsplit(gsub(' {2,}', ' ', s), ' ')[[1]]),
function(s) length(str_match_all(s, "\\S+")[[1]]),
function(s) str_count(s, "\\S+"),
function(s) sapply(gregexpr("\\W+", s), function(x) sum(x > 0)) + 1,
function(s) length(unlist(strsplit(s," "))),
function(s) sapply(strsplit(s, " "), length),
function(s) str_count(s, '\\w+')
)
unlist(lapply(funs, score))
Output:
6 10 10 8 9 9 7 6 6 11
A more current take on the situation. During 2018, the C++ extension added another option to the configuration compilerPath
of the c_cpp_properties.json
file;
compilerPath
(optional) The absolute path to the compiler you use to build your project. The extension will query the compiler to determine the system include paths and default defines to use for IntelliSense.
If used, the includePath
would not be needed since the IntelliSense will use the compiler to figure out the system include paths.
Originally,
How and where can I add include paths in the configurations below?
The list is a string array, hence adding an include path would look something like;
"configurations": [
{
"name": "Mac",
"includePath": ["/usr/local/include",
"/path/to/additional/includes",
"/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include"
]
}
]
Source; cpptools blog 31 March 2016.
The linked source has a gif showing the format for the Win32 configuration, but the same applies to the others.
The above sample includes the SDK (OSX 10.11) path if Xcode is installed.
Note I find it can take a while to update once the include path has been changed.
The cpptools extension can be found here.
Further documentation (from Microsoft) on the C++ language support in VSCode can be found here.
For the sake of preservation (from the discussion), the following are basic snippets for the contents of the tasks.json file to compile and execute either a C++ file, or a C file. They allow for spaces in the file name (requires escaping the additional quotes in the json using \"
). The shell is used as the runner, thus allowing the compilation (clang...
) and the execution (&& ./a.out
) of the program. It also assumes that the tasks.json "lives" in the local workspace (under the directory .vscode). Further task.json details, such as supported variables etc. can be found here.
For C++;
{
"version": "0.1.0",
"isShellCommand": true,
"taskName": "GenericBuild",
"showOutput": "always",
"command": "sh",
"suppressTaskName": false,
"args": ["-c", "clang++ -std=c++14 -Wall -Wextra -pedantic -pthread \"${file}\" && ./a.out"]
}
For C;
{
"version": "0.1.0",
"isShellCommand": true,
"taskName": "GenericBuild",
"showOutput": "always",
"command": "sh",
"suppressTaskName": false,
"args": ["-c", "clang -std=c11 -Wall -Wextra -pedantic -pthread \"${file}\" && ./a.out"] // command arguments...
}
Just to elaborate on an earlier suggestion by David Thomas:
a[href^="tel"]{
color:inherit;
text-decoration:none;
}
Adding this to your css leaves the functionality of the phone number but strips the underline and matches the color you were using originally.
Strange that I can post my own answer but I can't respond to someone else's..
I think you can try "Google Grid Gallery", it based on aforementioned Masonry with some additions, like styles and viewer.
I have another example, that I made for my process:
I get an Array with value-Description like this
states = [{
status: '1',
desc: '\u2713'
}, {
status: '2',
desc: '\u271B'
}]
in my Filters.js:
.filter('getState', function () {
return function (input, states) {
//console.log(states);
for (var i = 0; i < states.length; i++) {
//console.log(states[i]);
if (states[i].status == input) {
return states[i].desc;
}
}
return '\u2718';
};
})
Then, a test var (controller):
function myCtrl($scope, $filter) {
// ....
var resp = $filter('getState')('1', states);
// ....
}
This will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are doing is generally correct.
set.py:
import sys
sys.path.append("/tmp/TEST")
loop.py
import sys
import time
while True:
print sys.path
time.sleep(1)
run: python loop.py &
This will run loop.py, connected to your STDOUT, and it will continue to run in the background. You can then run python set.py
. Each has a different set of environment variables. Observe that the output from loop.py
does not change because set.py
does not change loop.py
's environment.
A note on importing
Python imports are dynamic, like the rest of the language. There is no static linking going on. The import is an executable line, just like sys.path.append...
.
For anyone who comes here with the similar message:
Unable to open debugger port (127.0.0.1:50470):
java.net.SocketException "Interrupted function call: accept failed"
This may be caused by something completely independent, i.e. it's not a port configuration. If you're running Tomcat, for instance, it may be that you have an invalid web.xml
. Check your Event Log for any previous errors:
Cannot load C:\...\conf\web.xml: ParseError at [row,col]:[480,29]
Message: The element type "param-value" must be terminated by the matching end-tag "</param-value>".
You could do something like this if you wanted
package main
import "fmt"
type Pair struct {
a, b interface{}
}
func main() {
p1 := Pair{"finished", 42}
p2 := Pair{6.1, "hello"}
fmt.Println("p1=", p1, "p2=", p2)
fmt.Println("p1.b", p1.b)
// But to use the values you'll need a type assertion
s := p1.a.(string) + " now"
fmt.Println("p1.a", s)
}
However I think what you have already is perfectly idiomatic and the struct describes your data perfectly which is a big advantage over using plain tuples.
See http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx
This explains that Unicode versions of Windows APIs have higher limits, and how to enable that.
yes, %c
will print a single char:
printf("%c", 'h');
also, putchar
/putc
will work too. From "man putchar":
#include <stdio.h>
int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c);
* fputc() writes the character c, cast to an unsigned char, to stream.
* putc() is equivalent to fputc() except that it may be implemented as a macro which evaluates stream more than once.
* putchar(c); is equivalent to putc(c,stdout).
EDIT:
Also note, that if you have a string, to output a single char, you need get the character in the string that you want to output. For example:
const char *h = "hello world";
printf("%c\n", h[4]); /* outputs an 'o' character */
The ALL_DIRECTORIES
data dictionary view will have information about all the directories that you have access to. That includes the operating system path
SELECT owner, directory_name, directory_path
FROM all_directories
You can use sklearn.utils.shuffle()
(requires sklearn 0.16.1 or higher to support Pandas data frames):
# Generate data
import pandas as pd
df = pd.DataFrame({'A':range(5), 'B':range(5)})
print('df: {0}'.format(df))
# Shuffle Pandas data frame
import sklearn.utils
df = sklearn.utils.shuffle(df)
print('\n\ndf: {0}'.format(df))
outputs:
df: A B
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
df: A B
1 1 1
0 0 0
3 3 3
4 4 4
2 2 2
Then you can use df.reset_index()
to reset the index column, if needs to be:
df = df.reset_index(drop=True)
print('\n\ndf: {0}'.format(df)
outputs:
df: A B
0 1 1
1 0 0
2 4 4
3 2 2
4 3 3
Another simple way you can do this is by adding a click event, through a class name to the anchor tags on the page to detect when it has been clicked, then you can now use the window.location.href to get the url data which you can use to run your ajax request to the server. Simple and Easy.
I think you might be looking for an "anchor" given the example you have.
<a href="#jump">This link will jump to the anchor named jump</a>
<a name="jump">This is where the link will jump to</a>
The focus jQuery method does something different from what you're trying to achieve.
just add in your backend API new property's into response body. from example .net core:
[Authorize]
[HttpGet]
public async Task<IActionResult> GetUsers([FromQuery]UserParams userParams)
{
var users = await _repo.GetUsers(userParams);
var usersToReturn = _mapper.Map<IEnumerable<UserForListDto>>(users);
// create new object and add into it total count param etc
var UsersListResult = new
{
usersToReturn,
currentPage = users.CurrentPage,
pageSize = users.PageSize,
totalCount = users.TotalCount,
totalPages = users.TotalPages
};
return Ok(UsersListResult);
}
In body response it look like this
{
"usersToReturn": [
{
"userId": 1,
"username": "[email protected]",
"firstName": "Joann",
"lastName": "Wilson",
"city": "Armstrong",
"phoneNumber": "+1 (893) 515-2172"
},
{
"userId": 2,
"username": "[email protected]",
"firstName": "Booth",
"lastName": "Drake",
"city": "Franks",
"phoneNumber": "+1 (800) 493-2168"
}
],
// metadata to pars in client side
"currentPage": 1,
"pageSize": 2,
"totalCount": 87,
"totalPages": 44
}
Hopefully this can help somebody: for some reason I couldn't track because of lack of time, if you have a form like:
<form (ngSubmit)="doSubmit($event)">
<button (click)="clearForm()">Clear</button>
<button type="submit">Submit</button>
</form>
when you hit the Enter
button, the clearForm
function is called, even though the expected behaviour was to call the doSubmit
function.
Changing the Clear
button to a <a>
tag solved the issue for me.
I would still like to know if that's expected or not. Seems confusing to me
You can use:
echo '<?php if(function_exists("my_func")) echo "function exists"; ' | php
The short tag "< ?=" can be helpful too:
echo '<?= function_exists("foo") ? "yes" : "no";' | php
echo '<?= 8+7+9 ;' | php
The closing tag "?>" is optional, but don't forget the final ";"!
It's my way to resolve this question. Tested on SQLServer2008R2
CREATE PROC SearchAllTables
@SearchStr nvarchar(100)
AS
BEGIN
DECLARE @dml nvarchar(max) = N''
IF OBJECT_ID('tempdb.dbo.#Results') IS NOT NULL DROP TABLE dbo.#Results
CREATE TABLE dbo.#Results
([tablename] nvarchar(100),
[ColumnName] nvarchar(100),
[Value] nvarchar(max))
SELECT @dml += ' SELECT ''' + s.name + '.' + t.name + ''' AS [tablename], ''' +
c.name + ''' AS [ColumnName], CAST(' + QUOTENAME(c.name) +
' AS nvarchar(max)) AS [Value] FROM ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) +
' (NOLOCK) WHERE CAST(' + QUOTENAME(c.name) + ' AS nvarchar(max)) LIKE ' + '''%' + @SearchStr + '%'''
FROM sys.schemas s JOIN sys.tables t ON s.schema_id = t.schema_id
JOIN sys.columns c ON t.object_id = c.object_id
JOIN sys.types ty ON c.system_type_id = ty.system_type_id AND c .user_type_id = ty .user_type_id
WHERE t.is_ms_shipped = 0 AND ty.name NOT IN ('timestamp', 'image', 'sql_variant')
INSERT dbo.#Results
EXEC sp_executesql @dml
SELECT *
FROM dbo.#Results
END
This should work:
find DIR_NAME -type f | wc -l
Explanation:
-type f
to include only files.|
(and not ¦
) redirects find
command's standard output to wc
command's standard input.wc
(short for word count) counts newlines, words and bytes on its input (docs).-l
to count just newlines.Notes:
DIR_NAME
with .
to execute the command in the current folder.-type f
to include directories (and symlinks) in the count.Explanation of why your example does not work:
In the command you showed, you do not use the "Pipe" (|
) to kind-of connect two commands, but the broken bar (¦
) which the shell does not recognize as a command or something similar. That's why you get that error message.
I have faced the same problem, and I fixed it in Linux.
Check your $JAVA_HOME
Need JDK 1.8 to compile/build APK
Install Java JDK 1.8 and change the JAVA_HOME
Edit ~/.bashrc
and add your JDK 1.8 path as JAVA_HOME
.
export JAVA_HOME=/usr/lib/jvm/java-8-oracle/jre/
And source ~/.bashrc
Close the current terminal window/tab and run $JAVA_HOME
to check the path.
You can just add these code in AppServiceProvider class boot method.
Blade::extend(function($value, $compiler){
$value = preg_replace('/(\s*)@switch\((.*)\)(?=\s)/', '$1<?php switch($2):', $value);
$value = preg_replace('/(\s*)@endswitch(?=\s)/', '$1endswitch; ?>', $value);
$value = preg_replace('/(\s*)@case\((.*)\)(?=\s)/', '$1case $2: ?>', $value);
$value = preg_replace('/(?<=\s)@default(?=\s)/', 'default: ?>', $value);
$value = preg_replace('/(?<=\s)@breakswitch(?=\s)/', '<?php break;', $value);
return $value;
});
then you can use as:
@switch( $item )
@case( condition_1 )
// do something
@breakswitch
@case( condition_2 )
// do something else
@breakswitch
@default
// do default behaviour
@breakswitch
@endswitch
Enjoy It~
Can't comment because I don't have enough reputation points, but recode only works on a vector, so the above code in @Stefano's answer should be
df <- iris %>%
mutate(Species = recode(Species,
setosa = "SETOSA",
versicolor = "VERSICOLOR",
virginica = "VIRGINICA")
)
catch (Exception ex) { ... }
WILL catch RuntimeException.
Whatever you put in catch block will be caught as well as the subclasses of it.
A brute force approach:
.gitmodules
file in the supermodule to point to the new submodule url,supermodule/.gitmodules
,.gitmodules
file are reflected in the clone),git submodule update --init path-to-submodule
on the submodule,et voilà! The submodule in the new clone of the supermodule is properly configured!
You cannot set or read cookies on CORS requests through JavaScript. Although CORS allows cross-origin requests, the cookies are still subject to the browser's same-origin policy, which means only pages from the same origin can read/write the cookie. withCredentials
only means that any cookies set by the remote host are sent to that remote host. You will have to set the cookie from the remote server by using the Set-Cookie
header.
More recent answer in the case you want to delete every entries in every tables:
def reset
Rails.application.eager_load!
ActiveRecord::Base.descendants.each { |c| c.delete_all unless c == ActiveRecord::SchemaMigration }
end
More information about the eager_load
here.
After calling it, we can access to all of the descendants of ActiveRecord::Base
and we can apply a delete_all
on all the models.
Note that we make sure not to clear the SchemaMigration table.
I don't like to use setTimeout in or even have strange temporary inputs. So I came up with this.
Simply change your password field type to text
<input name="password" type="text" value="">
And when the user focus that input change it again to password
$('input[name=password]').on('focus', function (e) {
$(e.target).attr('type', 'password');
});
Its working using latest Chrome (Version 54.0.2840.71 (64-bit))
This is how to assign a value to a variable:
SELECT @EmpID = Id
FROM dbo.Employee
However, the above query is returning more than one value. You'll need to add a WHERE
clause in order to return a single Id
value.
I faced the same exception while trying to test my web-services deployed to WSO2 ESB.
WSO2 generated both wsdl and wsdl2. I tried to pass a wsdl2 URL and got the above exception. Quick googling showed me, that one of differences between wsdl1.1 and wsdl2.0 is replacing 'definitions' element with 'description'. Also, I found out, that SoapUI does not support wsdl2.
Therefore, for me the solution was to use wsdl1 url instead of wsdl2.
Just like any other collection. With the addition of the List<T>.ForEach
method.
foreach (var item in myMoney)
Console.WriteLine("amount is {0}, and type is {1}", item.amount, item.type);
for (int i = 0; i < myMoney.Count; i++)
Console.WriteLine("amount is {0}, and type is {1}", myMoney[i].amount, myMoney[i].type);
myMoney.ForEach(item => Console.WriteLine("amount is {0}, and type is {1}", item.amount, item.type));
What you can do is:
Update your local git repo:
git fetch
Build a local branch and checkout on it:
git branch pouet && git checkout pouet
Apply the commit you want on this branch:
git cherry-pick abcdefabcdef
(abcdefabcdef is the sha1 of the commit you want to apply)
What kind of problem do you get with jregex? It worked well for me under java5 and java6.
Jregex does the job well (even if the last version is from 2002), unless you want to wait for javaSE 7.
Hope below helps!
PS C:\Users\aameer>$invoice = $object.'Invoice Month'
$invoice = "01-" + $invoice
[datetime]$Format_date =$invoice
Now type is converted. You can use method or can access any property.
Example :$Format_date.AddDays(5)
As an alternative answer, there's a command line to invoke directly the Control Panel, which is javaws -viewer
, should work for both openJDK and Oracle's JDK (thanks @Nasser for checking the availability in Oracle's JDK)
Same caution to run as the user you need to access permissions with applies.
You can expect that exception is not thrown by creating a rule.
@Rule
public ExpectedException expectedException = ExpectedException.none();
Concatenate "
as a ceparate cell:
A | B | C | D
1 " | text | " | =CONCATENATE(A1; B1; C1);
D1 displays "text"
Still better solution could be to follow a design pattern such that the back-button press event gets propagated from active fragment down to host Activity. So, it's like.. if one of the active fragments consume the back-press, the Activity wouldn't get to act upon it, and vice-versa.
One way to do it is to have all your Fragments extend a base fragment that has an abstract 'boolean onBackPressed()' method.
@Override
public boolean onBackPressed() {
if(some_condition)
// Do something
return true; //Back press consumed.
} else {
// Back-press not consumed. Let Activity handle it
return false;
}
}
Keep track of active fragment inside your Activity and inside it's onBackPressed callback write something like this
@Override
public void onBackPressed() {
if(!activeFragment.onBackPressed())
super.onBackPressed();
}
}
This post has this pattern described in detail
Beware of using vars as the target directory name for WORKDIR
- doing that appears to result in a "cannot normalize nothing" fatal error. IMO, it's also worth pointing out that WORKDIR
behaves in the same way as mkdir -p <path>
i.e. all elements of the path are created if they don't exist already.
UPDATE:
I encountered the variable related problem (mentioned above) whilst running a multi-stage build - it now appears that using a variable is fine - if it (the variable) is "in scope" e.g. in the following, the 2nd WORKDIR
reference fails ...
FROM <some image>
ENV varname varval
WORKDIR $varname
FROM <some other image>
WORKDIR $varname
whereas, it succeeds in this ...
FROM <some image>
ENV varname varval
WORKDIR $varname
FROM <some other image>
ENV varname varval
WORKDIR $varname
.oO(Maybe it's in the docs & I've missed it)
double a_nan = strtod("NaN", NULL);
double a_inf = strtod("Inf", NULL);
About this I think you can reference to http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html.
Here're my understandings about this, with the Identity Federation Use Case to give a details for those concepts:
IdP provides the Persistent identifiers, they are used for linking to the local accounts in SPs, but they identify as the user profile for the specific service each alone. For example, the persistent identifiers are kind of like : johnForAir, jonhForCar, johnForHotel, they all just for one specified service, since it need to link to its local identity in the service.
Transient identifiers are what IdP tell the SP that the users in the session have been granted to access the resource on SP, but the identities of users do not offer to SP actually. For example, The assertion just like “Anonymity(Idp doesn’t tell SP who he is) has the permission to access /resource on SP”. SP got it and let browser to access it, but still don’t know Anonymity' real name.
The explanation for it in the spec is "The interpretation of the content of the element is left to individual implementations". Which means IdP defines the real format for it, and it assumes that SP knows how to parse the format data respond from IdP. For example, IdP gives a format data "UserName=XXXXX Country=US", SP get the assertion, and can parse it and extract the UserName is "XXXXX".
You can use ren
(as in rename):
ren *.XXX *.YYY
And of course, switch XXX and YYY for the appropriate extensions. It will change from XXX to YYY. If you want to change all extensions, just use the wildcard again:
ren *.* *.YYY
One way to make this work recursively is with the FOR
command. It can be used with the /R
option to recursively apply a command to matching files. For example:
for /R %x in (*.txt) do ren "%x" *.renamed
will change all .txt
extensions to .renamed
recursively, starting in the current directory.
%x
is the variable that holds the matched file names.
And, since you have thousands of files, make sure to wait until the cursor starts blinking again indicating that it's done working.
Note: this works only on cmd. Won't work on Powershell or Bash
Another option are the excellent Elevation PowerToys by Michael Murgolo on TechNet at http://technet.microsoft.com/en-us/magazine/2008.06.elevation.aspx.
They include PowerShell Prompt Here and PowerShell Prompt Here as Administrator.
I find the answers to this question to be problematic, confusing and incomplete, so I'll make an effort to do better.
Nobody has really answered this in any complete fashion. The information on setting locks in the Access options has nothing to do with read vs. write locking. No Locks vs. All Records vs. Edited Record is how you set the default record locking for WRITES.
No locks means you are using OPTIMISTIC locking, which means you allow multiple users to edit the record and then inform them after the fact if the record has changed since they launched their own edits. Optimistic locking is what you should start with as it requires no coding to implement it, and for small users populations it hardly ever causes a problem.
All Records means that the whole table is locked any time an edit is launched.
Edited Record means that fewer records are locked, but whether or not it's a single record or more than one record depends on whether your database is set up to use record-level locking (first added in Jet 4) or page-level locking. Frankly, I've never thought it worth the trouble to set up record-level locking, as optimistic locking takes care of most of the problems.
One might think that you want to use record-level pessimistic locking, but the fact is that in the vast majority of apps, two users are almost never editing the same record. Now, obviously, certain kinds of apps might be exceptions to that, but if I ran into such an app, I'd likely try to engineer it away by redesigning the schema so that it would be very uncommon for two users to edit the same record (usually by going to some form of transactional editing instead, where changes are made by adding records, rather than editing the existing data).
Now, for your actual question, there are a number of ways to accomplish restricting some users to read-only and granting others write privileges. Jet user-level security was intended for this purpose and works fine insofar as it's "security" for any meaningful definition of the term. In general, as long as you're using a Jet/ACE data store, the best security you're going to get is that provided by Jet ULS. It's crackable, yes, but your users would be committing a firable offense by breaking it, so it might be sufficient.
I would tend to not implement Jet ULS at all and instead just architect the data editing forms such that they checked the user's Windows logon and made the forms read-only or writable depending on which users are supposed to get which access. Whether or not you want to record group membership in a data table, or maintain Windows security groups for this purpose is up to you. You could also use a Jet workgroup file to deal with it, and provide a different system.mdw file for the write users. The read-only users would log on transparently as admin, and those logged on as admin would be granted only read-only access. The write users would log on as some other username (transparently, in the shortcut you provide them for launching the app, supplying no password), and that would be used to set up the forms as read or write.
If you use Jet ULS, it can become really hairy to get it right. It involves locking down all the tables as read-only (or maybe not even that) and then using RWOP queries to provide access to the data. I haven't done but one such app in my 14 years of professional Access development.
To summarize my answers to the parts of your question:
I would recommend doing this in the application, setting forms to read/only or editable at runtime depending on the user logon. The easiest approach is to set your forms to be read-only and change to editable for the write users when they open the form.
Not in any meaningful sense. Jet/ACE does have read locks, but they are there only for the purpose of maintaining state for individual views, and for refreshing data for the user. They do not lock out write operations of any kind, though the overhead of tracking them theoretically slows things down. It's not enough to worry about.
Access in combination with Jet/ACE does this for you automatically, particularly if you choose optimistic locking as your default. The key point here is that Access apps are databound, so as soon as a form is loaded, the record has a read lock, and as soon as the record is edited, whether or not it is write-locked for other users is determined by whether you are using optimistic or pessimistic locking. Again, this is the kind of thing Access takes care of for you with its default behaviors in bound forms. You don't worry about any of it until the point at which you encounter problems.
Basically, other than setting editability at runtime (according to who has write access), there is no coding necessary if you're using optimistic locking. With pessimistic locking, you don't have to code, but you will almost always need to, as you can't just leave the user stuck with the default behaviors and error messages.
Jet/ACE has support for commit/rollback transactions, but it's not clear to me if that's what you mean in this question. In general, I don't use transactions except for maintaining atomicity, e.g., when creating an invoice, or doing any update that involves multiple tables. It works about the way you'd expect it to but is not really necessary for the vast majority of operations in an Access application.
Perhaps one of the issues here (particularly in light of the first question) is that you may not quite grasp that Access is designed for creating apps with data bound to the forms. "Transactions" is a topic of great importance for unbound and stateless apps (e.g., browser-based), but for data bound apps, the editing and saving all happens transparently.
For certain kinds of operations this can be problematic, and occasionally it's appropriate to edit data in Access with unbound forms. But that's very seldom the case, in my experience. It's not that I don't use unbound forms -- I use lots of them for dialogs and the like -- it's just that my apps don't edit data tables with unbound forms. With almost no exceptions, all my apps edit data with bound forms.
Now, unbound forms are actually fairly easy to implement in Access (particularly if you name your editing controls the same as the underlying fields), but going with unbound data editing forms is really missing the point of using Access, which is that the binding is all done for you. And the main drawback of going unbound is that you lose all the record-level form events, such as OnInsert, BeforeUpdate and so forth.
This is one of the questions that's been well-addressed. All multi-user or replicated Access apps should be split, and most single-user apps should be, too. It's good design and also makes the apps more stable, as only the data tables end up being opened by more than one user at a time.
"Things?" What things?
I don't know anything specifically about Oracle (none of my clients could afford it even if they wanted to), but asking for a comparison of Access and Oracle betrays a fundamental misunderstanding somewhere along the line.
Access is an application development tool.
Oracle is an industrial strength database server.
Apples and oranges.
Now, of course, Access ships with a default database engine, originally called Jet and now revised and renamed ACE, but there are many levels at which Access the development platform can be entirely decoupled from Jet/ACE, the default database engine.
In this case, you've chosen to use a Jet/ACE back end, which will likely be just fine for small user populations, i.e., under 25. Jet/ACE can also be fine up to 50 or 100, particularly when only a few of the simultaneous users have write permission. While the 255-user limit in Jet/ACE includes both read-only and write users, it's the number of write users that really controls how many simultaneous users you can support, and in your case, you've got an app with mostly read-only users, so it oughtn't be terribly difficult to engineer a good app that has no problems with the back end.
Basically, I think your Oracle background is likely leading you to misunderstand how to develop in Access, where the expected approach is to bind your forms to recordsources that are updated without any need to write code. Now, for efficiency's sake it's a good idea to bind your forms to subsets of records, rather than to whole tables, but even with an entire table in the recordsource behind a data editing form, Access is going to be fairly efficient in editing Jet/ACE tables (the old myth about pulling the whole table across the wire is still out there) as long your data tables are efficiently indexed.
Record locking is something you mostly shouldn't have any cause to worry about, and one of the reasons for that is because of bound editing, where the form knows what's going on in the back end at all times (well, at intervals about a second apart, the default refresh interval). That is, it's not like a web page where you retrieve a copy of the data and then post your edits back to the server in a transaction completely unconnected to the original data retrieval operation. In a bound environment like Access, the locking file on the back-end data file is always going to be keeping track of the fact that someone has the record open for editing. This prevents a user's edits from stomping on someone else's edits, because Access knows the state and informs the user. This all happens without any coding on the part of the developer and is one of the great advantages of the bound editing model (aside from not having to write code to post the edits).
For all those who are experienced database programmers familiar with other platforms who are coming to Access for the first time, I strongly suggest using Access like an end user. Try out all the point and click features. Run the form and report wizards and check out the results that they produce. I can't vouch for all of them as demonstrating good practices, but they definitely demonstrate the default assumptions behind the way Access is intended to be used.
If you find yourself writing a lot of code, then you're likely missing the point of Access.
I do a lot of Novell Identity Manager stuff, and XPATH in that context looks a little different.
Assume the value you are looking for is in a string variable, called TARGET, then the XPATH would be:
count(attr/value[.='$TARGET']/preceding-sibling::*)+1
Additionally it was pointed out that to save a few characters of space, the following would work as well:
count(attr/value[.='$TARGET']/preceding::*) + 1
I also posted a prettier version of this at Novell's Cool Solutions: Using XPATH to get the position node
When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.
http://api.jqueryui.com/datepicker/#option-maxDate
$( ".selector" ).datepicker( "option", "maxDate", '+0m +0w' );
Use StrictMode Something like this:-
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
I wanted a function that would join tables without requiring you to define the columns using an anonymous type selector, but had a hard time finding any. I ended up having to make my own. Hopefully this will help anyone in the future who searches for this:
private DataTable JoinDataTables(DataTable t1, DataTable t2, params Func<DataRow, DataRow, bool>[] joinOn)
{
DataTable result = new DataTable();
foreach (DataColumn col in t1.Columns)
{
if (result.Columns[col.ColumnName] == null)
result.Columns.Add(col.ColumnName, col.DataType);
}
foreach (DataColumn col in t2.Columns)
{
if (result.Columns[col.ColumnName] == null)
result.Columns.Add(col.ColumnName, col.DataType);
}
foreach (DataRow row1 in t1.Rows)
{
var joinRows = t2.AsEnumerable().Where(row2 =>
{
foreach (var parameter in joinOn)
{
if (!parameter(row1, row2)) return false;
}
return true;
});
foreach (DataRow fromRow in joinRows)
{
DataRow insertRow = result.NewRow();
foreach (DataColumn col1 in t1.Columns)
{
insertRow[col1.ColumnName] = row1[col1.ColumnName];
}
foreach (DataColumn col2 in t2.Columns)
{
insertRow[col2.ColumnName] = fromRow[col2.ColumnName];
}
result.Rows.Add(insertRow);
}
}
return result;
}
An example of how you might use this:
var test = JoinDataTables(transactionInfo, transactionItems,
(row1, row2) =>
row1.Field<int>("TransactionID") == row2.Field<int>("TransactionID"));
One caveat: This is certainly not optimized, so be mindful when getting to row counts above 20k. If you know that one table will be larger than the other, try to put the smaller one first and the larger one second.
What you have is a parse error. Those are thrown before any code is executed. A PHP file needs to be parsed in its entirety before any code in it can be executed. If there's a parse error in the file where you're setting your error levels, they won't have taken effect by the time the error is thrown.
Either break your files up into smaller parts, like setting the error levels in one file and then include
ing another file which contains the actual code (and errors), or set the error levels outside PHP using php.ini or .htaccess directives.
You are not specified your project as right way.
XAMPP control panel
then start the apache
and MySQL
localhost:80\
press enter now your php basic Config page is visible.xampp\htdocs\YourFloderName
Then
create php file then save it and go to browser then type it localhost\YourFolderName
now it listed the files click the file and it runs.Yes, an instance variable will be initialized to a default value. For a local variable, you need to initialize before use:
public class Main {
int instaceVariable; // An instance variable will be initialized to the default value
public static void main(String[] args) {
int localVariable = 0; // A local variable needs to be initialized before use
}
}
I believe running from Eclipse, if you're using "myconf.properties" as the relative path, You file structure should look somehting like this
ProjectRoot
src
bin
myconf.properties
Eclipse will look for the the file in the project root dir if no other dirs are specified in the file path
if you got actuall time in mind GETDATE()
would be the function what you looking for
In Objective C
-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
In swift
func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)
Override this method to detect the orientation change.
spring data save()
method will help you to perform both: adding new item and updating an existed item.
Just call the save()
and enjoy the life :))
No for the moment.
I doubt it will be possible for the future for ActiveX support will be discontinued in near future (as MS stated).
Look here about HTML Object tag, but not anything will be accepted. You should try.
I got rid of this same error in index.ts
with these combined properties:
In tsconfig.json:
"compilerOptions": {
"target": "ES6"
And in package.json:
"main": "index.ts",
"scripts": {
"start": "tsc -p tsconfig.json && node index.js"
if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.
PictureBox picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(100, 50),
Location = new Point(14, 17),
Image = Image.FromFile(@"c:\Images\test.jpg"),
SizeMode = PictureBoxSizeMode.CenterImage
};
p.Controls.Add(picture);
OR
PictureBox picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(100, 50),
Location = new Point(14, 17),
ImageLocation = @"c:\Images\test.jpg",
SizeMode = PictureBoxSizeMode.CenterImage
};
p.Controls.Add(picture);
i'm not sure where you put images in your folder structure but you can find the path as bellow
picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");
ASP.NET MVC offers us three options ViewData, ViewBag, and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility. Lets discuss or get key points on those three objects:
Similarities between ViewBag & ViewData :
Difference between ViewBag & ViewData:
ViewBag & ViewData Example:
public ActionResult Index()
{
ViewBag.Name = "Monjurul Habib";
return View();
}
public ActionResult Index()
{
ViewData["Name"] = "Monjurul Habib";
return View();
}
In View:
@ViewBag.Name
@ViewData["Name"]
TempData:
TempData is also a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value. The difference is that the life cycle of the object. TempData keep the information for the time of an HTTP Request. This mean only from one page to another. This also work with a 302/303 redirection because it’s in the same HTTP Request. Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect, “TempData” helps to maintain data between those redirects. It internally uses session variables. Temp data use during the current and subsequent request only means it is use when you are sure that next request will be redirecting to next view. It requires typecasting for complex data type and check for null values to avoid error. Generally used to store only one time messages like error messages, validation messages.
public ActionResult Index()
{
var model = new Review()
{
Body = "Start",
Rating=5
};
TempData["ModelName"] = model;
return RedirectToAction("About");
}
public ActionResult About()
{
var model= TempData["ModelName"];
return View(model);
}
The last mechanism is the Session which work like the ViewData, like a Dictionary that take a string for key and object for value. This one is stored into the client Cookie and can be used for a much more long time. It also need more verification to never have any confidential information. Regarding ViewData or ViewBag you should use it intelligently for application performance. Because each action goes through the whole life cycle of regular asp.net mvc request. You can use ViewData/ViewBag in your child action but be careful that you are not using it to populate the unrelated data which can pollute your controller.
This is a quite confusing way of using Apache configuration directives.
Technically, the first bit is equivalent to
Allow From All
This is because Order Deny,Allow
makes the Deny directive evaluated before the Allow Directives.
In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.
Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.
The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.
Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.
It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.
The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy all
</Files>
which forbids access to any file beginning by ".ht".
The equivalent Apache 2.4 configuration should look like:
<Files ~ "^\.ht">
Require all denied
</Files>
From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.
The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.
If this issue is causing serious problems, here are a few things I would suggest:
Revert back to JDK 1.7.0_25 until a fix is added to the JDK.
Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.
Try the JDK early releases as they come out. One of them might fix your problem.
Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.
It happens also if your code is expecting Java Mail 1.4 and your jars are Java Mail 1.3. Happened to me when upgraded Pentaho Kettle
Regards
Try this:
ALTER DATABASE [DATABASE_NAME]
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE
You can do this in any program other than Explorer
, e.g. Notepad
, cmd.exe
etc.
You just can't do it in Explorer, and Raymond Chen has offered an explanation as to why not.
The .NET implementation of UrlEncode
does not comply with RFC 3986.
Some characters are not encoded but should be. The !()*
characters are listed in the RFC's section 2.2 as a reserved characters that must be encoded yet .NET fails to encode these characters.
Some characters are encoded but should not be. The .-_
characters are not listed in the RFC's section 2.2 as a reserved character that should not be encoded yet .NET erroneously encodes these characters.
The RFC specifies that to be consistent, implementations should use upper-case HEXDIG, where .NET produces lower-case HEXDIG.
This problem could be solved as mentioned using the .on
on jQuery 1.7+ versions.
Unfortunately, this didn't work within my code (and I have 1.11) so I used:
$('body').delegate('.logout-link','click',function() {
http://api.jquery.com/delegate/
As of jQuery 3.0, .delegate() has been deprecated. It was superseded by the .on() method since jQuery 1.7, so its use was already discouraged. For earlier versions, however, it remains the most effective means to use event delegation. More information on event binding and delegation is in the .on() method. In general, these are the equivalent templates for the two methods:
// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, selector, data, handler );
This comment might help others :) !
You have no storage allocated for word
- it's just a dangling pointer.
Change:
char * word;
to:
char word[256];
Note that 256 is an arbitrary choice here - the size of this buffer needs to be greater than the largest possible string that you might encounter.
Note also that fgets is a better (safer) option then scanf for reading arbitrary length strings, in that it takes a size
argument, which in turn helps to prevent buffer overflows:
fgets(word, sizeof(word), stdin);
You can also use query(), i.e.:
df_filtered = df.query('a == 4 & b != 2')
Logically, Cody's answer should work. However I don't think the command prompt handles a code block logically. For the life of me I can't get that to work properly with any more than a single command within the block. In my case, extensive testing revealed that all of the commands within the block are being cached, and executed simultaneously at the end of the block. This of course doesn't yield the expected results. Here is an oversimplified example:
if %ERRORLEVEL%==0 (
set var1=blue
set var2=cheese
set var3=%var1%_%var2%
)
This should provide var3 with the following value:
blue_cheese
but instead yields:
_
because all 3 commands are cached and executed simultaneously upon exiting the code block.
I was able to overcome this problem by re-writing the if block to only execute one command - goto - and adding a few labels. Its clunky, and I don't much like it, but at least it works.
if %ERRORLEVEL%==0 goto :error0
goto :endif
:error0
set var1=blue
set var2=cheese
set var3=%var1%_%var2%
:endif
In Linux systems, you can use file command. It will give the correct encoding
Sample:
file blah.csv
Output:
blah.csv: ISO-8859 text, with very long lines
As suggested above the inclusion of
/usr/lib/openmpi/include
in the include path takes care of this (in my case)
I've done this kind of thing with a form that contains a TextBox.
So if you wanted to put this in say cell H1
, then use:
ActiveSheet.Range("H1").Value = txtBoxName.Text
To remove all child elements from your div:
$('#mysweetdiv').empty();
.removeData()
and the corresponding .data()
function are used to attach data behind an element, say if you wanted to note that a specific list element referred to user ID 25 in your database:
var $li = $('<li>Joe</li>').data('id', 25);
I won't stress much on the difference as it is already covered, but notice the below:
android:backgroundTint
android:backgroundTintMode
are only available at API 21android:background
, and you want to change its default color, then you can use android:backgroundTint
to add a shade to it.example
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:background="@android:drawable/ic_dialog_email" />
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:background="@android:drawable/ic_dialog_email"
android:backgroundTint="@color/colorAccent" />
Another example
If you try to change the accent color of the FloatingActionButton
using android:background
you won't notice a change, that is because it's already utilizes app:srcCompat
, so in order to do that you can use android:backgroundTint
instead
I tried all the suggestions mentioned above and nothing worked. I terminated the current instance, launched another one and repeated the same exact process. This time no problems. Sometimes it might be the remote ami's fault.