These are the versions of C# known about at the time of this writing:
Dispose
on IEnumerator
s which implemented IDisposable
. A few other small features.var
), query expressionsdynamic
), delegate and interface generic variance, more COM support, named arguments, tuple data type and optional parametersawait
in catch
and finally
, extension Add
methods in collection initializers.out
parameter declarations, local functions, binary literals, digit separators, and arbitrary async returns.unmanaged
generic type constraints. ref
reassignment. Unsafe improvements: stackalloc
initialization, unpinned indexed fixed
buffers, custom fixed
statements. Improved overloading resolution. Expression variables in initializers and queries. ==
and !=
defined for tuples. Auto-properties' backing fields can now be targeted by attributes.new
expressions, target typed ??
and ?
), covariant returns. Minor features: relax ordering of ref
and partial
modifiers, parameter null checking, lambda discard parameters, native int
s, attributes on local functions, function pointers, static lambdas, extension GetEnumerator
, module initializers, extending partial.What are the correct version numbers for C#? What came out when? Why can't I find any answers about C# 3.5?
There is no such thing as C# 3.5 - the cause of confusion here is that the C# 3.0 is present in .NET 3.5. The language and framework are versioned independently, however - as is the CLR, which is at version 2.0 for .NET 2.0 through 3.5, .NET 4 introducing CLR 4.0, service packs notwithstanding. The CLR in .NET 4.5 has various improvements, but the versioning is unclear: in some places it may be referred to as CLR 4.5 (this MSDN page used to refer to it that way, for example), but the Environment.Version
property still reports 4.0.xxx.
As of May 3, 2017, the C# Language Team created a history of C# versions and features on their GitHub repository: Features Added in C# Language Versions. There is also a page that tracks upcoming and recently implemented language features.
Regarding the question,
” can someone explain why the
compare()
function exists if a comparison can be made using simple operands?
Relative to <
and ==
, the compare
function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.
As an example of simplicity, for small integer values you can write a compare function like this:
auto compare( int a, int b ) -> int { return a - b; }
which is highly efficient.
Now for a structure
struct Foo
{
int a;
int b;
int c;
};
auto compare( Foo const& x, Foo const& y )
-> int
{
if( int const r = compare( x.a, y.a ) ) { return r; }
if( int const r = compare( x.b, y.b ) ) { return r; }
return compare( x.c, y.c );
}
Trying to express this lexicographic compare directly in terms of <
you wind up with horrendous complexity and inefficiency, relatively speaking.
With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.
This solutions worked perfectly for me to render the datepicker on top of bootstrap modal.
http://jsfiddle.net/cmpgtuwy/654/
HTML
<br/>
<div class="wrapper">
Some content goes here<br />
Some more content.
<div class="row">
<div class="col-xs-4">
<!-- padding for jsfiddle -->
<div class="input-group date" id="dtp">
<input type="text" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon-calendar glyphicon"></span>
</span>
</div>
</div>
</div>
</div>
Javascript
$('#dtp').datetimepicker({
format: 'MMM D, YYYY',
widgetParent: 'body'});
$('#dtp').on('dp.show', function() {
var datepicker = $('body').find('.bootstrap-datetimepicker-widget:last');
if (datepicker.hasClass('bottom')) {
var top = $(this).offset().top + $(this).outerHeight();
var left = $(this).offset().left;
datepicker.css({
'top': top + 'px',
'bottom': 'auto',
'left': left + 'px'
});
}
else if (datepicker.hasClass('top')) {
var top = $(this).offset().top - datepicker.outerHeight();
var left = $(this).offset().left;
datepicker.css({
'top': top + 'px',
'bottom': 'auto',
'left': left + 'px'
});
}
});
CSS
.wrapper {
height: 100px;
overflow: auto;}
body {
position: relative;
}
There's also AppGyver Steroids that unites PhoneGap and Native UI nicely.
With Steroids you can add things like native tabs, native navigation bar, native animations and transitions, native modal windows, native drawer/panel (facebooks side menu) etc. to your PhoneGap app.
Here's a demo: http://youtu.be/oXWwDMdoTCk?t=20m17s
If you just want the content as string
, then the simple solution is to use the ReadFile
function from the io/ioutil
package. This function returns a slice of bytes
which you can easily convert to a string
.
package main
import (
"fmt"
"io/ioutil"
)
func main() {
b, err := ioutil.ReadFile("file.txt") // just pass the file name
if err != nil {
fmt.Print(err)
}
fmt.Println(b) // print the content as 'bytes'
str := string(b) // convert content to a 'string'
fmt.Println(str) // print the content as a 'string'
}
Where is this info kept ("this connection is between computer
A
and serverF
")?
A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.
HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.
This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.
When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection
No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.
which is only for my session ?
Does it mean that no one else can use that connection
That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.
If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?
Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:
if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)
An typical keep-alive response looks like this:
Keep-Alive: timeout=15, max=100
See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):
A host sets the value of the timeout
parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.
The max
parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.
However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.
You have two options here, 1. Use for
instead for foreach
for iteration.But in your case the collection is IEnumerable and the upper limit of the collection is unknown so foreach will be the best option. so i prefer to use another integer variable to hold the iteration count: here is the code for that:
int i = 0; // for index
foreach (var row in list)
{
bool IsChecked;// assign value to this variable
if (IsChecked)
{
// use i value here
}
i++; // will increment i in each iteration
}
Your main objective in crafting your questions should be to make it as easy as possible for readers to understand and reproduce your problem on their systems. To do so:
This does take some work, but it seems like a fair trade-off since you ask others to do work for you.
The best option by far is to rely on built-in datasets. This makes it very easy for others to work on your problem. Type data()
at the R prompt to see what data is available to you. Some classic examples:
iris
mtcars
ggplot2::diamonds
(external package, but almost everyone has it)Inspect the built-in datasets to find one suitable for your problem.
If you can rephrase your problem to use the built-in datasets, you are much more likely to get good answers (and upvotes).
If your problem is specific to a type of data that is not represented in the existing data sets, then provide the R code that generates the smallest possible dataset that your problem manifests itself on. For example
set.seed(1) # important to make random data reproducible
myData <- data.frame(a=sample(letters[1:5], 20, rep=T), b=runif(20))
Someone trying to answer my question can copy/paste those two lines and start working on the problem immediately.
As a last resort, you can use dput
to transform a data object to R code (e.g. dput(myData)
). I say as a "last resort" because the output of dput
is often fairly unwieldy, annoying to copy-paste, and obscures the rest of your question.
Someone once said:
A picture of expected output is worth 1000 words
-- a sage person
If you can add something like "I expected to get this result":
cyl mean.hp
1: 6 122.28571
2: 4 82.63636
3: 8 209.21429
to your question, people are much more likely to understand what you are trying to do quickly. If your expected result is large and unwieldy, then you probably haven't thought enough about how to simplify your problem (see next).
The main thing to do is simplify your problem as much as possible before you ask your question. Re-framing the problem to work with the built-in datasets will help a lot in this regard. You will also often find that just by going through the process of simplification, you will answer your own problem.
Here are some examples of good questions:
In both cases, the user's problems are almost certainly not with the simple examples they provide. Rather they abstracted the nature of their problem and applied it to a simple data set to ask their question.
This answer focuses on what I think is the best practice: use built-in data sets and provide what you expect as a result in a minimal form. The most prominent answers focus on other aspects. I don't expect this answer to rising to any prominence; this is here solely so that I can link to it in comments to newbie questions.
You need:
li.Where(w=> w.name == "di").ToList().ForEach(i => i.age = 10);
Program code:
namespace Test
{
class Program
{
class Myclass
{
public string name { get; set; }
public decimal age { get; set; }
}
static void Main(string[] args)
{
var list = new List<Myclass> { new Myclass{name = "di", age = 0}, new Myclass{name = "marks", age = 0}, new Myclass{name = "grade", age = 0}};
list.Where(w=> w.name == "di").ToList().ForEach(i => i.age = 10);
list.ForEach(i => Console.WriteLine(i.name + ":" + i.age));
}
}
}
Output:
di:10
marks:0
grade:0
You have to set a default value.
ALTER TABLE mytable ADD COLUMN mycolumn character varying(50) NOT NULL DEFAULT 'foo';
... some work (set real values as you want)...
ALTER TABLE mytable ALTER COLUMN mycolumn DROP DEFAULT;
If you want to do rsync and use custom user and custom ssh key, you need to write this key in rsync options.
---
- name: rsync
hosts: serverA,serverB,serverC,serverD,serverE,serverF
gather_facts: no
vars:
ansible_user: oracle
ansible_ssh_private_key_file: ./mykey
src_file: "/path/to/file.txt"
tasks:
- name: Copy Remote-To-Remote from serverA to server{B..F}
synchronize:
src: "{{ src_file }}"
dest: "{{ src_file }}"
rsync_opts:
- "-e ssh -i /remote/path/to/mykey"
delegate_to: serverA
If you have extra fields in the form that not defined in Entity , $form->getData()
doesn't work , one way could be this :
$request->get("form")["foo"]
Or :
$form->get('foo')->getData();
ACL was overkill for my requirements also.
I ended up creating a library similar to @Alexander's to inject a GrantedAuthority
list for Role->Permissions based on the role membership of a user.
For example, using a DB to hold the relationships -
@Autowired
RolePermissionsRepository repository;
public void setup(){
String roleName = "ROLE_ADMIN";
List<String> permissions = new ArrayList<String>();
permissions.add("CREATE");
permissions.add("READ");
permissions.add("UPDATE");
permissions.add("DELETE");
repository.save(new RolePermissions(roleName, permissions));
}
When an Authentication object is injected in the current security session, it will have the original roles/granted authorities.
This library provides 2 built-in integration points for Spring Security.
When the integration point is reached, the PermissionProvider is called to get the effective permissions for each role the user is a member of.
The distinct list of permissions are added as GrantedAuthority items in the Authentication object.
You can also implement a custom PermissionProvider
to store the relationships in config for example.
A more complete explanation here - https://stackoverflow.com/a/60251931/1308685
And the source code is here - https://github.com/savantly-net/spring-role-permissions
Create a plain text file (using notepad) and type the exact line you would use to run your Java file with the command prompt. Then change the extension to .bat and you're done.
Double clicking on this file would run your java program.
I reccommend one file for javac, one for java so you can troubleshoot if anything is wrong.
You will need to get a DateTime
object from your TimeSpan
and then you can format it easily.
One possible solution is adding the timespan to any date with zero time value.
var timespan = new TimeSpan(3, 0, 0);
var output = new DateTime().Add(timespan).ToString("hh:mm tt");
The output value will be "03:00 AM"
(for english locale).
Who are you writing the message for? And is that reader typically reading the message pre- or post- ownership the commit themselves?
I think good answers here have been given from both perspectives, I’d perhaps just fall short of suggesting there is a best answer for every project. The split vote might suggest as much.
i.e. to summarise:
Is the message predominantly for other people, typically reading at some point before they have assumed the change: A proposal of what taking the change will do to their existing code.
Is the message predominantly as a journal/record to yourself (or to your team), but typically reading from the perspective of having assumed the change and searching back to discover what happened.
Perhaps this will lead the motivation for your team/project, either way.
Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.
When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.
When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.
You'll find more details about the specification and how to generate such a certificate in this answer.
I had this issue when the user connecting to the database had CONNECT permissions, but no permissions to read from the database. In my case, I could not even do something like this:
object userNameObj = command.ExecuteScalar()
Putting this in a try/catch (which you should probably be doing anyway) was the only way I could see to handle the insufficient permission issue.
Like this:
#include <vector>
// ...
std::vector<std::vector<int>> A(dimension, std::vector<int>(dimension));
(Pre-C++11 you need to leave whitespace between the angled brackets.)
This should work:
s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)
ifdef $(HAVE_CLIENT) libtest_LIBS = \ $(top_builddir)/libclient.la else ifdef $(HAVE_SERVER) libtest_LIBS = \ $(top_builddir)/libserver.la else libtest_LIBS = endif endif
NOTE: DO NOT indent the if then it don't work!
You could simply go to phpmyadmin.conf file and change "deny from all" to "allow from all". Well it worked for me, hope it works for you as well.
The Javadoc generation can be skipped by setting the property maven.javadoc.skip
to true [1], i.e.
-Dmaven.javadoc.skip=true
(and not false)
The maximum value that a Java Integer
can handle is 2147483657, or 2^31-1. The hexadecimal number AA0F245C is 2853119068 as a decimal number, and is far too large, so you need to use
Long.parseLong("AA0F245C", 16);
to make it work.
I was trying to achieve the exact opposite when I bumped on this thread. I know it's quite old, but here's my solution nonetheless. You can use blocks, see here. In this case, compile the following code (with the right imports):
> String s = "äêìóblah";
> Pattern p = Pattern.compile("[\\p{InLatin-1Supplement}]+"); // this regex uses a block
> Matcher m = p.matcher(s);
> System.out.println(m.find());
> System.out.println(s.replaceAll(p.pattern(), "#"));
You should see the following output:
true
#blah
Best,
Q:Can't bind to 'pSelectableRow' since it isn't a known property of 'tr'.
A:you need to configure the primeng tabulemodule in ngmodule
It's also important to realize that simply moving the program break pointer around with brk
and sbrk
doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.
This is not as complicated as some of the other answers make it.
Just use auto layout to add constraints to pin the left and top sides of the label.
After that it will automatically resize.
No need to set sizeToFit
when using auto layout. My complete code for the example project is here:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myLabel: UILabel!
@IBAction func changeTextButtonTapped(sender: UIButton) {
myLabel.text = "my name is really long i want it to fit in this box"
}
}
myLabel.preferredMaxLayoutWidth = 150 // or whatever
in code. (I also pinned my button to the bottom of the label so that it would move down when the label height increased.)UITableViewCell
then see this answer.Try this:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
RewriteRule ^$ store [L]
If you want an external redirect (which cause the visiting browser to show the redirected URL), set the R
flag there as well:
RewriteRule ^$ /store [L,R=301]
There's a couple of strong reasons to use iterators, some of which are mentioned here:
i.e., if you go from a std::vector to a std::list, or std::set, you can't use numerical indices to get at your contained value. Using an iterator is still valid.
If you modify your container in the middle of your loop, the next time you use your iterator it will throw an invalid iterator exception.
In very simple terms (because the other answers are referring you to all the official design patterns anyway, so look at them for further details):
If you want to have a class which is monitored by other classes in the ecosystem of your program you say that you want the class to be observable. I.e. there might be some changes in its state which you would want to broadcast to the rest of the program.
Now, to do this we have to call some kind of method. We don't want the Observable class to be tightly coupled with the classes that are interested in observing it. It doesn't care who it is as long as it fulfils certain criteria. (Imagine it is a radio station, it doesn't care who is listening as long as they have an FM radio tuned on their frequency). To achieve that we use an interface, referred to as the Observer.
Therefore, the Observable class will have a list of Observers (i.e. instances implementing the Observer interface methods you might have). Whenever it wants to broadcast something, it just calls the method on all the observers, one after the other.
The last thing to close the puzzle is how will the Observable class know who is interested?
So the Observable class must offer some mechanism to allow Observers to register their interest. A method such as addObserver(Observer o)
internally adds the Observer to the list of observers, so that when something important happens, it loops through the list and calls the respective notification method of the Observer interface of each instance in the list.
It might be that in the interview they did not ask you explicitly about the java.util.Observer
and java.util.Observable
but about the generic concept. The concept is a design pattern, which Java happens to provide support for directly out of the box to help you implement it quickly when you need it. So I would suggest that you understand the concept rather than the actual methods/classes (which you can look up when you need them).
UPDATE
In response to your comment, the actual java.util.Observable
class offers the following facilities:
Maintaining a list of java.util.Observer
instances. New instances interested in being notified can be added through addObserver(Observer o)
, and removed through deleteObserver(Observer o)
.
Maintaining an internal state, specifying whether the object has changed since the last notification to the observers. This is useful because it separates the part where you say that the Observable
has changed, from the part where you notify the changes. (E.g. Its useful if you have multiple changes happening and you only want to notify at the end of the process rather than at each small step). This is done through setChanged()
. So you just call it when you changed something to the Observable
and you want the rest of the Observers
to eventually know about it.
Notifying all observers that the specific Observable
has changed state. This is done through notifyObservers()
. This checks if the object has actually changed (i.e. a call to setChanged()
was made) before proceeding with the notification. There are 2 versions, one with no arguments and one with an Object
argument, in case you want to pass some extra information with the notification. Internally what happens is that it just iterates through the list of Observer
instances and calls the update(Observable o, Object arg)
method for each of them. This tells the Observer
which was the Observable object that changed (you could be observing more than one), and the extra Object arg
to potentially carry some extra information (passed through notifyObservers()
.
I use:
Imports System.IO
Dim strPath as String=Directory.GetCurrentDirectory
Try this:
foreach (string file in Directory.GetFiles(@"c:\directory\"))
File.Delete(file);
I know this is an old question, but maybe I can be of help to someone, bc this also stumped me until I read the documentation a bit more:
prevArrow string (html|jQuery selector) | object (DOM node|jQuery object) Previous Allows you to select a node or customize the HTML for the "Previous" arrow.
nextArrow string (html|jQuery selector) | object (DOM node|jQuery object) Next Allows you to select a node or customize the HTML for the "Next" arrow.
this is how i changed my buttons.. worked perfectly.
$('.carousel-content').slick({
prevArrow:"<img class='a-left control-c prev slick-prev' src='../images/shoe_story/arrow-left.png'>",
nextArrow:"<img class='a-right control-c next slick-next' src='../images/shoe_story/arrow-right.png'>"
});
You can use QString.arg like this
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", "Jane");
// You get "~/Tom-Jane.txt"
This method is preferred over sprintf because:
Changing the position of the string without having to change the ordering of substitution, e.g.
// To get "~/Jane-Tom.txt"
QString my_formatted_string = QString("%1/%3-%2.txt").arg("~", "Tom", "Jane");
Or, changing the type of the arguments doesn't require changing the format string, e.g.
// To get "~/Tom-1.txt"
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", QString::number(1));
As you can see, the change is minimal. Of course, you generally do not need to care about the type that is passed into QString::arg() since most types are correctly overloaded.
One drawback though: QString::arg() doesn't handle std::string. You will need to call: QString::fromStdString() on your std::string to make it into a QString before passing it to QString::arg(). Try to separate the classes that use QString from the classes that use std::string. Or if you can, switch to QString altogether.
UPDATE: Examples are updated thanks to Frank Osterfeld.
UPDATE: Examples are updated thanks to alexisdm.
Try to use
table {
table-layout: auto;
}
If you use Bootstrap, class table
has table-layout: fixed;
by default.
Try requests instead of urllib and you don't need to bother with urlencode!
import requests
requests.get('http://youraddress.com', params=evt.fields)
EDIT:
If you need ordered name-value pairs or multiple values for a name then set params like so:
params=[('name1','value11'), ('name1','value12'), ('name2','value21'), ...]
instead of using a dictionary.
Just clone one of your existing repos, this will prompt you for new credentials:
e.g.
git clone https://[email protected]/mypath/myrepo.git
// https://[email protected]/mypath/myrepo.git is an address of one of your existing repos.
I think it is not totally unrelated but did you consider canvas? something like Process JS can make it simpler.
CSharpJExcel for reading Excel 97-2003 files (XLS), ExcelPackage for reading Excel 2007/2010 files (Office Open XML format, XLSX), and ExcelDataReader that seems to have the ability to handle both formats
Good luck!
function _formatDatetime(date: Date, format: string) {
const _padStart = (value: number): string => value.toString().padStart(2, '0');
return format
.replace(/yyyy/g, _padStart(date.getFullYear()))
.replace(/dd/g, _padStart(date.getDate()))
.replace(/mm/g, _padStart(date.getMonth() + 1))
.replace(/hh/g, _padStart(date.getHours()))
.replace(/ii/g, _padStart(date.getMinutes()))
.replace(/ss/g, _padStart(date.getSeconds()));
}
function isValidDate(d: Date): boolean {
return !isNaN(d.getTime());
}
export function formatDate(date: any): string {
var datetime = new Date(date);
return isValidDate(datetime) ? _formatDatetime(datetime, 'yyyy-mm-dd hh:ii:ss') : '';
}
Try:
$("#"+styleTarget).css({ 'font-size': $(this).val() });
By putting the value in quotes, it becomes a string, and "+$(this).val()+"px
is definitely not close to a font value. There are a couple of ways of setting the style properties of an element:
Using a map:
$("#elem").css({
fontSize: 20
});
Using key and value parameters:
All of these are valid.
$("#elem").css("fontSize", 20);
$("#elem").css("fontSize", "20px");
$("#elem").css("font-size", "20");
$("#elem").css("font-size", "20px");
You can replace "fontSize"
with "font-size"
but it will have to be quoted then.
If you have import android.support.v7.app.ActionBarActivity;
and your class extends ActionBarActivity
then use this in your OnCreate
:
android.support.v7.app.ActionBar AB=getSupportActionBar();
AB.hide();
For some reason android studio doesn't like calling app icon from drawable folder. So in that case I created mipmap resource directory under res folder.
Right click res folder > new > android resource directory > resource type: mipmap and now drop any icon in there then reference that into manifest file. Sharing this since this method worked for me.
android:icon:@drawable/ic_launcher"
to
android:icon="@mipmap/ic_launcher"
There's a whole page of the Django documentation devoted to this, well indexed from the contents page.
As that page states, you need to do:
my_obj.categories.add(fragmentCategory.objects.get(id=1))
or
my_obj.categories.create(name='val1')
For me the problem with collecting user's email addres on PHP side (getGraphUser() method) was, that the default behavior of facebook-rendered button (on WEBSIDE side, created with xfbml=1) is to implicity calling FB.login() with the scope NOT including "email".
That means you MUST:
1) call
FB.login(....,{scope: email})
manifestly, creating your own button to start login process
OR
2) add scope="email" attribute to the xfbml button
<div class="fb-login-button" data-size="large" data-button-type="continue_with" data- layout="rounded" data-auto-logout-link="false" data-use-continue-as="true" data- width="1000px" scope="email"></div>
to be able to collect email address on PHP side.
Hope it helps.
In addition to all the concerns expressed about why you give a rat's ass what the ID value is (all are correct that you shouldn't), let me add this to the mix:
If you've deleted all the records from the table, compacting the database will reset the seed value back to its original value.
For a table where there are still records, and you've inserted a value into the Autonumber field that is lower than the highest value, you have to use @Remou's method to reset the seed value. This also applies if you want to reset to the Max+1 in a table where records have been deleted, e.g., 300 records, last ID of 300, delete 201-300, compact won't reset the counter (you have to use @Remou's method -- this was not the case in earlier versions of Jet, and, indeed, in early versions of Jet 4, the first Jet version that allowed manipulating the seed value programatically).
Use the constructor overload which takes a Comparator<? super E> comparator
and pass in a comparator which compares in the appropriate way for your sort order. If you give an example of how you want to sort, we can provide some sample code to implement the comparator if you're not sure. (It's pretty straightforward though.)
As has been said elsewhere: offer
and add
are just different interface method implementations. In the JDK source I've got, add
calls offer
. Although add
and offer
have potentially different behaviour in general due to the ability for offer
to indicate that the value can't be added due to size limitations, this difference is irrelevant in PriorityQueue
which is unbounded.
Here's an example of a priority queue sorting by string length:
// Test.java
import java.util.Comparator;
import java.util.PriorityQueue;
public class Test {
public static void main(String[] args) {
Comparator<String> comparator = new StringLengthComparator();
PriorityQueue<String> queue = new PriorityQueue<String>(10, comparator);
queue.add("short");
queue.add("very long indeed");
queue.add("medium");
while (queue.size() != 0) {
System.out.println(queue.remove());
}
}
}
// StringLengthComparator.java
import java.util.Comparator;
public class StringLengthComparator implements Comparator<String> {
@Override
public int compare(String x, String y) {
// Assume neither string is null. Real code should
// probably be more robust
// You could also just return x.length() - y.length(),
// which would be more efficient.
if (x.length() < y.length()) {
return -1;
}
if (x.length() > y.length()) {
return 1;
}
return 0;
}
}
Here is the output:
short
medium
very long indeed
When installing SQL 2019 Python, there are known issues for PIP which require a fix (step 7) https://docs.microsoft.com/en-us/sql/advanced-analytics/known-issues-for-sql-server-machine-learning-services?view=sql-server-ver15
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Workaround
Copy the following files:
libssl-1_1-x64.dll
libcrypto-1_1-x64.dll
from the folder
C:\Program Files\Microsoft SQL Server\MSSSQL15.MSSQLSERVER\PYTHON_SERVICES\Library\bin
to the folder
C:\Program Files\Microsoft SQL Server\MSSSQL15.MSSQLSERVER\PYTHON_SERVICES\DLLs
Then open a new DOS command shell prompt.
ls=['hello','world']
ls.append('python')
['hello', 'world', 'python']
or (use insert
function where you can use index position in list)
ls.insert(0,'python')
print(ls)
['python', 'hello', 'world']
in batch file abc.bat
cd c:\user\ben_dchost\documents\
executible.exe -flag1 -flag2 -flag3
I am assuming that your executible.exe
is present in c:\user\ben_dchost\documents\
I am also assuming that the parameters it takes are -flag1
-flag2
-flag3
Edited:
For the command you say you want to execute, do:
cd C:\Users\Ben\Desktop\BGInfo\
bginfo.exe dc_bginfo.bgi
pause
Hope this helps
Simplification from the above Andrew's answer leads to this key theme to generate the half border.
theme (panel.border = element_blank(),
axis.line = element_line(color='black'))
When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.
With Basic Auth, the HTTP request from the question will look something like this:
GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk
The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password)
.
To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl
, the username and password will be clearly visible on the process list and might turn up in the bash history file.
When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.
Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.
When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.
Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.
In case one does not have sudo privilege, but still needs to install the library.
Download source for the software/library using:
apt-get source libaio
or
wget https://src.fedoraproject.org/lookaside/pkgs/libaio/libaio-0.3.110.tar.gz/2a35602e43778383e2f4907a4ca39ab8/libaio-0.3.110.tar.gz
unzip the library
Install with the following command to user-specific library:
make prefix=`pwd`/usr install #(Copy from INSTALL file of libaio-0.3.110)
or
make prefix=/path/to/your/lib/libaio install
Include libaio library into LD_LIBRARY_PATH for your app:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/your/lib/libaio/lib
Now, your app should be able to find libaio.so.1
I wrote about my initial experience regarding AMQP, Qpid and ZeroMQ here: http://ron.shoutboot.com/2010/09/25/is-ampq-for-you/
My subjective opinion is that AMQP is fine if you really need the persistent messaging facilities and is not too concerned that the broker may be a bottleneck. Also, C++ client is currently missing for AMQP (Qpid didn't win my support; not sure about the ActiveMQ client however), but maybe work in progress. ZeroMQ may be the way otherwise.
Using SDK Manager to download Intel HAX did not work.
Downloading and installing it from the Intel website did work. http://software.intel.com/en-us/articles/intel-hardware-accelerated-execution-manager/
Top Tip: making the change in my BIOS to enable virtualization and then using "restart" did not enable virtualization. Doing a cold boot (i.e. shutdown and restart) suddenly made it appear.
The first step (on Windows) is to make sure that the Micrsoft Hardware-Assisted Virtualization Tool reports that "this computer is configured with hardware-assisted virtualization". http://www.microsoft.com/en-us/download/details.aspx?id=592
You can use curly braces like expression with both double quotes and single quotes for space i.e.,
{" "} or {' '}
You can also use ES6 template literals i.e.,
` <li></li>` or ` ${value}`
You can also use   like below (inside span)
<span>sample text </span>
You can also use   in dangerouslySetInnerHTML when printing html content
<div dangerouslySetInnerHTML={{__html: 'sample html text: '}} />
Read from sys.stdin
, but to read binary data on Windows, you need to be extra careful, because sys.stdin
there is opened in text mode and it will corrupt \r\n
replacing them with \n
.
The solution is to set mode to binary if Windows + Python 2 is detected, and on Python 3 use sys.stdin.buffer
.
import sys
PY3K = sys.version_info >= (3, 0)
if PY3K:
source = sys.stdin.buffer
else:
# Python 2 on Windows opens sys.stdin in text mode, and
# binary data that read from it becomes corrupted on \r\n
if sys.platform == "win32":
# set sys.stdin to binary mode
import os, msvcrt
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
source = sys.stdin
b = source.read()
If you want to select ALL(columns) data as distinct frrom a DataFrame (df), then
df.select('*').distinct().show(10,truncate=False)
I believe you are misinterpreting the JSON format for key values. You should store your string as
NSString *jsonString = @"{\"ID\":{\"Content\":268,\"type\":\"text\"},\"ContractTemplateID\":{\"Content\":65,\"type\":\"text\"}}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
Now if you do following NSLog statement
NSLog(@"%@",[json objectForKey:@"ID"]);
Result would be another NSDictionary.
{
Content = 268;
type = text;
}
Hope this helps to get clear understanding.
Regarding tokens carrying information, JSON Web Tokens (http://jwt.io) is a brilliant technology. The main concept is to embed information elements (claims) into the token, and then signing the whole token so that the validating end can verify that the claims are indeed trustworthy.
I use this Java implementation: https://bitbucket.org/b_c/jose4j/wiki/Home
There is also a Spring module (spring-security-jwt), but I haven't looked into what it supports.
I have a BindingList<> object bind as a data source to dataGridView.
BindingList x1;
x1 = new BindingList<sourceObject>();
BindingSource bsx1 = new BindingSource();
bsx1.DataSource = x1;
dataGridView1.DataSource = bsx1;
When I clicked the column header, no sorting takes place. I used the SortableBindingList answer provided by Tom Bushell. Having included two source files into my project
Then this change is made to my code:
Be.Timvw.Framework.ComponentModel.SortableBindingList x1; // 1
x1 = new Be.Timvw.Framework.ComponentModel.SortableBindingList<sourceObject>(); // 2
BindingSource bsx1 = new BindingSource();
bsx1.DataSource = x1;
dataGridView1.DataSource = bsx1;
After these changes I performed a build on my program. I am now able to sort by clicking the column headers. Only two lines need changing, they are highlighted in the code snippet above by trailing comments.
As another guy described here, all you need to do is add
height: 100vh;
to the style of whatever you need to fill the screen
i have this error when using "--ui tdd". remove this or using "--ui bdd" fix problem.
Try
[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' )
[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' );
_x000D_
<select id="mySelect">
<option value="A">Text A</option>
<option value="B">Text B</option>
<option value="C">Text C</option>
</select>
_x000D_
This is how I've tackled a similar issue in an ES6 context:
function merge(array1, array2, prop) {
return array2.map(function (item2) {
var item1 = array1.find(function (item1) {
return item1[prop] === item2[prop];
});
return Object.assign({}, item1, item2);
});
}
Note: This approach will not return any items from array1 that don't appear in array2.
EDIT: I have some scenarios where I want to preserve items that don't appear in the second array so I came up with another method.
function mergeArrays(arrays, prop) {
const merged = {};
arrays.forEach(arr => {
arr.forEach(item => {
merged[item[prop]] = Object.assign({}, merged[item[prop]], item);
});
});
return Object.values(merged);
}
var arr1 = [
{ name: 'Bob', age: 11 },
{ name: 'Ben', age: 12 },
{ name: 'Bill', age: 13 },
];
var arr2 = [
{ name: 'Bob', age: 22 },
{ name: 'Fred', age: 24 },
{ name: 'Jack', age: 25 },
{ name: 'Ben' },
];
console.log(mergeArrays([arr1, arr2], 'name'));
A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next
. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear
below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:
On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
WScript.Echo "Error: " & Err.Number
WScript.Echo "Error (Hex): " & Hex(Err.Number)
WScript.Echo "Source: " & Err.Source
WScript.Echo "Description: " & Err.Description
Err.Clear ' Clear the Error
End If
On Error Goto 0 ' Don't resume on Error
WScript.Echo "This text will always print."
Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear
with WScript.Quit(Err.Number)
.
Also note the On Error Goto 0
which turns off resuming execution at the next statement when an error occurs.
If you want to test behavior for when the Set
succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp
.
The On Error
directive only affects the current running scope (current Sub
or Function
) and does not affect calling or called scopes.
If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise
. Err.Raise
takes up to five arguments, Number
, Source
, Description
, HelpFile
, and HelpContext
. Using help files and contexts is beyond the scope of this text. Number
is an error number you choose, Source
is the name of your application/class/object/property that is raising the error, and Description
is a short description of the error that occurred.
If MyValue <> 42 Then
Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If
You could then handle the raised error as discussed above.
Change Log
Err.Clear
before the possibly error causing line to clear any previous errors that may have been ignored.
On Error Resume Next
and Err.Clear
. Fixed some grammar to be less awkward. Added info on Err.Raise
. Formatting.
#try this one:
tuples = list(zip(data_set["data_date"], data_set["data_1"],data_set["data_2"]))
print (tuples)
First, you have to create your own inline TS-Class, since the FormData Class is not well supported at the moment:
var data : {
name: string;
file: File;
} = {
name: "Name",
file: inputValue.files[0]
};
Then you send it to the Server with JSON.stringify(data)
let opts: RequestOptions = new RequestOptions();
opts.method = RequestMethods.Post;
opts.headers = headers;
this.http.post(url,JSON.stringify(data),opts);
If you know, or can enforce the size for the to-be-upper element, you could use
position : absolute;
In your css and give the divs their position.
otherwise javascript seems the only way to go:
fd = document.getElementById( 'firstDiv' );
sd = document.getElementById( 'secondDiv' );
fd.parentNode.removeChild( fd );
sd.parentNode.insertAfter( fd, sd );
or something similar.
edit: I just found this which might be useful: w3 document css3 move-to
I'm also struck with this same problem, finally i got simple solution. just added one line to action bar style.
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="android:textColorPrimary">@color/colorAccent</item>
<item name="android:colorBackground">@color/colorAppWhite</item>
</style>
"android:colorBackground" is enough to change option menu background
Jquery like any other good JavaScript frameworks supplies you with functionality independent of browser platform wrapping all the intricacies, which you may not care about or don't want to care about.
I think using a framework is better instead of using pure JavaScript and doing all the stuff from scratch, unless you usage is very limited.
I definitely recommend JQuery!
Thanks
When signing into the server to execute the code use this instead:
ssh -X username@servername
the -X
will get rid of the no display name and no $DISPLAY environment variable
error
:)
This is the way I do it on Red Hat Linux systems.
Put your script in /etc/init.d
, owned by root and executable. At the top of the script, you can give a directive for chkconfig
. Example, the following script is used to start a Java application as user oracle.
The name of the script is /etc/init.d/apex
#!/bin/bash
# chkconfig: 345 99 10
# Description: auto start apex listener
#
case "$1" in
'start')
su - oracle -c "cd /opt/apex ; java -jar apex.war > logs/apex.log 2>logs/apex_error.log &";;
'stop')
echo "put something to shutdown or kill the process here";;
esac
This says that the script must run at levels 3, 4, and 5, and the priority for start/stop is 99 and 10.
Then, as user root
you can use chkconfig
to enable or disable the script at startup:
chkconfig --list apex
chkconfig --add apex
And you can use service start/stop apex
.
type-specific formatting
can be used as well:
t = datetime.datetime(2012, 2, 23, 0, 0)
"{:%m/%d/%Y}".format(t)
Output:
'02/23/2012'
As a quick example:
var name = 'jack';
var age = 40;
console.log('%s is %d yrs old',name,age);
The output is:
jack is 40 yrs old
git stash
+ rebase
automation
For when I need to modify an old commit a lot of times for Gerrit reviews, I've been doing:
git-amend-old() (
# Stash, apply to past commit, and rebase the current branch on to of the result.
current_branch="$(git rev-parse --abbrev-ref HEAD)"
apply_to="$1"
git stash
git checkout "$apply_to"
git stash apply
git add -u
git commit --amend --no-edit
new_sha="$(git log --format="%H" -n 1)"
git checkout "$current_branch"
git rebase --onto "$new_sha" "$apply_to"
)
Usage:
git add
if already in repogit-amend-old $old_sha
I like this over --autosquash
as it does not squash other unrelated fixups.
Try this
Dim app As Excel.Application = Nothing
Dim Active_Cell As Excel.Range = Nothing
Try
app = CType(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
Active_Cell = app.ActiveCell
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
' .address will return the cell reference :)
For adding background icon always before text when length of text is not known in advance.
.create:before{
content: "";
display: inline-block;
background: #ccc url(arrow.png) no-repeat;
width: 10px;background-size: contain;
height: 10px;
}
I had a similar issue where I also continuously got the same error. I tried many things like changing the listener port number, turning off the firewall etc. Finally I was able to resolve the issue by changing listener.ora file. I changed the following line:
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
to
(ADDRESS = (PROTOCOL = TCP)(HOST = hostname)(PORT = 1521))
I also added an entry in the /etc/hosts
file.
you can use Oracle net manager to change the above line in listener.ora file. See Oracle Net Services Administrator's Guide for more information on how to do it using net manager.
Also you can use the service name (database_name.domain_name
) instead of SID while making the connnection.
I Hope it helps.
You close the second Scanner
which closes the underlying InputStream
, therefore the first Scanner
can no longer read from the same InputStream
and a NoSuchElementException
results.
The solution: For console apps, use a single Scanner
to read from System.in
.
Aside: As stated already, be aware that Scanner#nextInt
does not consume newline characters. Ensure that these are consumed before attempting to call nextLine
again by using Scanner#newLine()
.
See: Do not create multiple buffered wrappers on a single InputStream
That depends on the situation. Often the most simple approach is the best because it is easy to understand:
if (something) {
otherThing = 1;
} else {
otherThing = 0;
}
or
int otherThing = something ? 1 : 0;
But sometimes it useful to use an Enum instead of a boolean flag. Let imagine there are synchronous and asynchronous processes:
Process process = Process.SYNCHRONOUS;
System.out.println(process.getCode());
In Java, enum can have additional attributes and methods:
public enum Process {
SYNCHRONOUS (0),
ASYNCHRONOUS (1);
private int code;
private Process (int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
What I used was a small hack. I used T(1), which returned an empty cell. T is a function in excel that returns its argument if its a string and an empty cell otherwise. So, what you can do is:
=IF(condition,T(1),value)
here is a simple way of calculating age:
//dob date dd/mm/yy
var d = 01/01/1990
//today
//date today string format
var today = new Date(); // i.e wed 04 may 2016 15:12:09 GMT
//todays year
var todayYear = today.getFullYear();
// today month
var todayMonth = today.getMonth();
//today date
var todayDate = today.getDate();
//dob
//dob parsed as date format
var dob = new Date(d);
// dob year
var dobYear = dob.getFullYear();
// dob month
var dobMonth = dob.getMonth();
//dob date
var dobDate = dob.getDate();
var yearsDiff = todayYear - dobYear ;
var age;
if ( todayMonth < dobMonth )
{
age = yearsDiff - 1;
}
else if ( todayMonth > dobMonth )
{
age = yearsDiff ;
}
else //if today month = dob month
{ if ( todayDate < dobDate )
{
age = yearsDiff - 1;
}
else
{
age = yearsDiff;
}
}
all of above answers would help you but you have to add three ports in the firewall of PC on which SQL Server is installed.
Add new TCP Local port in Windows firewall at port no. 1434
Add new program for SQL Server and select sql server.exe Path: C:\ProgramFiles\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Binn\sqlservr.exe
Add new program for SQL Browser and select sqlbrowser.exe Path: C:\ProgramFiles\Microsoft SQL Server\90\Shared\sqlbrowser.exe
Use UIAlertController instead of UIAlertView
-(void)showMessage:(NSString*)message withTitle:(NSString *)title
{
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:title
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//do something when click button
}];
[alert addAction:okAction];
UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
[vc presentViewController:alert animated:YES completion:nil];
}
bundler clean
Stopped the message showing for me, as a last step after I tried all of the above.
Use overloaded functions. Does not require dynamic_cast or even RTTI support:
class A {};
class B : public A {};
class Foo {
public:
void Bar(A& a) {
// do something
}
void Bar(B& b) {
Bar(static_cast<A&>(b));
// do B specific stuff
}
};
or do it with Route Attribute:
public class InventoryController : Controller
{
[Route("whatever/{firstItem}")]
public ActionResult ViewStockNext(int firstItem)
{
int yourNewVariable = firstItem;
// ...
}
}
For a more detailed answer on creating your own colormaps, I highly suggest visiting this page
If that answer is too much work, you can quickly make your own list of colors and pass them to the color
parameter. All the colormaps are in the cm
matplotlib module. Let's get a list of 30 RGB (plus alpha) color values from the reversed inferno colormap. To do so, first get the colormap and then pass it a sequence of values between 0 and 1. Here, we use np.linspace
to create 30 equally-spaced values between .4 and .8 that represent that portion of the colormap.
from matplotlib import cm
color = cm.inferno_r(np.linspace(.4, .8, 30))
color
array([[ 0.865006, 0.316822, 0.226055, 1. ],
[ 0.851384, 0.30226 , 0.239636, 1. ],
[ 0.832299, 0.283913, 0.257383, 1. ],
[ 0.817341, 0.270954, 0.27039 , 1. ],
[ 0.796607, 0.254728, 0.287264, 1. ],
[ 0.775059, 0.239667, 0.303526, 1. ],
[ 0.758422, 0.229097, 0.315266, 1. ],
[ 0.735683, 0.215906, 0.330245, 1. ],
.....
Then we can use this to plot, using the data from the original post:
import random
x = [{i: random.randint(1, 5)} for i in range(30)]
df = pd.DataFrame(x)
df.plot(kind='bar', stacked=True, color=color, legend=False, figsize=(12, 4))
This might work for you (GNU sed):
sed 'y/:/\n/' file
or perhaps:
sed y/:/$"\n"/ file
Setting net.ipv6.conf.all.forwarding=1
will fix the issue.
This can be done on a live system using
sudo sysctl -w net.ipv6.conf.all.forwarding=1
function findLongestWord(str) {
str = str.split(" ");
var sorted = str.sort(function(prev,current){
return prev.length - current.length;
});
var index = sorted.length;
str = sorted[index-1];
return str;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
if (-e $base_path)
{
# code
}
-e
is the 'existence' operator in Perl.
You can check permissions and other attributes using the code on this page.
You could use strftime
, but struct tm
doesn't have resolution for parts of seconds. I'm not sure if that's absolutely required for your purposes.
struct tm tm;
/* Set tm to the correct time */
char s[20]; /* strlen("2009-08-10 18:17:54") + 1 */
strftime(s, 20, "%F %H:%M:%S", &tm);
Somebody asked me to post a link to the framework! that I presented at Open World 2012. This is the full blog post that demonstrates how to architect a solution with external tables.
Your code won't work because you haven't assigned anything to n
before you first use it. Try this:
def oracle():
n = None
while n != 'Correct':
# etc...
A more readable approach is to move the test until later and use a break
:
def oracle():
guess = 50
while True:
print 'Current number = {0}'.format(guess)
n = raw_input("lower, higher or stop?: ")
if n == 'stop':
break
# etc...
Also input
in Python 2.x reads a line of input and then evaluates it. You want to use raw_input
.
Note: In Python 3.x, raw_input
has been renamed to input
and the old input
method no longer exists.
For what it's worth, I had the issue as well in IE11:
<!DOCTYPE html>
and IE=Edge
settings mentioned in the question<head>
elementAfter a while, I found out that:
HTTP Header:
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E)
but
JavaScript:
window.navigator.userAgent === 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; rv:11.0) like Gecko'
So I ended up doing the check on the client side.
And BTW, meanwhile, checking the user agent is no longer recommended. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent (but there might be a good case)
The .success
syntax was correct up to Angular v1.4.3.
For versions up to Angular v.1.6, you have to use then
method. The then()
method takes two arguments: a success
and an error
callback which will be called with a response object.
Using the then()
method, attach a callback
function to the returned promise
.
Something like this:
app.controller('MainCtrl', function ($scope, $http){
$http({
method: 'GET',
url: 'api/url-api'
}).then(function (response){
},function (error){
});
}
See reference here.
Shortcut
methods are also available.
$http.get('api/url-api').then(successCallback, errorCallback);
function successCallback(response){
//success code
}
function errorCallback(error){
//error code
}
The data you get from the response is expected to be in JSON
format.
JSON is a great way of transporting data, and it is easy to use within AngularJS
The major difference between the 2 is that .then()
call returns a promise
(resolved with a value returned from a callback
) while .success()
is more traditional way of registering callbacks
and doesn't return a promise
.
If you are on Eclipse,
Right click on your project folder under "Package Explorer".
Goto Source -> Clean up and choose your project.
This will cleanup any mess and your break-point should work now.
use strchr function when dealing with C strings.
const char * strchr ( const char * str, int character );
Here is an example of what you want to do.
/* strchr example */
#include <stdio.h>
#include <string.h>
int main ()
{
char invalids[] = ".@<>#";
char * pch;
pch=strchr(invalids,'s');//is s an invalid character?
if (pch!=NULL)
{
printf ("Invalid character");
}
else
{
printf("Valid character");
}
return 0;
}
Use memchr when dealing with memory blocks (as not null terminated arrays)
const void * memchr ( const void * ptr, int value, size_t num );
/* memchr example */
#include <stdio.h>
#include <string.h>
int main ()
{
char * pch;
char invalids[] = "@<>#";
pch = (char*) memchr (invalids, 'p', strlen(invalids));
if (pch!=NULL)
printf (p is an invalid character);
else
printf ("p valid character.\n");
return 0;
}
Easier still: return a pointer to a string that's been malloc'd with strdup.
#include <ncurses.h>
char * getStr(int length)
{
char word[length];
for (int i = 0; i < length; i++)
{
word[i] = getch();
}
word[i] = '\0';
return strdup(&word[0]);
}
int main()
{
char wordd[10];
initscr();
*wordd = getStr(10);
printw("The string is:\n");
printw("%s\n",*wordd);
getch();
endwin();
return 0;
}
This goes back to the basic difference between & and &&, | and ||
BTW you perform the same tasks many times. Not sure if efficiency is an issue. You could remove some of the duplication.
Z z2 = partialHits.get(req_nr).get(z); // assuming a value cannout be null.
Z z3 = tmpmap.get(z); // assuming z3 cannot be null.
if(z2 == null || z2 < z3){
partialHits.get(z).put(z, z3);
}
You will have to annotate your service with @Service
since you have said I am using annotations for mapping
Here's a solution with robocopy which copies the content of Folder1 into Folder2 going trough all subdirectories and automatically overwriting the files with the same name:
robocopy C:\Folder1 C:\Folder2 /COPYALL /E /IS /IT
Here:
/COPYALL
copies all file information
/E
copies subdirectories including empty directories
/IS
includes the same files
/IT
includes modified files with the same name
For more parameters see the official documentation: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy
Note: it can be necessary to run the command as administrator, because of the argument /COPYALL
. If you can't: just get rid of it.
No, cross-browser form custimization is very hard if not impossible to get it right for all browsers. If you really care about the appearance of those widgets you should use a javascript implementation.
see http://www.456bereastreet.com/archive/200409/styling_form_controls/ and http://developer.yahoo.com/yui/examples/button/btn_example07.html
I found an unorthodox way to accomplish this.
Just put the script page in an iframe. Doing so allows the page to be refreshed, seemingly even on older browsers without the "confirm form resubmission" message ever appearing.
All the symptoms you describe suggest that you never tell MySQL what time zone to use so it defaults to system's zone. Think about it: if all it has is '2011-03-13 02:49:10'
, how can it guess that it's a local Tanzanian date?
As far as I know, MySQL doesn't provide any syntax to specify time zone information in dates. You have to change it a per-connection basis; something like:
SET time_zone = 'EAT';
If this doesn't work (to use named zones you need that the server has been configured to do so and it's often not the case) you can use UTC offsets because Tanzania does not observe daylight saving time at the time of writing but of course it isn't the best option:
SET time_zone = '+03:00';
I think the "messy" second method, which is linked from another question here may be the only pure CSS solution.
If you're thinking about using JavaScript, then this was my solution to the problem:
demo: using a
canvas
element to fade text against an animated backgroundThe idea is that your element with the text and the
canvas
element are one on top of the other. You keep the text in your element (in order to allow text selection, which isn't possible withcanvas
text), but make it completely transparent (withrgba(0,0,0,0)
, in order to have the text visible in IE8 and older - that's because you have noRGBa
support and nocanvas
support in IE8 and older).You then read the text inside your element and write it on the canvas with the same font properties so that each letter you write on the canvas is over the corresponding letter in the element with the text.
The
canvas
element does not support multi-line text, so you'll have to break the text into words and then keep adding words on a test line which you then measure. If the width taken by the test line is bigger than the maximum allowed width you can have for a line (you get that maximum allowed width by reading the computed width of the element with the text), then you write it on the canvas without the last word added, you reset the test line to be that last word, and you increase the y coordinate at which to write the next line by one line height (which you also get from the computed styles of your element with the text). With each line that you write, you also decrease the opacity of the text with an appropriate step (this step being inversely proportional to the average number of characters per line).What you cannot do easily in this case is to justify text. It can be done, but it gets a bit more complicated, meaning that you would have to compute how wide should each step be and write the text word by word rather than line by line.
Also, keep in mind that if your text container changes width as you resize the window, then you'll have to clear the canvas and redraw the text on it on each resize.
OK, the code:
HTML:
<article> <h1>Interacting Spiral Galaxies NGC 2207/ IC 2163</h1> <em class='timestamp'>February 4, 2004 09:00 AM</em> <section class='article-content' id='art-cntnt'> <canvas id='c' class='c'></canvas>In the direction of <!--and so on--> </section> </article>
CSS:
html { background: url(moving.jpg) 0 0; background-size: 200%; font: 100%/1.3 Verdana, sans-serif; animation: ani 4s infinite linear; } article { width: 50em; /* tweak this ;) */ padding: .5em; margin: 0 auto; } .article-content { position: relative; color: rgba(0,0,0,0); /* add slash at the end to check they superimpose * color: rgba(255,0,0,.5);/**/ } .c { position: absolute; z-index: -1; top: 0; left: 0; } @keyframes ani { to { background-position: 100% 0; } }
JavaScript:
var wrapText = function(ctxt, s, x, y, maxWidth, lineHeight) { var words = s.split(' '), line = '', testLine, metrics, testWidth, alpha = 1, step = .8*maxWidth/ctxt.measureText(s).width; for(var n = 0; n < words.length; n++) { testLine = line + words[n] + ' '; metrics = ctxt.measureText(testLine); testWidth = metrics.width; if(testWidth > maxWidth) { ctxt.fillStyle = 'rgba(0,0,0,'+alpha+')'; alpha -= step; ctxt.fillText(line, x, y); line = words[n] + ' '; y += lineHeight; } else line = testLine; } ctxt.fillStyle = 'rgba(0,0,0,'+alpha+')'; alpha -= step; ctxt.fillText(line, x, y); return y + lineHeight; } window.onload = function() { var c = document.getElementById('c'), ac = document.getElementById('art-cntnt'), /* use currentStyle for IE9 */ styles = window.getComputedStyle(ac), ctxt = c.getContext('2d'), w = parseInt(styles.width.split('px')[0], 10), h = parseInt(styles.height.split('px')[0], 10), maxWidth = w, lineHeight = parseInt(styles.lineHeight.split('px')[0], 10), x = 0, y = parseInt(styles.fontSize.split('px')[0], 10), text = ac.innerHTML.split('</canvas>')[1]; c.width = w; c.height = h; ctxt.font = '1em Verdana, sans-serif'; wrapText(ctxt, text, x, y, maxWidth, lineHeight); };
Another way is to use an array as a type, e.g.:
ObjectMapper objectMapper = new ObjectMapper();
MyPojo[] pojos = objectMapper.readValue(json, MyPojo[].class);
This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list by:
List<MyPojo> pojoList = Arrays.asList(pojos);
IMHO this is much more readable.
And to make it be an actual list (that can be modified, see limitations of Arrays.asList()
) then just do the following:
List<MyPojo> mcList = new ArrayList<>(Arrays.asList(pojos));
In addition, If you know your code should not work if object is null, you can throw exception by using Optional.orElseThrow
String nullName = null;
String name = Optional.ofNullable(nullName)
.orElseThrow(NullPointerException::new);
// .orElseThrow(CustomException::new);
(Copying answer from question)
To add an insecure docker registry, add the file /etc/docker/daemon.json
with the following content:
{
"insecure-registries" : [ "hostname.cloudapp.net:5000" ]
}
and then restart docker.
malloc()
(and its friends free()
and realloc()
) is the way to do this in C.
A Popen
object has a .wait()
method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).
If you use this method, you'll prevent that the process zombies are lying around for too long.
(Alternatively, you can use subprocess.call()
or subprocess.check_call()
for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_
)call()
.)
If you have several subprocesses to wait for, you can do
exit_codes = [p.wait() for p in p1, p2]
which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.
Your use of it isn't a hack, though like many things in C++, mutable can be hack for a lazy programmer who doesn't want to go all the way back and mark something that shouldn't be const as non-const.
IF(compliment IN('set','Y',1), 'Y', 'N') AS customer_compliment
Will do the job as Buttle Butkus suggested.
Here is an example how I do it.
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import java.util.Map;
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>() {
}.getType();
MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
formData.add("key1", "value1");
formData.add("key1", "value2");
WebTarget webTarget = ClientBuilder.newClient().target("https://some.server.url/");
String response = webTarget.path("subpath/subpath2").request().post(Entity.form(formData), String.class);
Map<String, String> gsonResponse = gson.fromJson(response, type);
It would be interesting to have a csv serializer as it would take up the minimal space compared to other serializing method.
The closest support for java object to csv is stringutils provided by spring utils project
arrayToCommaDelimitedString(Object[] arr) but it is far from being a serializer.
Here is a simple utility which uses reflection to serialize value objects
public class CSVWriter
{
private static String produceCsvData(Object[] data) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
if(data.length==0)
{
return "";
}
Class classType = data[0].getClass();
StringBuilder builder = new StringBuilder();
Method[] methods = classType.getDeclaredMethods();
for(Method m : methods)
{
if(m.getParameterTypes().length==0)
{
if(m.getName().startsWith("get"))
{
builder.append(m.getName().substring(3)).append(',');
}
else if(m.getName().startsWith("is"))
{
builder.append(m.getName().substring(2)).append(',');
}
}
}
builder.deleteCharAt(builder.length()-1);
builder.append('\n');
for(Object d : data)
{
for(Method m : methods)
{
if(m.getParameterTypes().length==0)
{
if(m.getName().startsWith("get") || m.getName().startsWith("is"))
{
System.out.println(m.invoke(d).toString());
builder.append(m.invoke(d).toString()).append(',');
}
}
}
builder.append('\n');
}
builder.deleteCharAt(builder.length()-1);
return builder.toString();
}
public static boolean generateCSV(File csvFileName,Object[] data)
{
FileWriter fw = null;
try
{
fw = new FileWriter(csvFileName);
if(!csvFileName.exists())
csvFileName.createNewFile();
fw.write(produceCsvData(data));
fw.flush();
}
catch(Exception e)
{
System.out.println("Error while generating csv from data. Error message : " + e.getMessage());
e.printStackTrace();
return false;
}
finally
{
if(fw!=null)
{
try
{
fw.close();
}
catch(Exception e)
{
}
fw=null;
}
}
return true;
}
}
Here is an example value object
public class Product {
private String name;
private double price;
private int identifier;
private boolean isVatApplicable;
public Product(String name, double price, int identifier,
boolean isVatApplicable) {
super();
this.name = name;
this.price = price;
this.identifier = identifier;
this.isVatApplicable = isVatApplicable;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
public int getIdentifier() {
return identifier;
}
public void setIdentifier(int identifier) {
this.identifier = identifier;
}
public boolean isVatApplicable() {
return isVatApplicable;
}
public void setVatApplicable(boolean isVatApplicable) {
this.isVatApplicable = isVatApplicable;
}
}
and the code to run the util
public class TestCSV
{
public static void main(String... a)
{
Product[] list = new Product[5];
list[0] = new Product("dvd", 24.99, 967, true);
list[1] = new Product("pen", 4.99, 162, false);
list[2] = new Product("ipad", 624.99, 234, true);
list[3] = new Product("crayons", 4.99,127, false);
list[4] = new Product("laptop", 1444.99, 997, true);
CSVWriter.generateCSV(new File("C:\\products.csv"),list);
}
}
Output:
Name VatApplicable Price Identifier
dvd true 24.99 967
pen false 4.99 162
ipad true 624.99 234
crayons false 4.99 127
laptop true 1444.99 997
As per recent version. You need to go advanced settings. In this section you will find the un-publish button.
If you want to add a native library without interfering with java.library.path
at development time in Eclipse (to avoid including absolute paths and having to add parameters to your launch configuration), you can supply the path to the native libraries location for each Jar in the Java Build Path dialog under Native library location. Note that the native library file name has to correspond to the Jar file name. See also this detailed description.
Just to add to the other answers: In case you don't like the onload
callback approach, you can "promisify" it like so:
let url = "data:image/gif;base64,R0lGODl...";
let img = new Image();
await new Promise(r => img.onload=r, img.src=url);
// now do something with img
Here is another way you can get to the root of your website without hard coding the url:
var response = Request.CreateResponse(HttpStatusCode.Moved);
string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
response.Headers.Location = new Uri(fullyQualifiedUrl);
Note: Will only work if both your MVC website and WebApi are on the same URL
Most of the answers are outdated now. Better if you import tqdm correctly.
from tqdm import tqdm_notebook as tqdm
for some applications, for example google chrome, they store it under /opt. you can follow the above instruction using dpkg -l to get the correct naming then dpkg -L to get the detail.
hope it helps
So your endpoint address defined in your first example is incomplete. You must also define endpoint identity as shown in client configuration. In code you can try this:
EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
var address = new EndpointAddress("http://id.web/Services/EchoService.svc", spn);
var client = new EchoServiceClient(address);
litResponse.Text = client.SendEcho("Hello World");
client.Close();
Actual working final version by valamas
EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
Uri uri = new Uri("http://id.web/Services/EchoService.svc");
var address = new EndpointAddress(uri, spn);
var client = new EchoServiceClient("WSHttpBinding_IEchoService", address);
client.SendEcho("Hello World");
client.Close();
If you are using Angular (2+), (or any other framework), you could add some logic. The logic would be: only display an empty option if the user did not select any other yet. So after the user selected an option, the empty option disappears.
For Angular (9) this would look something like this:
<select>
<option *ngIf="(hasOptionSelected$ | async) === false"></option>
<option *ngFor="let option of (options$ | async)[value]="option.id">{{ option.title }}</option>
</select>
Other possible solution:
tv.setText(Integer.toString(a1)); // where a1 - int value
No, you still need to scp [from] [to]
whichever way you're copying
The difference is, you need to scp -p server:serverpath localpath
Though the question asks inserting efficiently to Oracle using JDBC, I'm currently playing with DB2 (On IBM mainframe), conceptually inserting would be similar so thought it might be helpful to see my metrics between
inserting one record at a time
inserting a batch of records (very efficient)
Here go the metrics
public void writeWithCompileQuery(int records) {
PreparedStatement statement;
try {
Connection connection = getDatabaseConnection();
connection.setAutoCommit(true);
String compiledQuery = "INSERT INTO TESTDB.EMPLOYEE(EMPNO, EMPNM, DEPT, RANK, USERNAME)" +
" VALUES" + "(?, ?, ?, ?, ?)";
statement = connection.prepareStatement(compiledQuery);
long start = System.currentTimeMillis();
for(int index = 1; index < records; index++) {
statement.setInt(1, index);
statement.setString(2, "emp number-"+index);
statement.setInt(3, index);
statement.setInt(4, index);
statement.setString(5, "username");
long startInternal = System.currentTimeMillis();
statement.executeUpdate();
System.out.println("each transaction time taken = " + (System.currentTimeMillis() - startInternal) + " ms");
}
long end = System.currentTimeMillis();
System.out.println("total time taken = " + (end - start) + " ms");
System.out.println("avg total time taken = " + (end - start)/ records + " ms");
statement.close();
connection.close();
} catch (SQLException ex) {
System.err.println("SQLException information");
while (ex != null) {
System.err.println("Error msg: " + ex.getMessage());
ex = ex.getNextException();
}
}
}
The metrics for 100 transactions :
each transaction time taken = 123 ms
each transaction time taken = 53 ms
each transaction time taken = 48 ms
each transaction time taken = 48 ms
each transaction time taken = 49 ms
each transaction time taken = 49 ms
...
..
.
each transaction time taken = 49 ms
each transaction time taken = 49 ms
total time taken = 4935 ms
avg total time taken = 49 ms
The first transaction is taking around 120-150ms
which is for the query parse and then execution, the subsequent transactions are only taking around 50ms
. (Which is still high, but my database is on a different server(I need to troubleshoot the network))
preparedStatement.executeBatch()
public int[] writeInABatchWithCompiledQuery(int records) {
PreparedStatement preparedStatement;
try {
Connection connection = getDatabaseConnection();
connection.setAutoCommit(true);
String compiledQuery = "INSERT INTO TESTDB.EMPLOYEE(EMPNO, EMPNM, DEPT, RANK, USERNAME)" +
" VALUES" + "(?, ?, ?, ?, ?)";
preparedStatement = connection.prepareStatement(compiledQuery);
for(int index = 1; index <= records; index++) {
preparedStatement.setInt(1, index);
preparedStatement.setString(2, "empo number-"+index);
preparedStatement.setInt(3, index+100);
preparedStatement.setInt(4, index+200);
preparedStatement.setString(5, "usernames");
preparedStatement.addBatch();
}
long start = System.currentTimeMillis();
int[] inserted = preparedStatement.executeBatch();
long end = System.currentTimeMillis();
System.out.println("total time taken to insert the batch = " + (end - start) + " ms");
System.out.println("total time taken = " + (end - start)/records + " s");
preparedStatement.close();
connection.close();
return inserted;
} catch (SQLException ex) {
System.err.println("SQLException information");
while (ex != null) {
System.err.println("Error msg: " + ex.getMessage());
ex = ex.getNextException();
}
throw new RuntimeException("Error");
}
}
The metrics for a batch of 100 transactions is
total time taken to insert the batch = 127 ms
and for 1000 transactions
total time taken to insert the batch = 341 ms
So, making 100 transactions in ~5000ms
(with one trxn at a time) is decreased to ~150ms
(with a batch of 100 records).
NOTE - Ignore my network which is super slow, but the metrics values would be relative.
If the line before your error contains COMMENT ''
either populate the comment in the script or remove the empty comment definition. I've found this in scripts generated by MySQL Workbench.
You can set using SelectedIndex
comboBox1.SelectedIndex= 1;
OR
SelectedItem
comboBox1.SelectedItem = "your value"; //
The latter won't throw an exception if the value is not available in the combobox
EDIT
If the value to be selected is not specific then you would be better off with this
comboBox1.SelectedIndex = comboBox1.Items.Count - 1;
To generalize the task of reading multiple header lines and to improve readability I'd use method extraction. Suppose you wanted to tokenize the first three lines of coordinates.txt
to use as header information.
Example
coordinates.txt
---------------
Name,Longitude,Latitude,Elevation, Comments
String, Decimal Deg., Decimal Deg., Meters, String
Euler's Town,7.58857,47.559537,0, "Blah"
Faneuil Hall,-71.054773,42.360217,0
Yellowstone National Park,-110.588455,44.427963,0
Then method extraction allows you to specify what you want to do with the header information (in this example we simply tokenize the header lines based on the comma and return it as a list but there's room to do much more).
def __readheader(filehandle, numberheaderlines=1):
"""Reads the specified number of lines and returns the comma-delimited
strings on each line as a list"""
for _ in range(numberheaderlines):
yield map(str.strip, filehandle.readline().strip().split(','))
with open('coordinates.txt', 'r') as rh:
# Single header line
#print next(__readheader(rh))
# Multiple header lines
for headerline in __readheader(rh, numberheaderlines=2):
print headerline # Or do other stuff with headerline tokens
Output
['Name', 'Longitude', 'Latitude', 'Elevation', 'Comments']
['String', 'Decimal Deg.', 'Decimal Deg.', 'Meters', 'String']
If coordinates.txt
contains another headerline, simply change numberheaderlines
. Best of all, it's clear what __readheader(rh, numberheaderlines=2)
is doing and we avoid the ambiguity of having to figure out or comment on why author of the the accepted answer uses next()
in his code.
I think other answers here are more comprehensive, but I thought I'd share a trick I usually use to differentiate tabs and spaces visually:
:syntax on
:set syntax=whitespace
These are syntax highlighting rules for the Whitespace programming language - tabs show in green and spaces in red. :)
Can be combined with :set list
as mentioned by many other answers, although the tabs will then show as ^I without a green higlight, but the spaces will show in red.
.NET Core 2.0+ provides the LINQ method TakeLast()
:
https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.takelast
example:
Enumerable
.Range(1, 10)
.TakeLast(3) // <--- takes last 3 items
.ToList()
.ForEach(i => System.Console.WriteLine(i))
// outputs:
// 8
// 9
// 10
FWIW: I had problems with all of these answers when dealing with a private organization repository.
The following worked for me:
npm install -S "git+https://[email protected]/orgname/repositoryname.git"
For example:
npm install -S "git+https://[email protected]/netflix/private-repository.git"
I'm not entirely sure why the other answers didn't work for me in this one case, because they're what I tried first before I hit Google and found this answer. And the other answers are what I've done in the past.
Hopefully this helps someone else.
defaultOrder contain a array where key is a column name and value is a SORT_DESC
or SORT_ASC
that's why below code not working.
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => ['defaultOrder'=>'topic_order asc']
]);
Correct Way
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'topic_order' => SORT_ASC,
]
],
]);
Note: If a query already specifies the orderBy clause, the new ordering instructions given by end users (through the sort configuration) will be appended to the existing orderBy clause. Any existing limit and offset clauses will be overwritten by the pagination request from end users (through the pagination configuration).
You can detail learn from Yii2 Guide of Data Provider
Sorting By passing Sort object in query
$sort = new Sort([
'attributes' => [
'age',
'name' => [
'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Name',
],
],
]);
$models = Article::find()
->where(['status' => 1])
->orderBy($sort->orders)
->all();
It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.
Pymongo 3.9+
update()
is now deprecated and you should use replace_one()
, update_one()
, or update_many()
instead.
In my case I used update_many()
and it solved my issue:
db.your_collection.update_many({}, {"$set": {"new_field": "value"}}, upsert=False, array_filters=None)
From documents
update_many(filter, update, upsert=False, array_filters=None, bypass_document_validation=False, collation=None, session=None) filter: A query that matches the documents to update. update: The modifications to apply. upsert (optional): If True, perform an insert if no documents match the filter. bypass_document_validation (optional): If True, allows the write to opt-out of document level validation. Default is False. collation (optional): An instance of Collation. This option is only supported on MongoDB 3.4 and above. array_filters (optional): A list of filters specifying which array elements an update should apply. Requires MongoDB 3.6+. session (optional): a ClientSession.
sed --expression='s/\r\n/\n/g'
Since the question mentions sed, this is the most straight forward way to use sed to achieve this. What the expression says is replace all carriage-return and line-feed with just line-feed only. That is what you need when you go from Windows to Unix. I verified it works.
As a follow-up to this question - since it relates specifically to creation time and discusses obtaining it via the new nio classes - it seems right now in JDK7's implementation you're out of luck. Addendum: same behaviour is in OpenJDK7.
On Unix filesystems you cannot retrieve the creation timestamp, you simply get a copy of the last modification time. So sad, but unfortunately true. I'm not sure why that is but the code specifically does that as the following will demonstrate.
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;
public class TestFA {
static void getAttributes(String pathStr) throws IOException {
Path p = Paths.get(pathStr);
BasicFileAttributes view
= Files.getFileAttributeView(p, BasicFileAttributeView.class)
.readAttributes();
System.out.println(view.creationTime()+" is the same as "+view.lastModifiedTime());
}
public static void main(String[] args) throws IOException {
for (String s : args) {
getAttributes(s);
}
}
}
The problem is you typed the wrong file extension for excel file. you used .xsl instead of xls.
I know i came in late but it can help future readers of this post.
Short solution:
const query = {}
const projection = {}
const options = { sort: { id: 1 }, limit: 2, skip: 10 }
Room.find(query, projection, options).exec(function(err, docs) { ... });
if you are using 3.6 try this
k = 250
print(f"User pressed the: {k}")
Output: User pressed the: 250
I was having same issue, way i have resolved is:
opened the MySQL installer. i was having a Reconfigure link on MYSQL Server row.
Clicked on it, it does reinstalled MySQL Server. after that opened MySQL Workbench, and it was working fine.
The issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file.
The easiest solution would be to close the file after you've read it in, then reopen it for writing.
with open("replayScript.json", "r") as jsonFile:
data = json.load(jsonFile)
data["location"] = "NewPath"
with open("replayScript.json", "w") as jsonFile:
json.dump(data, jsonFile)
Alternatively, you can use seek()
to move the cursor back to the beginning of the file then start writing, followed by a truncate()
to deal with the case where the new data is smaller than the previous.
with open("replayScript.json", "r+") as jsonFile:
data = json.load(jsonFile)
data["location"] = "NewPath"
jsonFile.seek(0) # rewind
json.dump(data, jsonFile)
jsonFile.truncate()
Either make ActiveAlarm
implement Comparable<ActiveAlarm>
or implement Comparator<ActiveAlarm>
in a separate class. Then call:
Collections.sort(list);
or
Collections.sort(list, comparator);
In general, it's a good idea to implement Comparable<T>
if there's a single "natural" sort order... otherwise (if you happen to want to sort in a particular order, but might equally easily want a different one) it's better to implement Comparator<T>
. This particular situation could go either way, to be honest... but I'd probably stick with the more flexible Comparator<T>
option.
EDIT: Sample implementation:
public class AlarmByTimesComparer implements Comparator<ActiveAlarm> {
@Override
public int compare(ActiveAlarm x, ActiveAlarm y) {
// TODO: Handle null x or y values
int startComparison = compare(x.timeStarted, y.timeStarted);
return startComparison != 0 ? startComparison
: compare(x.timeEnded, y.timeEnded);
}
// I don't know why this isn't in Long...
private static int compare(long a, long b) {
return a < b ? -1
: a > b ? 1
: 0;
}
}
you can use simple if condition like:
if(round(var) != var)
My solution is:
-vm
D:/work/Java/jdk1.6.0_13/bin/javaw.exe
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256M
-framework
plugins\org.eclipse.osgi_3.4.3.R34x_v20081215-1030.jar
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m
#include<iostream>
#include<ctime>
int main()
{
std::time_t t = std::time(0); // t is an integer type
std::cout << t << " seconds since 01-Jan-1970\n";
return 0;
}
Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.
Having added a new view controller scene to your storyboard, you then have to:
Create a UIViewController
subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":
And then select a unique name for the new view controller subclass:
Specify this new subclass as the base class for the scene you just added to the storyboard.
Now hook up any IBOutlet
and IBAction
references for this new scene with the new view controller subclass.
In simple terms
It is better to have more coarse-grained service operations, which are composed by fine-grained operations
In my own words, after reading the docs and experimenting:
You can use RewriteBase
to provide a base for your rewrites. Consider this
# invoke rewrite engine
RewriteEngine On
RewriteBase /~new/
# add trailing slash if missing
rewriteRule ^(([a-z0-9\-]+/)*[a-z0-9\-]+)$ $1/ [NC,R=301,L]
This is a real rule I used to ensure that URLs have a trailing slash. This will convert
http://www.example.com/~new/page
to
http://www.example.com/~new/page/
By having the RewriteBase
there, you make the relative path come off the RewriteBase
parameter.
Now Update word-wrap is replace by :
overflow-wrap:break-word;
Compatible old navigator and css 3 it's good alternative !
it's evolution of word-wrap ( since 2012... )
See more information : https://www.w3.org/TR/css-text-3/#overflow-wrap
See compatibility full : http://caniuse.com/#search=overflow-wrap
Contents of table cell, variable height, could be more than 60px;
<div style="position: absolute; bottom: 0px;">
Notice
</div>
Borrowing from Samrat Mazumdar's answer, here's a short method that estimates the device screen size. It works with the latest devices, but may fail on future ones (as all methods of guessing might). It will also get confused if the device is being mirrored (returns the device's screen size, not the mirrored screen size)
#define SCREEN_SIZE_IPHONE_CLASSIC 3.5
#define SCREEN_SIZE_IPHONE_TALL 4.0
#define SCREEN_SIZE_IPAD_CLASSIC 9.7
+ (CGFloat)screenPhysicalSize
{
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
CGSize result = [[UIScreen mainScreen] bounds].size;
if (result.height < 500)
return SCREEN_SIZE_IPHONE_CLASSIC; // iPhone 4S / 4th Gen iPod Touch or earlier
else
return SCREEN_SIZE_IPHONE_TALL; // iPhone 5
}
else
{
return SCREEN_SIZE_IPAD_CLASSIC; // iPad
}
}
You could try to sort descending "sort LastWriteTime -Descending" and then "select -first 1." Not sure which one is faster
Google's official answer is the Android Cloud to Device Messaging Framework (deprecated) Google Cloud Messaging(deprecated) Firebase Cloud Messaging
It will work on Android >= 2.2 (on phones that have the Play Store).
Some modern browsers (Firefox, Safari, and Opera, but not Chrome) support the special "back/forward" cache (I'll call it bfcache, which is a term invented by Mozilla), involved when the user navigates Back. Unlike the regular (HTTP) cache, it captures the complete state of the page (including the state of JS, DOM). This allows it to re-load the page quicker and exactly as the user left it.
The load
event is not supposed to fire when the page is loaded from this bfcache. For example, if you created your UI in the "load" handler, and the "load" event was fired once on the initial load, and the second time when the page was re-loaded from the bfcache, the page would end up with duplicate UI elements.
This is also why adding the "unload" handler stops the page from being stored in the bfcache (thus making it slower to navigate back to) -- the unload handler could perform clean-up tasks, which could leave the page in unworkable state.
For pages that need to know when they're being navigated away/back to, Firefox 1.5+ and the version of Safari with the fix for bug 28758 support special events called "pageshow" and "pagehide".
References:
Perhaps the question is getting old, but I hope my code will help someone.
def powSet(set):
if len(set) == 0:
return [[]]
return addtoAll(set[0],powSet(set[1:])) + powSet(set[1:])
def addtoAll(e, set):
for c in set:
c.append(e)
return set
The accepted answer throws a ProtocolException at:
OutputStream os = conn.getOutputStream();
because it does not enable the output for the URLConnection object. The solution should include this:
conn.setDoOutput(true);
to make it work.
If the time involved in implementing a directory partitioning scheme is minimal, I am in favor of it. The first time you have to debug a problem that involves manipulating a 10000-file directory via the console you will understand.
As an example, F-Spot stores photo files as YYYY\MM\DD\filename.ext, which means the largest directory I have had to deal with while manually manipulating my ~20000-photo collection is about 800 files. This also makes the files more easily browsable from a third party application. Never assume that your software is the only thing that will be accessing your software's files.
I would think that one reason could be that the color is applied to things other than font. For example:
div {
border: 1px solid;
color: red;
}
Yields both a red font color and a red border.
Alternatively, it could just be that the W3C's CSS standards are completely backwards and nonsensical as evidenced elsewhere.
put base64()
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0CAIAAABEtEjdAAAACXBIWXMAAA7zAAAO8wEcU5k6AAAAEXRFWHRUaXRsZQBQREYgQ3JlYXRvckFevCgAAAATdEVYdEF1dGhvcgBQREYgVG9vbHMgQUcbz3cwAAAALXpUWHREZXNjcmlwdGlvbgAACJnLKCkpsNLXLy8v1ytISdMtyc/PKdZLzs8FAG6fCPGXryy4AAPW0ElEQVR42uy9Z5djV3Yl+ByAB+9deG8yMzLSMA1tkeWk6pJKKmla06MlafRB3/UX9BP0eTSj1RpperpLKpXKscgii0xDZpLpIyMiM7yPQCCAgLfPzr73AUikYVVR00sqUvcwVxABIICHB2Dfc/fZZx/eNE2OBQsWLFh8uUJgp4AFCxYsGLizYMGCBQsG7ixYsGDBgoE7CxYsWLBg4M6CBQsWLBi4s2DBggUDdxYsWLBgwcCdBQsWLFgwcGfBggULFgzcWbBgwYIFA3cWLFiwYODOggULFiwYuLNgwYIFCwbuLFiwYMGCgTsLFixYsGDgzoIFCxYsGLizYMGCBQN3FixYsGDBwJ0FCxYsWDBwZ8GCBQsWDNxZsGDBggUDdxYsWLBg4M6CBQsWLBi4s2DBggULBu4sWLBgwYKBOwsWLFiwYODOggULFiwYuLNgwYIFA3cWLFiwYMHAnQULFixYMHBnwYIFCxYM3FmwYMGCBQN3FixYsGDgzoIFCxYsGLizYMGCBQsG7ixYsGDBgoE7CxYsWLBg4M6CBQsWLBi4s2DBggUDdxYsWLBgwcCdBQsWLFgwcGfBggULFgzcWbBgwYIFA3cWLFiwYODOggULFiwYuLNgwYIFCwbuLFiwYMHi3zokdgpY/FuG/oLrjK4Uw+hc4lv315/LRfjnHsHsuoftcx0P/8Jrzc+4jOMRtBclRoLJvmAsGLizYPE0NAodTOe7LrdvE1/0R93Aavz/O5AXgTXf/tV8Fv6F5za7xnOLhMneXRa/AcGbJvsosvi3C/MzE2fjV68CvxI4+c8NrDynfs7MXnj+qF74pNbrEdlbzoKBOwuG9//KO3Tf9wlt8q9/ev7FsG7dXfocCwELFv9+wWgZFr95gG4+jZj85/rzz5us2D7XQ/DmZyO7yRCfBQN3Fv/Rd4yfAaKfdQ3/6yIm/znR1DQ/J/6an3EMJoNyFgzcWfyHTtnBRQv8Z+Hj8+DIW9y18auy6s5ffj51L99+SJP/9f/g107PGdazYODO4j9IGJ8NwDz/QgB/BtZ/Vd3V/JytG60nNZ7DYcN88YbC9vnwnQULBu4svmxJOo02cJPABc0E+hpmG8itO9DbeKF1TRfKc1YB06R/a3Ql2fxnpu0muaNp0IdrPSJn6hwv0T82n1tY+ObzGwfT1Dh6SO3lxTBNXSCPiOsIR28YTxYkXngW/s2uI2SYz+LfK5hahsW/aaifAXyarlkoL/K8wAtdH9DOUkF/FZ5K5+nyYX2GBfqAPK9a8NuGa6NLjai3wd1aKSwwtzW7l6MWYwTwFgR6hcF3HYxu6KLgemoBo/c1DIMcBw5eFAD3RmdN0XWHyPInFgzcWXyJQtM0viusjxl+6vyz2b1FqYiC+BRqI/nWdICmYMitnFzkhDZMA0sFke/gq6FTWBYI9Bs1DZCq0sAFC3ZxL6fTics4EjsNwDBnpfbNJidJFMrN9qPwLemLQZcOod23pJt4UdhIWFsQ63UJ1hrQtToYZFtC7mKR+IJpbTtYsGDgzuLLzdV05eFt1DO6eByd0iFdaKhKTzJ85Mi6oWpNTVNqtRruCbxuNtV6va40gekEu7VmQVGUZrOJx5IkyWazWc8CQG/SsK7Hrw6HAz9lIYBfRZvNulKWXaJNslYjySZw9vZBd/gc24s6Wk1B1VQAvSiypiUWDNxZ/IfC9A75bj5dNgXxoaumbogSxXTKihiqWqtVqtWq0mgUsgqSY4A+MB0ZuSCaokiwF6htAbTN5hAESeAlkYTk9ds5kpULLXaFPKbwJK+2lg1VVer1RqNBMvGGBz8B+vhVaaqaoSsktIaiOJ1up9tlkxx4XDwdLjudLldAtX7lke/zrWchFD9+7TgW6ISQAdbz0vNuBa1ShCAwzz4WDNxZ/Cah87MfoM/gHICYHe6iU00loVjceYd413FXQ1MqFaB5pVjIAdMB4gBuECn46fc4ZVkGhguiwYuWLZjB6SqBbItCMSnJTdQuFqPS3gdYdwC+k8fXBAvxAcG4gNeCw8NPkmi7WsuATqFfJLQLeUDcQTcB99VGvVrBPqGGBUCjqwHAnaT4suxBuH0ul1uw2w1VF/Dgkv3pHQpniuYzZ4mBOwsG7iy+wOBuPsc14xqwKKIuck2lRqC8ivQc/0jKrDZ8Pq/ssAEtfT6PwyUTFKYENieVwMdzkK80arrWaDarpXKhXC4eHBzoNEh2ziGVBsciI6HeP8yTB1QUJPVerxc/cRm8DdYJi64BFw909vl8yWQyEom47IROwaHq0PHwYG9ku0MGQyN7vXhUAtat9NzaByDr9+qNRqVSK5VK1Uodj6kjTzc5t9uL1cjr9fu8AZvLxVklAZPTRf3Z5e1FJ4cFCwbuLL4Y4N4J4C8gtU4DwFo/KIAxB8oDiP1+bzDkd/v9nN1GZTEGzcrh8quYzUaz3sD9d3ZvVCqlo6PD9FGqXC40mkDVQrFY4AWTgHWDVE3B0ABbkUQDynNVrkHDegpgukh5nHK5jF9xB0A58m/c2mJ1uENcQMJOrtQB5lhgfE7Z5fJ4w+FoNB4PBsOy0+V2u32+AH4K2jDJ90kNlspgNINTDVRac4VCuVQtFEpYPvCwfl/Q7/cju5ciLqEd7FPEgoE7i/+JqPzMG/55705YDqAX5Ilgx7mOGBEQTFkRvXU3qGDafUDIY1WTkxxcVatmq8fpUiFX0RqmW/YhsXX0V/0Br+TzcrxGOBlIF034MjY5Qctm9ra213Z21/cPd/P541qd8DPp7Gy9jnRbtwF3bU7Cm0gOu01G7gs0pul/DWAai8Wi0ShyZ87lQE5dLBZJkq5rQHbsBpBPA7sJiAuCpZ/Bz0qtCsRPF/cB2X5PSLa7eY1XGyrodggzRVMz1JqhVjijbhc1l8wHgq6A39c/RfYHHo8rEvZHo5FQwIdUnxPAFoGQcXCmzCmiWlRyx9VsJl8p1W3KqM/njiSCgbjEeaEKwvmsc4KC1B7HYZgSLzhxslRaHSCEUFuNyeMguCrPNSRk/4R7ElpPYbjJmTbaak77c+9s91vMd/d8WZeZNJOBO4svHbb/OkSARpnnTj8RmBGelAsNodNGBOk3pOOE7DaRkDtcpmroPAqikpszbWpVKx6Xq8Xa7va2XQKG28MhfyTs5X1ODuwzcNxxTPDF1Bvl6nE2nzrMHBwcHudKa2vrtYZWKVNyW4GMUgRSkww6OkAB2hcKRTxuv8PhlMHayG5JtBMuhagedaA2yByXy0XEKrLNKpAiWum5ywk4xj0hg+FoMYBKHE3sJPBkxUbDCSJGlrF0cLqmKyoKAKi4FnM5pVFp1spKs9qs15RGVcf1nHFU2IOuBkJMCHZUtely2qPRMDB+aGAw4Pci1Y8EQzanh6xtJASuqteL5XT6KHtcrDcNtyeQ6OmPxhKSbOPtdFXE2SXgDVTXsVuxO3wWEPOk19akHbcG7Yoi7BM1NZZasG7p9H+5PId/vqGXbSAYuLP4MibubeD4zC+8otEqI9+6lsIK/un0oUzak88T8Tcwx5Kdm3WAk6ma+Ux5Zzt1nC3JdmcgEBgfG7I7kWjqnIg7VMk/rgYdTKNR290/WFx4tLK8dZTO1xqm2hQ0FTR1xO0Mef0xlxwkjUK8zSl7oFcJDtWAz6BcgO9QxWChgVYFEI9dBCAbXAc+wLTCicsASgMcic1GDgyKF/x0OCRcj7xYsgqlBq2k0moraqNkATBlgb4UkkljaTOanIGfioryKRYZRcMrRYMrdg/1ah2bgVpToYuKWq/WiqV8sXBcrRY1BeR72Wbn3E7B55MjUd/gQHJkdDAej9qdJU4A0Hs5062V+KOjRi7brNVMrycYCAX9AbckQ3OpC7JJGrzI5BAvPfuC1W2L12uarQau1vtC8Bo7I4W+KbgcetHb3oXpz/gxMKqfgTuLLwu4Gy/+zj8B8KdCb19jWjDCQzwOeCD31SkrDR7burlZM4vFci2rZrPpfCHj9shDw8megSiYA86sgX8w1apuKEhzkeFu7+0uLi5ub29njyhX3gSQ8Xabyy67RcEJTUkgGA8Foz29Q6FgTBQdOrhsUYIM0RU6hqKQ4rhInl8jOhOUPSnYSRSvDdoaCuQzqACR3Bm/GUarJwk/UXaVHALdbLTkkVa9FtySRAU1LR8Z8P68Dg6KpwQUcnxdAwsFkaYNrak4ZkVRRZvYANAjCdegdzQb1drx8XGxkMXCoCrlSu0YBYJKLavrVZvdxH4gGFJARvX1Do6NTfX3jUj2AKcJWtMs5atH6eNcroADDvmDIRqCx8MpKsn6hbaqsu2JYPV64WhMQmc1DbISqHRCYejp9/RpA7XnnXYYuDNwZ/FlAffPHF7xwvzdmlkKAQhvWEJG0VIZilyrb1NXuEIeIpd6Hrz4cb7XNdI/EHYmLX6gyIkFTqwBfY4LqWwunz4qZdKV3d38/n5BU5CMe2VuiBQ2nQ7Q1h6vCz/dXpfsROVTsDsdbg9ELxIMBdCrRPNxCX2qlsEArdyCjhZstOHIklqS9QpaFXJrqwPWaXe2nQBE0hOl63QZIDVVof2KO+VN0gFLlgHDuhvfupIk8A67jOvB4ND2VyxxWNsMwteLNfIrTg9ZArBlQSmCnCKw/LpKKseNRimfz2SyB4X8cb1eVUzQULrTKURjgcH+2OBgvDcZDQZ8AuFtZMKhF7W9neP0QZ7nZK/L3z86jBICLztaPvMdfLfRAoipmeSNMemaDUYHzy0KTy3SAj1LfOsyA3cG7iy+rKF3jZ"></img>
_x000D_
in Javascript
var id=document.getElementById("image");
id.src=base64Url;
Minimal runnable example
glOrtho
: 2D games, objects close and far appear the same size:
glFrustrum
: more real-life like 3D, identical objects further away appear smaller:
main.c
#include <stdlib.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
static int ortho = 0;
static void display(void) {
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
if (ortho) {
} else {
/* This only rotates and translates the world around to look like the camera moved. */
gluLookAt(0.0, 0.0, -3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}
glColor3f(1.0f, 1.0f, 1.0f);
glutWireCube(2);
glFlush();
}
static void reshape(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (ortho) {
glOrtho(-2.0, 2.0, -2.0, 2.0, -1.5, 1.5);
} else {
glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
}
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
if (argc > 1) {
ortho = 1;
}
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow(argv[0]);
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return EXIT_SUCCESS;
}
Compile:
gcc -ggdb3 -O0 -o main -std=c99 -Wall -Wextra -pedantic main.c -lGL -lGLU -lglut
Run with glOrtho
:
./main 1
Run with glFrustrum
:
./main
Tested on Ubuntu 18.10.
Schema
Ortho: camera is a plane, visible volume a rectangle:
Frustrum: camera is a point,visible volume a slice of a pyramid:
Parameters
We are always looking from +z to -z with +y upwards:
glOrtho(left, right, bottom, top, near, far)
left
: minimum x
we seeright
: maximum x
we seebottom
: minimum y
we seetop
: maximum y
we see-near
: minimum z
we see. Yes, this is -1
times near
. So a negative input means positive z
.-far
: maximum z
we see. Also negative.Schema:
How it works under the hood
In the end, OpenGL always "uses":
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
If we use neither glOrtho
nor glFrustrum
, that is what we get.
glOrtho
and glFrustrum
are just linear transformations (AKA matrix multiplication) such that:
glOrtho
: takes a given 3D rectangle into the default cubeglFrustrum
: takes a given pyramid section into the default cubeThis transformation is then applied to all vertexes. This is what I mean in 2D:
The final step after transformation is simple:
x
, y
and z
are in [-1, +1]
z
component and take only x
and y
, which now can be put into a 2D screenWith glOrtho
, z
is ignored, so you might as well always use 0
.
One reason you might want to use z != 0
is to make sprites hide the background with the depth buffer.
Deprecation
glOrtho
is deprecated as of OpenGL 4.5: the compatibility profile 12.1. "FIXED-FUNCTION VERTEX TRANSFORMATIONS" is in red.
So don't use it for production. In any case, understanding it is a good way to get some OpenGL insight.
Modern OpenGL 4 programs calculate the transformation matrix (which is small) on the CPU, and then give the matrix and all points to be transformed to OpenGL, which can do the thousands of matrix multiplications for different points really fast in parallel.
Manually written vertex shaders then do the multiplication explicitly, usually with the convenient vector data types of the OpenGL Shading Language.
Since you write the shader explicitly, this allows you to tweak the algorithm to your needs. Such flexibility is a major feature of more modern GPUs, which unlike the old ones that did a fixed algorithm with some input parameters, can now do arbitrary computations. See also: https://stackoverflow.com/a/36211337/895245
With an explicit GLfloat transform[]
it would look something like this:
glfw_transform.c
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
static const GLuint WIDTH = 800;
static const GLuint HEIGHT = 600;
/* ourColor is passed on to the fragment shader. */
static const GLchar* vertex_shader_source =
"#version 330 core\n"
"layout (location = 0) in vec3 position;\n"
"layout (location = 1) in vec3 color;\n"
"out vec3 ourColor;\n"
"uniform mat4 transform;\n"
"void main() {\n"
" gl_Position = transform * vec4(position, 1.0f);\n"
" ourColor = color;\n"
"}\n";
static const GLchar* fragment_shader_source =
"#version 330 core\n"
"in vec3 ourColor;\n"
"out vec4 color;\n"
"void main() {\n"
" color = vec4(ourColor, 1.0f);\n"
"}\n";
static GLfloat vertices[] = {
/* Positions Colors */
0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f
};
/* Build and compile shader program, return its ID. */
GLuint common_get_shader_program(
const char *vertex_shader_source,
const char *fragment_shader_source
) {
GLchar *log = NULL;
GLint log_length, success;
GLuint fragment_shader, program, vertex_shader;
/* Vertex shader */
vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL);
glCompileShader(vertex_shader);
glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &log_length);
log = malloc(log_length);
if (log_length > 0) {
glGetShaderInfoLog(vertex_shader, log_length, NULL, log);
printf("vertex shader log:\n\n%s\n", log);
}
if (!success) {
printf("vertex shader compile error\n");
exit(EXIT_FAILURE);
}
/* Fragment shader */
fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL);
glCompileShader(fragment_shader);
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &log_length);
if (log_length > 0) {
log = realloc(log, log_length);
glGetShaderInfoLog(fragment_shader, log_length, NULL, log);
printf("fragment shader log:\n\n%s\n", log);
}
if (!success) {
printf("fragment shader compile error\n");
exit(EXIT_FAILURE);
}
/* Link shaders */
program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &success);
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
if (log_length > 0) {
log = realloc(log, log_length);
glGetProgramInfoLog(program, log_length, NULL, log);
printf("shader link log:\n\n%s\n", log);
}
if (!success) {
printf("shader link error");
exit(EXIT_FAILURE);
}
/* Cleanup. */
free(log);
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
return program;
}
int main(void) {
GLint shader_program;
GLint transform_location;
GLuint vbo;
GLuint vao;
GLFWwindow* window;
double time;
glfwInit();
window = glfwCreateWindow(WIDTH, HEIGHT, __FILE__, NULL, NULL);
glfwMakeContextCurrent(window);
glewExperimental = GL_TRUE;
glewInit();
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glViewport(0, 0, WIDTH, HEIGHT);
shader_program = common_get_shader_program(vertex_shader_source, fragment_shader_source);
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
/* Position attribute */
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
/* Color attribute */
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glBindVertexArray(0);
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shader_program);
transform_location = glGetUniformLocation(shader_program, "transform");
/* THIS is just a dummy transform. */
GLfloat transform[] = {
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f,
};
time = glfwGetTime();
transform[0] = 2.0f * sin(time);
transform[5] = 2.0f * cos(time);
glUniformMatrix4fv(transform_location, 1, GL_FALSE, transform);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(0);
glfwSwapBuffers(window);
}
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
glfwTerminate();
return EXIT_SUCCESS;
}
Compile and run:
gcc -ggdb3 -O0 -o glfw_transform.out -std=c99 -Wall -Wextra -pedantic glfw_transform.c -lGL -lGLU -lglut -lGLEW -lglfw -lm
./glfw_transform.out
Output:
The matrix for glOrtho
is really simple, composed only of scaling and translation:
scalex, 0, 0, translatex,
0, scaley, 0, translatey,
0, 0, scalez, translatez,
0, 0, 0, 1
as mentioned in the OpenGL 2 docs.
The glFrustum
matrix is not too hard to calculate by hand either, but starts getting annoying. Note how frustum cannot be made up with only scaling and translations like glOrtho
, more info at: https://gamedev.stackexchange.com/a/118848/25171
The GLM OpenGL C++ math library is a popular choice for calculating such matrices. http://glm.g-truc.net/0.9.2/api/a00245.html documents both an ortho
and frustum
operations.
I would use this syntax
Delete a
from TableA a
Inner Join TableB b
on a.BId = b.BId
WHERE [filter condition]
Use this code :
<input type="button" onclick="demoShow()" value="edit" />
<script type="text/javascript">
function demoShow()
{document.getElementById("p2").style.visibility="hidden";}
</script>
<input id="p2" type="submit" value="submit" name="submit" />
Possibly browser returns String representation of some integer value? Actually int can't be null. May be you could check for null, if value is not null, then transform String representation to int.
[ ]{2,}
SPACE (2 or more)
You could also check that before and after those spaces words follow. (not other whitespace like tabs or new lines)
\w[ ]{2,}\w
the same, but you can also pick (capture) only the spaces for tasks like replacement
\w([ ]{2,})\w
or see that before and after spaces there is anything, not only word characters (except whitespace)
[^\s]([ ]{2,})[^\s]
With push you can even add multiple objects to an array
let myArray = [];
myArray.push(
{name:"James", dataType:TYPES.VarChar, Value: body.Name},
{name:"Boo", dataType:TYPES.VarChar, Value: body.Name},
{name:"Alina", dataType:TYPES.VarChar, Value: body.Name}
);
Add the goal like -
<build>
<defaultGoal>install</defaultGoal>
<!-- Source directory configuration -->
<sourceDirectory>src</sourceDirectory>
</build>
This will solve the issue
As it turns out, the recent WebRTC extension of HTML5 allows javascript to query the local client IP address. A proof of concept is available here: http://net.ipcalf.com
This feature is apparently by design, and is not a bug. However, given its controversial nature, I would be cautious about relying on this behaviour. Nevertheless, I think it perfectly and appropriately addresses your intended purpose (revealing to the user what their browser is leaking).
The line
when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
would do the same as
when(someObject.doSomething(Matchers.any())).thenReturn(true);
So, using argumentCaptor.capture() when stubbing has no added value. Using Matchers.any() shows better what really happens and therefor is better for readability. With argumentCaptor.capture(), you can't read what arguments are really matched. And instead of using any(), you can use more specific matchers when you have more information (class of the expected argument), to improve your test.
And another problem: If using argumentCaptor.capture() when stubbing it becomes unclear how many values you should expect to be captured after verification. We want to capture a value during verification, not during stubbing because at that point there is no value to capture yet. So what does the argument captors capture method capture during stubbing? It capture anything because there is nothing to be captured yet. I consider it to be undefined behavior and I don't want to use undefined behavior.
Any browser that does not support the input type date
will default to the standard type, which is text
, so all you have to do is check the type property (not the attribute), if it's not date
, the date input is not supported by the browser, and you add your own datepicker:
if ( $('[type="date"]').prop('type') != 'date' ) {
$('[type="date"]').datepicker();
}
You can of course use any datepicker you want, jQuery UI's datepicker is probably the one most commonly used, but it does add quite a bit of javascript if you're not using the UI library for anything else, but there are hundreds of alternative datepickers to choose from.
The type
attribute never changes, the browser will only fall back to the default text
type for the property, so one has to check the property.
The attribute can still be used as a selector, as in the example above.
comp:~$ python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2
>>> import timeit
>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)
5.656799077987671
>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)
5.579368829727173
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)
21.54827117919922
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)
22.014557123184204
With timeit number=1 param:
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)
0.2245171070098877
>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=1)
0.10750913619995117
comp:~$ python3 Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)
9.113872020003328
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)
9.07014398300089
With timeit number=1,2,3,4 param works quick and in linear way:
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)
0.09329321900440846
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=2)
0.18501482300052885
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=3)
0.2703447980020428
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=4)
0.36209142999723554
So it seems if we measure 1 running loop cycle like timeit.timeit("[x for x in range(1000000) if x%4]",number=1) (as we actually use in real code) python3 works quick enough, but in repeated loops python 2 xrange() wins in speed against range() from python 3.
Use Java 8's never-too-late-to-join-in-the-fun class: java.util.Base64
new String(Base64.getEncoder().encode(bytes));
Every SQL statement executed by the Oracle database has a cursor associated with it, which is a private work area to store processing information. Implicit cursors are implicitly created by the Oracle server for all DML and SELECT statements.
You can declare and use Explicit cursors to name the private work area, and access its stored information in your program block.
Linux: You can use this command if you know the port :
netstat -plten | grep LISTEN | grep 8080
AIX:
netstat -Aan | grep LISTEN | grep 8080
You then take the first column (example: f100050000b05bb8) and run the following command:
rmsock f100050000b05bb8 tcpcb
kill process.
To bind a control to your state you need to call a function on the component that updates the state from the control's event handler.
Rather than have an update function for all your form fields, you could create a generic update function using ES6 computed name feature and pass it the values it needs inline from the control like this:
class LovelyForm extends React.Component {_x000D_
constructor(props) {_x000D_
alert("Construct");_x000D_
super(props);_x000D_
this.state = {_x000D_
field1: "Default 1",_x000D_
field2: "Default 2"_x000D_
};_x000D_
}_x000D_
_x000D_
update = (name, e) => {_x000D_
this.setState({ [name]: e.target.value });_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<form>_x000D_
<p><input type="text" value={this.state.field1} onChange={(e) => this.update("field1", e)} />_x000D_
{this.state.field1}</p>_x000D_
<p><input type="text" value={this.state.field2} onChange={(e) => this.update("field2", e)} />_x000D_
{this.state.field2}</p>_x000D_
</form>_x000D_
);_x000D_
}_x000D_
}_x000D_
ReactDOM.render(<LovelyForm/>, document.getElementById('example'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="example"></div>
_x000D_
I think it works the other way
<#if object.attribute??>
Do whatever you want....
</#if>
If object.attribute
is NOT NULL, then the content will be printed.
Same issue on my Mac with a pre-packaged RCP client that was unzip only. The other answers pointed me to the eclipse.ini where all the paths looked valid, tried to check the working directory of my Eclipse bundle that doesn't see that easy to do. Seems when Finder starts an application it's working directory is / so that seems to be the issue.
Updated both references in my eclipse.ini to absolute paths and voila!
-startup
/Applications/RCPClient/client/eclipse/plugins/org.eclipse.equinox.launcher_1.1.1.R36x_v20101122_1400.jar
--launcher.library
/Applications/RCPClient/eclipse/plugins/org.eclipse.equinox.launcher.cocoa.macosx.x86_64_1.1.2.R36x_v20101019_1345
...
what about that simple way)
$(document).ready ->
$('#datepicker').datepicker( dateFormat: 'yy-mm-dd', onSelect: (dateStr) ->
alert dateStr # yy-mm-dd
#OR
alert $("#datepicker").val(); # yy-mm-dd
you have to name your checkboxes accordingly:
<input type="checkbox" name="check_list[]" value="…" />
you can then access all checked checkboxes with
// loop over checked checkboxes
foreach($_POST['check_list'] as $checkbox) {
// do something
}
ps. make sure to properly escape your output (htmlspecialchars()
)
Just to include one more alternative, you could also use this:
find "/starting/path" -type f -regextype posix-extended -regex "^.*\.(php|html|js)$" -exec grep -EH '(document\.cookie|setcookie)' {} \;
Where:
-regextype posix-extended
tells find
what kind of regex to expect-regex "^.*\.(php|html|js)$"
tells find
the regex itself filenames must match-exec grep -EH '(document\.cookie|setcookie)' {} \;
tells find
to run the command (with its options and arguments) specified between the -exec
option and the \;
for each file it finds, where {}
represents where the file path goes in this command.
while
E
option tells grep
to use extended regex (to support the parentheses) and...H
option tells grep
to print file paths before the matches.And, given this, if you only want file paths, you may use:
find "/starting/path" -type f -regextype posix-extended -regex "^.*\.(php|html|js)$" -exec grep -EH '(document\.cookie|setcookie)' {} \; | sed -r 's/(^.*):.*$/\1/' | sort -u
Where
|
[pipe] send the output of find
to the next command after this (which is sed
, then sort
) r
option tells sed
to use extended regex.s/HI/BYE/
tells sed
to replace every First occurrence (per line) of "HI" with "BYE" and...s/(^.*):.*$/\1/
tells it to replace the regex (^.*):.*$
(meaning a group [stuff enclosed by ()
] including everything [.*
= one or more of any-character] from the beginning of the line [^
] till' the first ':' followed by anything till' the end of line [$
]) by the first group [\1
] of the replaced regex.u
tells sort to remove duplicate entries (take sort -u
as optional)....FAR from being the most elegant way. As I said, my intention is to increase the range of possibilities (and also to give more complete explanations on some tools you could use).
a possible solution could be
create a batch file
there do a loop on lib directory for all files inside it and set each file unside lib on classpath
then after that run the jar
source for loop in batch file for info on loops
Your data is problematic in that you have inner wrapper objects in your array. Presumably your Vendor
object is designed to handle id
, name
, company_id
, but each of those multiple objects are also wrapped in an object with a single property vendor
.
I'm assuming that you're using the Jackson Data Binding model.
If so then there are two things to consider:
The first is using a special Jackson config property. Jackson - since 1.9 I believe, this may not be available if you're using an old version of Jackson - provides UNWRAP_ROOT_VALUE
. It's designed for cases where your results are wrapped in a top-level single-property object that you want to discard.
So, play around with:
objectMapper.configure(SerializationConfig.Feature.UNWRAP_ROOT_VALUE, true);
The second is using wrapper objects. Even after discarding the outer wrapper object you still have the problem of your Vendor
objects being wrapped in a single-property object. Use a wrapper to get around this:
class VendorWrapper
{
Vendor vendor;
// gettors, settors for vendor if you need them
}
Similarly, instead of using UNWRAP_ROOT_VALUES
, you could also define a wrapper class to handle the outer object. Assuming that you have correct Vendor
, VendorWrapper
object, you can define:
class VendorsWrapper
{
List<VendorWrapper> vendors = new ArrayList<VendorWrapper>();
// gettors, settors for vendors if you need them
}
// in your deserialization code:
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readValue(jsonInput, VendorsWrapper.class);
The object tree for VendorsWrapper is analogous to your JSON:
VendorsWrapper:
vendors:
[
VendorWrapper
vendor: Vendor,
VendorWrapper:
vendor: Vendor,
...
]
Finally, you might use the Jackson Tree Model to parse this into JsonNodes
, discarding the outer node, and for each JsonNode
in the ArrayNode
, calling:
mapper.readValue(node.get("vendor").getTextValue(), Vendor.class);
That might result in less code, but it seems no less clumsy than using two wrappers.
<input name="submitBnt" type="submit" value="like"/>
name is useful when using $_POST
in php and also in javascript as document.getElementByName('submitBnt')
.
Also you can use name as a CS selector like input[name="submitBnt"]
;
Hope this helps
Nullable type can invoke runtime error.
So I think it's good to use a compiler option --strictNullChecks
and declare number | null
as type. also in case of nested function, although input type is null, compiler can not know what it could break, so I recommend use !
(exclamination mark).
function broken(name: string | null): string {
function postfix(epithet: string) {
return name.charAt(0) + '. the ' + epithet; // error, 'name' is possibly null
}
name = name || "Bob";
return postfix("great");
}
function fixed(name: string | null): string {
function postfix(epithet: string) {
return name!.charAt(0) + '. the ' + epithet; // ok
}
name = name || "Bob";
return postfix("great");
}
Reference. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-type-assertions
get
returns Collection
and is rather supposed to fetch multiple rows.
count
is a generic way of checking the result:
$user = User::where(...)->first(); // returns Model or null
if (count($user)) // do what you want with $user
// or use this:
$user = User::where(...)->firstOrFail(); // returns Model or throws ModelNotFoundException
// count will works with a collection of course:
$users = User::where(...)->get(); // returns Collection always (might be empty)
if (count($users)) // do what you want with $users
Try this:
CSS
.style1{
background-color:red;
color:white;
font-size:44px;
}
HTML
<div id="foo">hello world!</div>
<img src="zoom.png" onclick="myFunction()" />
Javascript
function myFunction()
{
document.getElementById('foo').setAttribute("class", "style1");
}
You just need to return
from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.
/* .... */
if (Date1 == Date2)
fprintf (stderr , "Indicating that the first date is equal to second date.\n");
return 0;
}
As Josh has stated above, you want to give each one the same name (letter, button, etc.) and all of them work. Then you want to surround all of these with a form tag:
<form name="myLetters" action="yourScript.php" method="POST">
<!-- Enter your values here with the following syntax: -->
<input type="radio" name="letter" value="A" /> A
<!-- Then add a submit value & close your form -->
<input type="submit" name="submit" value="Choose Letter!" />
</form>
Then, in the PHP script "yourScript.php" as defined by the action attribute, you can use:
$_POST['letter']
To get the value chosen.
You can download individual ones from their site like @mayerdesign has stated or you can click on the download link on the left and you can download the whole pack.
To use unsafe code blocks, the project has to be compiled with the /unsafe switch on.
Open the properties for the project, go to the Build
tab and check the Allow unsafe code
checkbox.
In order to call this you will have to store a reference to your form and pass the reference to the run method. Then you can call this in an actionhandler.
public partial class Form1 : Form
{
public void ChangeSize(int width, int height)
{
this.Size = new Size(width, height);
}
}
Here in 2017, Promises are built into JavaScript, they were added by the ES2015 spec (polyfills are available for outdated environments like IE8-IE11). The syntax they went with uses a callback you pass into the Promise
constructor (the Promise
executor) which receives the functions for resolving/rejecting the promise as arguments.
First, since async
now has a meaning in JavaScript (even though it's only a keyword in certain contexts), I'm going to use later
as the name of the function to avoid confusion.
Using native promises (or a faithful polyfill) it would look like this:
function later(delay) {
return new Promise(function(resolve) {
setTimeout(resolve, delay);
});
}
Note that that assumes a version of setTimeout
that's compliant with the definition for browsers where setTimeout
doesn't pass any arguments to the callback unless you give them after the interval (this may not be true in non-browser environments, and didn't used to be true on Firefox, but is now; it's true on Chrome and even back on IE8).
If you want your function to optionally pass a resolution value, on any vaguely-modern browser that allows you to give extra arguments to setTimeout
after the delay and then passes those to the callback when called, you can do this (current Firefox and Chrome; IE11+, presumably Edge; not IE8 or IE9, no idea about IE10):
function later(delay, value) {
return new Promise(function(resolve) {
setTimeout(resolve, delay, value); // Note the order, `delay` before `value`
/* Or for outdated browsers that don't support doing that:
setTimeout(function() {
resolve(value);
}, delay);
Or alternately:
setTimeout(resolve.bind(null, value), delay);
*/
});
}
If you're using ES2015+ arrow functions, that can be more concise:
function later(delay, value) {
return new Promise(resolve => setTimeout(resolve, delay, value));
}
or even
const later = (delay, value) =>
new Promise(resolve => setTimeout(resolve, delay, value));
If you want to make it possible to cancel the timeout, you can't just return a promise from later
, because promises can't be cancelled.
But we can easily return an object with a cancel
method and an accessor for the promise, and reject the promise on cancel:
const later = (delay, value) => {
let timer = 0;
let reject = null;
const promise = new Promise((resolve, _reject) => {
reject = _reject;
timer = setTimeout(resolve, delay, value);
});
return {
get promise() { return promise; },
cancel() {
if (timer) {
clearTimeout(timer);
timer = 0;
reject();
reject = null;
}
}
};
};
Live Example:
const later = (delay, value) => {_x000D_
let timer = 0;_x000D_
let reject = null;_x000D_
const promise = new Promise((resolve, _reject) => {_x000D_
reject = _reject;_x000D_
timer = setTimeout(resolve, delay, value);_x000D_
});_x000D_
return {_x000D_
get promise() { return promise; },_x000D_
cancel() {_x000D_
if (timer) {_x000D_
clearTimeout(timer);_x000D_
timer = 0;_x000D_
reject();_x000D_
reject = null;_x000D_
}_x000D_
}_x000D_
};_x000D_
};_x000D_
_x000D_
const l1 = later(100, "l1");_x000D_
l1.promise_x000D_
.then(msg => { console.log(msg); })_x000D_
.catch(() => { console.log("l1 cancelled"); });_x000D_
_x000D_
const l2 = later(200, "l2");_x000D_
l2.promise_x000D_
.then(msg => { console.log(msg); })_x000D_
.catch(() => { console.log("l2 cancelled"); });_x000D_
setTimeout(() => {_x000D_
l2.cancel();_x000D_
}, 150);
_x000D_
Usually you'll have a promise library (one you write yourself, or one of the several out there). That library will usually have an object that you can create and later "resolve," and that object will have a "promise" you can get from it.
Then later
would tend to look something like this:
function later() {
var p = new PromiseThingy();
setTimeout(function() {
p.resolve();
}, 2000);
return p.promise(); // Note we're not returning `p` directly
}
In a comment on the question, I asked:
Are you trying to create your own promise library?
and you said
I wasn't but I guess now that's actually what I was trying to understand. That how a library would do it
To aid that understanding, here's a very very basic example, which isn't remotely Promises-A compliant: Live Copy
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Very basic promises</title>
</head>
<body>
<script>
(function() {
// ==== Very basic promise implementation, not remotely Promises-A compliant, just a very basic example
var PromiseThingy = (function() {
// Internal - trigger a callback
function triggerCallback(callback, promise) {
try {
callback(promise.resolvedValue);
}
catch (e) {
}
}
// The internal promise constructor, we don't share this
function Promise() {
this.callbacks = [];
}
// Register a 'then' callback
Promise.prototype.then = function(callback) {
var thispromise = this;
if (!this.resolved) {
// Not resolved yet, remember the callback
this.callbacks.push(callback);
}
else {
// Resolved; trigger callback right away, but always async
setTimeout(function() {
triggerCallback(callback, thispromise);
}, 0);
}
return this;
};
// Our public constructor for PromiseThingys
function PromiseThingy() {
this.p = new Promise();
}
// Resolve our underlying promise
PromiseThingy.prototype.resolve = function(value) {
var n;
if (!this.p.resolved) {
this.p.resolved = true;
this.p.resolvedValue = value;
for (n = 0; n < this.p.callbacks.length; ++n) {
triggerCallback(this.p.callbacks[n], this.p);
}
}
};
// Get our underlying promise
PromiseThingy.prototype.promise = function() {
return this.p;
};
// Export public
return PromiseThingy;
})();
// ==== Using it
function later() {
var p = new PromiseThingy();
setTimeout(function() {
p.resolve();
}, 2000);
return p.promise(); // Note we're not returning `p` directly
}
display("Start " + Date.now());
later().then(function() {
display("Done1 " + Date.now());
}).then(function() {
display("Done2 " + Date.now());
});
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>
The button
element has a default type of submit
.
You can make it do nothing by setting a type of button
:
<button type="button">Cancel changes</button>
if user find particular array elements then use below code same as integer value.
var arrelemnts = ["sachin", "test", "test1", "test3"]
if arrelemnts.contains("test"){
print("found") }else{
print("not found") }
POSIX recognizes multiple variations on regular expressions - basic regular expressions (BRE) and extended regular expressions (ERE). And even then, there are quirks because of the historical implementations of the utilities standardized by POSIX.
There isn't a simple rule for when to use which notation, or even which notation a given command uses.
Check out Jeff Friedl's Mastering Regular Expressions book.